1 //===-- LLParser.cpp - Parser Class ---------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the parser class for .ll files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/AsmParser/LLParser.h" 14 #include "llvm/ADT/APSInt.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/AsmParser/LLToken.h" 20 #include "llvm/AsmParser/SlotMapping.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/IR/Argument.h" 23 #include "llvm/IR/AutoUpgrade.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/CallingConv.h" 26 #include "llvm/IR/Comdat.h" 27 #include "llvm/IR/ConstantRange.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DebugInfoMetadata.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/GlobalIFunc.h" 33 #include "llvm/IR/GlobalObject.h" 34 #include "llvm/IR/InlineAsm.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/IR/LLVMContext.h" 38 #include "llvm/IR/Metadata.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/IR/Value.h" 41 #include "llvm/IR/ValueSymbolTable.h" 42 #include "llvm/Support/Casting.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/MathExtras.h" 45 #include "llvm/Support/SaveAndRestore.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstring> 50 #include <iterator> 51 #include <vector> 52 53 using namespace llvm; 54 55 static std::string getTypeString(Type *T) { 56 std::string Result; 57 raw_string_ostream Tmp(Result); 58 Tmp << *T; 59 return Tmp.str(); 60 } 61 62 /// Run: module ::= toplevelentity* 63 bool LLParser::Run(bool UpgradeDebugInfo, 64 DataLayoutCallbackTy DataLayoutCallback) { 65 // Prime the lexer. 66 Lex.Lex(); 67 68 if (Context.shouldDiscardValueNames()) 69 return error( 70 Lex.getLoc(), 71 "Can't read textual IR with a Context that discards named Values"); 72 73 if (M) { 74 if (parseTargetDefinitions()) 75 return true; 76 77 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple())) 78 M->setDataLayout(*LayoutOverride); 79 } 80 81 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) || 82 validateEndOfIndex(); 83 } 84 85 bool LLParser::parseStandaloneConstantValue(Constant *&C, 86 const SlotMapping *Slots) { 87 restoreParsingState(Slots); 88 Lex.Lex(); 89 90 Type *Ty = nullptr; 91 if (parseType(Ty) || parseConstantValue(Ty, C)) 92 return true; 93 if (Lex.getKind() != lltok::Eof) 94 return error(Lex.getLoc(), "expected end of string"); 95 return false; 96 } 97 98 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read, 99 const SlotMapping *Slots) { 100 restoreParsingState(Slots); 101 Lex.Lex(); 102 103 Read = 0; 104 SMLoc Start = Lex.getLoc(); 105 Ty = nullptr; 106 if (parseType(Ty)) 107 return true; 108 SMLoc End = Lex.getLoc(); 109 Read = End.getPointer() - Start.getPointer(); 110 111 return false; 112 } 113 114 void LLParser::restoreParsingState(const SlotMapping *Slots) { 115 if (!Slots) 116 return; 117 NumberedVals = Slots->GlobalValues; 118 NumberedMetadata = Slots->MetadataNodes; 119 for (const auto &I : Slots->NamedTypes) 120 NamedTypes.insert( 121 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy()))); 122 for (const auto &I : Slots->Types) 123 NumberedTypes.insert( 124 std::make_pair(I.first, std::make_pair(I.second, LocTy()))); 125 } 126 127 /// validateEndOfModule - Do final validity and basic correctness checks at the 128 /// end of the module. 129 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) { 130 if (!M) 131 return false; 132 // Handle any function attribute group forward references. 133 for (const auto &RAG : ForwardRefAttrGroups) { 134 Value *V = RAG.first; 135 const std::vector<unsigned> &Attrs = RAG.second; 136 AttrBuilder B; 137 138 for (const auto &Attr : Attrs) 139 B.merge(NumberedAttrBuilders[Attr]); 140 141 if (Function *Fn = dyn_cast<Function>(V)) { 142 AttributeList AS = Fn->getAttributes(); 143 AttrBuilder FnAttrs(AS.getFnAttrs()); 144 AS = AS.removeFnAttributes(Context); 145 146 FnAttrs.merge(B); 147 148 // If the alignment was parsed as an attribute, move to the alignment 149 // field. 150 if (FnAttrs.hasAlignmentAttr()) { 151 Fn->setAlignment(FnAttrs.getAlignment()); 152 FnAttrs.removeAttribute(Attribute::Alignment); 153 } 154 155 AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs)); 156 Fn->setAttributes(AS); 157 } else if (CallInst *CI = dyn_cast<CallInst>(V)) { 158 AttributeList AS = CI->getAttributes(); 159 AttrBuilder FnAttrs(AS.getFnAttrs()); 160 AS = AS.removeFnAttributes(Context); 161 FnAttrs.merge(B); 162 AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs)); 163 CI->setAttributes(AS); 164 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) { 165 AttributeList AS = II->getAttributes(); 166 AttrBuilder FnAttrs(AS.getFnAttrs()); 167 AS = AS.removeFnAttributes(Context); 168 FnAttrs.merge(B); 169 AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs)); 170 II->setAttributes(AS); 171 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) { 172 AttributeList AS = CBI->getAttributes(); 173 AttrBuilder FnAttrs(AS.getFnAttrs()); 174 AS = AS.removeFnAttributes(Context); 175 FnAttrs.merge(B); 176 AS = AS.addFnAttributes(Context, AttributeSet::get(Context, FnAttrs)); 177 CBI->setAttributes(AS); 178 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) { 179 AttrBuilder Attrs(GV->getAttributes()); 180 Attrs.merge(B); 181 GV->setAttributes(AttributeSet::get(Context,Attrs)); 182 } else { 183 llvm_unreachable("invalid object with forward attribute group reference"); 184 } 185 } 186 187 // If there are entries in ForwardRefBlockAddresses at this point, the 188 // function was never defined. 189 if (!ForwardRefBlockAddresses.empty()) 190 return error(ForwardRefBlockAddresses.begin()->first.Loc, 191 "expected function name in blockaddress"); 192 193 for (const auto &NT : NumberedTypes) 194 if (NT.second.second.isValid()) 195 return error(NT.second.second, 196 "use of undefined type '%" + Twine(NT.first) + "'"); 197 198 for (StringMap<std::pair<Type*, LocTy> >::iterator I = 199 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) 200 if (I->second.second.isValid()) 201 return error(I->second.second, 202 "use of undefined type named '" + I->getKey() + "'"); 203 204 if (!ForwardRefComdats.empty()) 205 return error(ForwardRefComdats.begin()->second, 206 "use of undefined comdat '$" + 207 ForwardRefComdats.begin()->first + "'"); 208 209 if (!ForwardRefVals.empty()) 210 return error(ForwardRefVals.begin()->second.second, 211 "use of undefined value '@" + ForwardRefVals.begin()->first + 212 "'"); 213 214 if (!ForwardRefValIDs.empty()) 215 return error(ForwardRefValIDs.begin()->second.second, 216 "use of undefined value '@" + 217 Twine(ForwardRefValIDs.begin()->first) + "'"); 218 219 if (!ForwardRefMDNodes.empty()) 220 return error(ForwardRefMDNodes.begin()->second.second, 221 "use of undefined metadata '!" + 222 Twine(ForwardRefMDNodes.begin()->first) + "'"); 223 224 // Resolve metadata cycles. 225 for (auto &N : NumberedMetadata) { 226 if (N.second && !N.second->isResolved()) 227 N.second->resolveCycles(); 228 } 229 230 for (auto *Inst : InstsWithTBAATag) { 231 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa); 232 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag"); 233 auto *UpgradedMD = UpgradeTBAANode(*MD); 234 if (MD != UpgradedMD) 235 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD); 236 } 237 238 // Look for intrinsic functions and CallInst that need to be upgraded. We use 239 // make_early_inc_range here because we may remove some functions. 240 for (Function &F : llvm::make_early_inc_range(*M)) 241 UpgradeCallsToIntrinsic(&F); 242 243 // Some types could be renamed during loading if several modules are 244 // loaded in the same LLVMContext (LTO scenario). In this case we should 245 // remangle intrinsics names as well. 246 for (Function &F : llvm::make_early_inc_range(*M)) { 247 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) { 248 F.replaceAllUsesWith(Remangled.getValue()); 249 F.eraseFromParent(); 250 } 251 } 252 253 if (UpgradeDebugInfo) 254 llvm::UpgradeDebugInfo(*M); 255 256 UpgradeModuleFlags(*M); 257 UpgradeSectionAttributes(*M); 258 259 if (!Slots) 260 return false; 261 // Initialize the slot mapping. 262 // Because by this point we've parsed and validated everything, we can "steal" 263 // the mapping from LLParser as it doesn't need it anymore. 264 Slots->GlobalValues = std::move(NumberedVals); 265 Slots->MetadataNodes = std::move(NumberedMetadata); 266 for (const auto &I : NamedTypes) 267 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first)); 268 for (const auto &I : NumberedTypes) 269 Slots->Types.insert(std::make_pair(I.first, I.second.first)); 270 271 return false; 272 } 273 274 /// Do final validity and basic correctness checks at the end of the index. 275 bool LLParser::validateEndOfIndex() { 276 if (!Index) 277 return false; 278 279 if (!ForwardRefValueInfos.empty()) 280 return error(ForwardRefValueInfos.begin()->second.front().second, 281 "use of undefined summary '^" + 282 Twine(ForwardRefValueInfos.begin()->first) + "'"); 283 284 if (!ForwardRefAliasees.empty()) 285 return error(ForwardRefAliasees.begin()->second.front().second, 286 "use of undefined summary '^" + 287 Twine(ForwardRefAliasees.begin()->first) + "'"); 288 289 if (!ForwardRefTypeIds.empty()) 290 return error(ForwardRefTypeIds.begin()->second.front().second, 291 "use of undefined type id summary '^" + 292 Twine(ForwardRefTypeIds.begin()->first) + "'"); 293 294 return false; 295 } 296 297 //===----------------------------------------------------------------------===// 298 // Top-Level Entities 299 //===----------------------------------------------------------------------===// 300 301 bool LLParser::parseTargetDefinitions() { 302 while (true) { 303 switch (Lex.getKind()) { 304 case lltok::kw_target: 305 if (parseTargetDefinition()) 306 return true; 307 break; 308 case lltok::kw_source_filename: 309 if (parseSourceFileName()) 310 return true; 311 break; 312 default: 313 return false; 314 } 315 } 316 } 317 318 bool LLParser::parseTopLevelEntities() { 319 // If there is no Module, then parse just the summary index entries. 320 if (!M) { 321 while (true) { 322 switch (Lex.getKind()) { 323 case lltok::Eof: 324 return false; 325 case lltok::SummaryID: 326 if (parseSummaryEntry()) 327 return true; 328 break; 329 case lltok::kw_source_filename: 330 if (parseSourceFileName()) 331 return true; 332 break; 333 default: 334 // Skip everything else 335 Lex.Lex(); 336 } 337 } 338 } 339 while (true) { 340 switch (Lex.getKind()) { 341 default: 342 return tokError("expected top-level entity"); 343 case lltok::Eof: return false; 344 case lltok::kw_declare: 345 if (parseDeclare()) 346 return true; 347 break; 348 case lltok::kw_define: 349 if (parseDefine()) 350 return true; 351 break; 352 case lltok::kw_module: 353 if (parseModuleAsm()) 354 return true; 355 break; 356 case lltok::LocalVarID: 357 if (parseUnnamedType()) 358 return true; 359 break; 360 case lltok::LocalVar: 361 if (parseNamedType()) 362 return true; 363 break; 364 case lltok::GlobalID: 365 if (parseUnnamedGlobal()) 366 return true; 367 break; 368 case lltok::GlobalVar: 369 if (parseNamedGlobal()) 370 return true; 371 break; 372 case lltok::ComdatVar: if (parseComdat()) return true; break; 373 case lltok::exclaim: 374 if (parseStandaloneMetadata()) 375 return true; 376 break; 377 case lltok::SummaryID: 378 if (parseSummaryEntry()) 379 return true; 380 break; 381 case lltok::MetadataVar: 382 if (parseNamedMetadata()) 383 return true; 384 break; 385 case lltok::kw_attributes: 386 if (parseUnnamedAttrGrp()) 387 return true; 388 break; 389 case lltok::kw_uselistorder: 390 if (parseUseListOrder()) 391 return true; 392 break; 393 case lltok::kw_uselistorder_bb: 394 if (parseUseListOrderBB()) 395 return true; 396 break; 397 } 398 } 399 } 400 401 /// toplevelentity 402 /// ::= 'module' 'asm' STRINGCONSTANT 403 bool LLParser::parseModuleAsm() { 404 assert(Lex.getKind() == lltok::kw_module); 405 Lex.Lex(); 406 407 std::string AsmStr; 408 if (parseToken(lltok::kw_asm, "expected 'module asm'") || 409 parseStringConstant(AsmStr)) 410 return true; 411 412 M->appendModuleInlineAsm(AsmStr); 413 return false; 414 } 415 416 /// toplevelentity 417 /// ::= 'target' 'triple' '=' STRINGCONSTANT 418 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT 419 bool LLParser::parseTargetDefinition() { 420 assert(Lex.getKind() == lltok::kw_target); 421 std::string Str; 422 switch (Lex.Lex()) { 423 default: 424 return tokError("unknown target property"); 425 case lltok::kw_triple: 426 Lex.Lex(); 427 if (parseToken(lltok::equal, "expected '=' after target triple") || 428 parseStringConstant(Str)) 429 return true; 430 M->setTargetTriple(Str); 431 return false; 432 case lltok::kw_datalayout: 433 Lex.Lex(); 434 if (parseToken(lltok::equal, "expected '=' after target datalayout") || 435 parseStringConstant(Str)) 436 return true; 437 M->setDataLayout(Str); 438 return false; 439 } 440 } 441 442 /// toplevelentity 443 /// ::= 'source_filename' '=' STRINGCONSTANT 444 bool LLParser::parseSourceFileName() { 445 assert(Lex.getKind() == lltok::kw_source_filename); 446 Lex.Lex(); 447 if (parseToken(lltok::equal, "expected '=' after source_filename") || 448 parseStringConstant(SourceFileName)) 449 return true; 450 if (M) 451 M->setSourceFileName(SourceFileName); 452 return false; 453 } 454 455 /// parseUnnamedType: 456 /// ::= LocalVarID '=' 'type' type 457 bool LLParser::parseUnnamedType() { 458 LocTy TypeLoc = Lex.getLoc(); 459 unsigned TypeID = Lex.getUIntVal(); 460 Lex.Lex(); // eat LocalVarID; 461 462 if (parseToken(lltok::equal, "expected '=' after name") || 463 parseToken(lltok::kw_type, "expected 'type' after '='")) 464 return true; 465 466 Type *Result = nullptr; 467 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result)) 468 return true; 469 470 if (!isa<StructType>(Result)) { 471 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID]; 472 if (Entry.first) 473 return error(TypeLoc, "non-struct types may not be recursive"); 474 Entry.first = Result; 475 Entry.second = SMLoc(); 476 } 477 478 return false; 479 } 480 481 /// toplevelentity 482 /// ::= LocalVar '=' 'type' type 483 bool LLParser::parseNamedType() { 484 std::string Name = Lex.getStrVal(); 485 LocTy NameLoc = Lex.getLoc(); 486 Lex.Lex(); // eat LocalVar. 487 488 if (parseToken(lltok::equal, "expected '=' after name") || 489 parseToken(lltok::kw_type, "expected 'type' after name")) 490 return true; 491 492 Type *Result = nullptr; 493 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result)) 494 return true; 495 496 if (!isa<StructType>(Result)) { 497 std::pair<Type*, LocTy> &Entry = NamedTypes[Name]; 498 if (Entry.first) 499 return error(NameLoc, "non-struct types may not be recursive"); 500 Entry.first = Result; 501 Entry.second = SMLoc(); 502 } 503 504 return false; 505 } 506 507 /// toplevelentity 508 /// ::= 'declare' FunctionHeader 509 bool LLParser::parseDeclare() { 510 assert(Lex.getKind() == lltok::kw_declare); 511 Lex.Lex(); 512 513 std::vector<std::pair<unsigned, MDNode *>> MDs; 514 while (Lex.getKind() == lltok::MetadataVar) { 515 unsigned MDK; 516 MDNode *N; 517 if (parseMetadataAttachment(MDK, N)) 518 return true; 519 MDs.push_back({MDK, N}); 520 } 521 522 Function *F; 523 if (parseFunctionHeader(F, false)) 524 return true; 525 for (auto &MD : MDs) 526 F->addMetadata(MD.first, *MD.second); 527 return false; 528 } 529 530 /// toplevelentity 531 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ... 532 bool LLParser::parseDefine() { 533 assert(Lex.getKind() == lltok::kw_define); 534 Lex.Lex(); 535 536 Function *F; 537 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) || 538 parseFunctionBody(*F); 539 } 540 541 /// parseGlobalType 542 /// ::= 'constant' 543 /// ::= 'global' 544 bool LLParser::parseGlobalType(bool &IsConstant) { 545 if (Lex.getKind() == lltok::kw_constant) 546 IsConstant = true; 547 else if (Lex.getKind() == lltok::kw_global) 548 IsConstant = false; 549 else { 550 IsConstant = false; 551 return tokError("expected 'global' or 'constant'"); 552 } 553 Lex.Lex(); 554 return false; 555 } 556 557 bool LLParser::parseOptionalUnnamedAddr( 558 GlobalVariable::UnnamedAddr &UnnamedAddr) { 559 if (EatIfPresent(lltok::kw_unnamed_addr)) 560 UnnamedAddr = GlobalValue::UnnamedAddr::Global; 561 else if (EatIfPresent(lltok::kw_local_unnamed_addr)) 562 UnnamedAddr = GlobalValue::UnnamedAddr::Local; 563 else 564 UnnamedAddr = GlobalValue::UnnamedAddr::None; 565 return false; 566 } 567 568 /// parseUnnamedGlobal: 569 /// OptionalVisibility (ALIAS | IFUNC) ... 570 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 571 /// OptionalDLLStorageClass 572 /// ... -> global variable 573 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ... 574 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier 575 /// OptionalVisibility 576 /// OptionalDLLStorageClass 577 /// ... -> global variable 578 bool LLParser::parseUnnamedGlobal() { 579 unsigned VarID = NumberedVals.size(); 580 std::string Name; 581 LocTy NameLoc = Lex.getLoc(); 582 583 // Handle the GlobalID form. 584 if (Lex.getKind() == lltok::GlobalID) { 585 if (Lex.getUIntVal() != VarID) 586 return error(Lex.getLoc(), 587 "variable expected to be numbered '%" + Twine(VarID) + "'"); 588 Lex.Lex(); // eat GlobalID; 589 590 if (parseToken(lltok::equal, "expected '=' after name")) 591 return true; 592 } 593 594 bool HasLinkage; 595 unsigned Linkage, Visibility, DLLStorageClass; 596 bool DSOLocal; 597 GlobalVariable::ThreadLocalMode TLM; 598 GlobalVariable::UnnamedAddr UnnamedAddr; 599 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 600 DSOLocal) || 601 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) 602 return true; 603 604 switch (Lex.getKind()) { 605 default: 606 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 607 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 608 case lltok::kw_alias: 609 case lltok::kw_ifunc: 610 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility, 611 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 612 } 613 } 614 615 /// parseNamedGlobal: 616 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ... 617 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 618 /// OptionalVisibility OptionalDLLStorageClass 619 /// ... -> global variable 620 bool LLParser::parseNamedGlobal() { 621 assert(Lex.getKind() == lltok::GlobalVar); 622 LocTy NameLoc = Lex.getLoc(); 623 std::string Name = Lex.getStrVal(); 624 Lex.Lex(); 625 626 bool HasLinkage; 627 unsigned Linkage, Visibility, DLLStorageClass; 628 bool DSOLocal; 629 GlobalVariable::ThreadLocalMode TLM; 630 GlobalVariable::UnnamedAddr UnnamedAddr; 631 if (parseToken(lltok::equal, "expected '=' in global variable") || 632 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 633 DSOLocal) || 634 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr)) 635 return true; 636 637 switch (Lex.getKind()) { 638 default: 639 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility, 640 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 641 case lltok::kw_alias: 642 case lltok::kw_ifunc: 643 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility, 644 DLLStorageClass, DSOLocal, TLM, UnnamedAddr); 645 } 646 } 647 648 bool LLParser::parseComdat() { 649 assert(Lex.getKind() == lltok::ComdatVar); 650 std::string Name = Lex.getStrVal(); 651 LocTy NameLoc = Lex.getLoc(); 652 Lex.Lex(); 653 654 if (parseToken(lltok::equal, "expected '=' here")) 655 return true; 656 657 if (parseToken(lltok::kw_comdat, "expected comdat keyword")) 658 return tokError("expected comdat type"); 659 660 Comdat::SelectionKind SK; 661 switch (Lex.getKind()) { 662 default: 663 return tokError("unknown selection kind"); 664 case lltok::kw_any: 665 SK = Comdat::Any; 666 break; 667 case lltok::kw_exactmatch: 668 SK = Comdat::ExactMatch; 669 break; 670 case lltok::kw_largest: 671 SK = Comdat::Largest; 672 break; 673 case lltok::kw_nodeduplicate: 674 SK = Comdat::NoDeduplicate; 675 break; 676 case lltok::kw_samesize: 677 SK = Comdat::SameSize; 678 break; 679 } 680 Lex.Lex(); 681 682 // See if the comdat was forward referenced, if so, use the comdat. 683 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 684 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 685 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name)) 686 return error(NameLoc, "redefinition of comdat '$" + Name + "'"); 687 688 Comdat *C; 689 if (I != ComdatSymTab.end()) 690 C = &I->second; 691 else 692 C = M->getOrInsertComdat(Name); 693 C->setSelectionKind(SK); 694 695 return false; 696 } 697 698 // MDString: 699 // ::= '!' STRINGCONSTANT 700 bool LLParser::parseMDString(MDString *&Result) { 701 std::string Str; 702 if (parseStringConstant(Str)) 703 return true; 704 Result = MDString::get(Context, Str); 705 return false; 706 } 707 708 // MDNode: 709 // ::= '!' MDNodeNumber 710 bool LLParser::parseMDNodeID(MDNode *&Result) { 711 // !{ ..., !42, ... } 712 LocTy IDLoc = Lex.getLoc(); 713 unsigned MID = 0; 714 if (parseUInt32(MID)) 715 return true; 716 717 // If not a forward reference, just return it now. 718 if (NumberedMetadata.count(MID)) { 719 Result = NumberedMetadata[MID]; 720 return false; 721 } 722 723 // Otherwise, create MDNode forward reference. 724 auto &FwdRef = ForwardRefMDNodes[MID]; 725 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc); 726 727 Result = FwdRef.first.get(); 728 NumberedMetadata[MID].reset(Result); 729 return false; 730 } 731 732 /// parseNamedMetadata: 733 /// !foo = !{ !1, !2 } 734 bool LLParser::parseNamedMetadata() { 735 assert(Lex.getKind() == lltok::MetadataVar); 736 std::string Name = Lex.getStrVal(); 737 Lex.Lex(); 738 739 if (parseToken(lltok::equal, "expected '=' here") || 740 parseToken(lltok::exclaim, "Expected '!' here") || 741 parseToken(lltok::lbrace, "Expected '{' here")) 742 return true; 743 744 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name); 745 if (Lex.getKind() != lltok::rbrace) 746 do { 747 MDNode *N = nullptr; 748 // parse DIExpressions inline as a special case. They are still MDNodes, 749 // so they can still appear in named metadata. Remove this logic if they 750 // become plain Metadata. 751 if (Lex.getKind() == lltok::MetadataVar && 752 Lex.getStrVal() == "DIExpression") { 753 if (parseDIExpression(N, /*IsDistinct=*/false)) 754 return true; 755 // DIArgLists should only appear inline in a function, as they may 756 // contain LocalAsMetadata arguments which require a function context. 757 } else if (Lex.getKind() == lltok::MetadataVar && 758 Lex.getStrVal() == "DIArgList") { 759 return tokError("found DIArgList outside of function"); 760 } else if (parseToken(lltok::exclaim, "Expected '!' here") || 761 parseMDNodeID(N)) { 762 return true; 763 } 764 NMD->addOperand(N); 765 } while (EatIfPresent(lltok::comma)); 766 767 return parseToken(lltok::rbrace, "expected end of metadata node"); 768 } 769 770 /// parseStandaloneMetadata: 771 /// !42 = !{...} 772 bool LLParser::parseStandaloneMetadata() { 773 assert(Lex.getKind() == lltok::exclaim); 774 Lex.Lex(); 775 unsigned MetadataID = 0; 776 777 MDNode *Init; 778 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here")) 779 return true; 780 781 // Detect common error, from old metadata syntax. 782 if (Lex.getKind() == lltok::Type) 783 return tokError("unexpected type in metadata definition"); 784 785 bool IsDistinct = EatIfPresent(lltok::kw_distinct); 786 if (Lex.getKind() == lltok::MetadataVar) { 787 if (parseSpecializedMDNode(Init, IsDistinct)) 788 return true; 789 } else if (parseToken(lltok::exclaim, "Expected '!' here") || 790 parseMDTuple(Init, IsDistinct)) 791 return true; 792 793 // See if this was forward referenced, if so, handle it. 794 auto FI = ForwardRefMDNodes.find(MetadataID); 795 if (FI != ForwardRefMDNodes.end()) { 796 FI->second.first->replaceAllUsesWith(Init); 797 ForwardRefMDNodes.erase(FI); 798 799 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work"); 800 } else { 801 if (NumberedMetadata.count(MetadataID)) 802 return tokError("Metadata id is already used"); 803 NumberedMetadata[MetadataID].reset(Init); 804 } 805 806 return false; 807 } 808 809 // Skips a single module summary entry. 810 bool LLParser::skipModuleSummaryEntry() { 811 // Each module summary entry consists of a tag for the entry 812 // type, followed by a colon, then the fields which may be surrounded by 813 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing 814 // support is in place we will look for the tokens corresponding to the 815 // expected tags. 816 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module && 817 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags && 818 Lex.getKind() != lltok::kw_blockcount) 819 return tokError( 820 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the " 821 "start of summary entry"); 822 if (Lex.getKind() == lltok::kw_flags) 823 return parseSummaryIndexFlags(); 824 if (Lex.getKind() == lltok::kw_blockcount) 825 return parseBlockCount(); 826 Lex.Lex(); 827 if (parseToken(lltok::colon, "expected ':' at start of summary entry") || 828 parseToken(lltok::lparen, "expected '(' at start of summary entry")) 829 return true; 830 // Now walk through the parenthesized entry, until the number of open 831 // parentheses goes back down to 0 (the first '(' was parsed above). 832 unsigned NumOpenParen = 1; 833 do { 834 switch (Lex.getKind()) { 835 case lltok::lparen: 836 NumOpenParen++; 837 break; 838 case lltok::rparen: 839 NumOpenParen--; 840 break; 841 case lltok::Eof: 842 return tokError("found end of file while parsing summary entry"); 843 default: 844 // Skip everything in between parentheses. 845 break; 846 } 847 Lex.Lex(); 848 } while (NumOpenParen > 0); 849 return false; 850 } 851 852 /// SummaryEntry 853 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry 854 bool LLParser::parseSummaryEntry() { 855 assert(Lex.getKind() == lltok::SummaryID); 856 unsigned SummaryID = Lex.getUIntVal(); 857 858 // For summary entries, colons should be treated as distinct tokens, 859 // not an indication of the end of a label token. 860 Lex.setIgnoreColonInIdentifiers(true); 861 862 Lex.Lex(); 863 if (parseToken(lltok::equal, "expected '=' here")) 864 return true; 865 866 // If we don't have an index object, skip the summary entry. 867 if (!Index) 868 return skipModuleSummaryEntry(); 869 870 bool result = false; 871 switch (Lex.getKind()) { 872 case lltok::kw_gv: 873 result = parseGVEntry(SummaryID); 874 break; 875 case lltok::kw_module: 876 result = parseModuleEntry(SummaryID); 877 break; 878 case lltok::kw_typeid: 879 result = parseTypeIdEntry(SummaryID); 880 break; 881 case lltok::kw_typeidCompatibleVTable: 882 result = parseTypeIdCompatibleVtableEntry(SummaryID); 883 break; 884 case lltok::kw_flags: 885 result = parseSummaryIndexFlags(); 886 break; 887 case lltok::kw_blockcount: 888 result = parseBlockCount(); 889 break; 890 default: 891 result = error(Lex.getLoc(), "unexpected summary kind"); 892 break; 893 } 894 Lex.setIgnoreColonInIdentifiers(false); 895 return result; 896 } 897 898 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) { 899 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) || 900 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility; 901 } 902 903 // If there was an explicit dso_local, update GV. In the absence of an explicit 904 // dso_local we keep the default value. 905 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) { 906 if (DSOLocal) 907 GV.setDSOLocal(true); 908 } 909 910 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1, 911 Type *Ty2) { 912 std::string ErrString; 913 raw_string_ostream ErrOS(ErrString); 914 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")"; 915 return ErrOS.str(); 916 } 917 918 /// parseAliasOrIFunc: 919 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 920 /// OptionalVisibility OptionalDLLStorageClass 921 /// OptionalThreadLocal OptionalUnnamedAddr 922 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs* 923 /// 924 /// AliaseeOrResolver 925 /// ::= TypeAndValue 926 /// 927 /// SymbolAttrs 928 /// ::= ',' 'partition' StringConstant 929 /// 930 /// Everything through OptionalUnnamedAddr has already been parsed. 931 /// 932 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc, 933 unsigned L, unsigned Visibility, 934 unsigned DLLStorageClass, bool DSOLocal, 935 GlobalVariable::ThreadLocalMode TLM, 936 GlobalVariable::UnnamedAddr UnnamedAddr) { 937 bool IsAlias; 938 if (Lex.getKind() == lltok::kw_alias) 939 IsAlias = true; 940 else if (Lex.getKind() == lltok::kw_ifunc) 941 IsAlias = false; 942 else 943 llvm_unreachable("Not an alias or ifunc!"); 944 Lex.Lex(); 945 946 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L; 947 948 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage)) 949 return error(NameLoc, "invalid linkage type for alias"); 950 951 if (!isValidVisibilityForLinkage(Visibility, L)) 952 return error(NameLoc, 953 "symbol with local linkage must have default visibility"); 954 955 Type *Ty; 956 LocTy ExplicitTypeLoc = Lex.getLoc(); 957 if (parseType(Ty) || 958 parseToken(lltok::comma, "expected comma after alias or ifunc's type")) 959 return true; 960 961 Constant *Aliasee; 962 LocTy AliaseeLoc = Lex.getLoc(); 963 if (Lex.getKind() != lltok::kw_bitcast && 964 Lex.getKind() != lltok::kw_getelementptr && 965 Lex.getKind() != lltok::kw_addrspacecast && 966 Lex.getKind() != lltok::kw_inttoptr) { 967 if (parseGlobalTypeAndValue(Aliasee)) 968 return true; 969 } else { 970 // The bitcast dest type is not present, it is implied by the dest type. 971 ValID ID; 972 if (parseValID(ID, /*PFS=*/nullptr)) 973 return true; 974 if (ID.Kind != ValID::t_Constant) 975 return error(AliaseeLoc, "invalid aliasee"); 976 Aliasee = ID.ConstantVal; 977 } 978 979 Type *AliaseeType = Aliasee->getType(); 980 auto *PTy = dyn_cast<PointerType>(AliaseeType); 981 if (!PTy) 982 return error(AliaseeLoc, "An alias or ifunc must have pointer type"); 983 unsigned AddrSpace = PTy->getAddressSpace(); 984 985 if (IsAlias && !PTy->isOpaqueOrPointeeTypeMatches(Ty)) { 986 return error( 987 ExplicitTypeLoc, 988 typeComparisonErrorMessage( 989 "explicit pointee type doesn't match operand's pointee type", Ty, 990 PTy->getElementType())); 991 } 992 993 if (!IsAlias && !PTy->getElementType()->isFunctionTy()) { 994 return error(ExplicitTypeLoc, 995 "explicit pointee type should be a function type"); 996 } 997 998 GlobalValue *GVal = nullptr; 999 1000 // See if the alias was forward referenced, if so, prepare to replace the 1001 // forward reference. 1002 if (!Name.empty()) { 1003 auto I = ForwardRefVals.find(Name); 1004 if (I != ForwardRefVals.end()) { 1005 GVal = I->second.first; 1006 ForwardRefVals.erase(Name); 1007 } else if (M->getNamedValue(Name)) { 1008 return error(NameLoc, "redefinition of global '@" + Name + "'"); 1009 } 1010 } else { 1011 auto I = ForwardRefValIDs.find(NumberedVals.size()); 1012 if (I != ForwardRefValIDs.end()) { 1013 GVal = I->second.first; 1014 ForwardRefValIDs.erase(I); 1015 } 1016 } 1017 1018 // Okay, create the alias/ifunc but do not insert it into the module yet. 1019 std::unique_ptr<GlobalAlias> GA; 1020 std::unique_ptr<GlobalIFunc> GI; 1021 GlobalValue *GV; 1022 if (IsAlias) { 1023 GA.reset(GlobalAlias::create(Ty, AddrSpace, 1024 (GlobalValue::LinkageTypes)Linkage, Name, 1025 Aliasee, /*Parent*/ nullptr)); 1026 GV = GA.get(); 1027 } else { 1028 GI.reset(GlobalIFunc::create(Ty, AddrSpace, 1029 (GlobalValue::LinkageTypes)Linkage, Name, 1030 Aliasee, /*Parent*/ nullptr)); 1031 GV = GI.get(); 1032 } 1033 GV->setThreadLocalMode(TLM); 1034 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 1035 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 1036 GV->setUnnamedAddr(UnnamedAddr); 1037 maybeSetDSOLocal(DSOLocal, *GV); 1038 1039 // At this point we've parsed everything except for the IndirectSymbolAttrs. 1040 // Now parse them if there are any. 1041 while (Lex.getKind() == lltok::comma) { 1042 Lex.Lex(); 1043 1044 if (Lex.getKind() == lltok::kw_partition) { 1045 Lex.Lex(); 1046 GV->setPartition(Lex.getStrVal()); 1047 if (parseToken(lltok::StringConstant, "expected partition string")) 1048 return true; 1049 } else { 1050 return tokError("unknown alias or ifunc property!"); 1051 } 1052 } 1053 1054 if (Name.empty()) 1055 NumberedVals.push_back(GV); 1056 1057 if (GVal) { 1058 // Verify that types agree. 1059 if (GVal->getType() != GV->getType()) 1060 return error( 1061 ExplicitTypeLoc, 1062 "forward reference and definition of alias have different types"); 1063 1064 // If they agree, just RAUW the old value with the alias and remove the 1065 // forward ref info. 1066 GVal->replaceAllUsesWith(GV); 1067 GVal->eraseFromParent(); 1068 } 1069 1070 // Insert into the module, we know its name won't collide now. 1071 if (IsAlias) 1072 M->getAliasList().push_back(GA.release()); 1073 else 1074 M->getIFuncList().push_back(GI.release()); 1075 assert(GV->getName() == Name && "Should not be a name conflict!"); 1076 1077 return false; 1078 } 1079 1080 /// parseGlobal 1081 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 1082 /// OptionalVisibility OptionalDLLStorageClass 1083 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace 1084 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs 1085 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 1086 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr 1087 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type 1088 /// Const OptionalAttrs 1089 /// 1090 /// Everything up to and including OptionalUnnamedAddr has been parsed 1091 /// already. 1092 /// 1093 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc, 1094 unsigned Linkage, bool HasLinkage, 1095 unsigned Visibility, unsigned DLLStorageClass, 1096 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM, 1097 GlobalVariable::UnnamedAddr UnnamedAddr) { 1098 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 1099 return error(NameLoc, 1100 "symbol with local linkage must have default visibility"); 1101 1102 unsigned AddrSpace; 1103 bool IsConstant, IsExternallyInitialized; 1104 LocTy IsExternallyInitializedLoc; 1105 LocTy TyLoc; 1106 1107 Type *Ty = nullptr; 1108 if (parseOptionalAddrSpace(AddrSpace) || 1109 parseOptionalToken(lltok::kw_externally_initialized, 1110 IsExternallyInitialized, 1111 &IsExternallyInitializedLoc) || 1112 parseGlobalType(IsConstant) || parseType(Ty, TyLoc)) 1113 return true; 1114 1115 // If the linkage is specified and is external, then no initializer is 1116 // present. 1117 Constant *Init = nullptr; 1118 if (!HasLinkage || 1119 !GlobalValue::isValidDeclarationLinkage( 1120 (GlobalValue::LinkageTypes)Linkage)) { 1121 if (parseGlobalValue(Ty, Init)) 1122 return true; 1123 } 1124 1125 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 1126 return error(TyLoc, "invalid type for global variable"); 1127 1128 GlobalValue *GVal = nullptr; 1129 1130 // See if the global was forward referenced, if so, use the global. 1131 if (!Name.empty()) { 1132 auto I = ForwardRefVals.find(Name); 1133 if (I != ForwardRefVals.end()) { 1134 GVal = I->second.first; 1135 ForwardRefVals.erase(I); 1136 } else if (M->getNamedValue(Name)) { 1137 return error(NameLoc, "redefinition of global '@" + Name + "'"); 1138 } 1139 } else { 1140 auto I = ForwardRefValIDs.find(NumberedVals.size()); 1141 if (I != ForwardRefValIDs.end()) { 1142 GVal = I->second.first; 1143 ForwardRefValIDs.erase(I); 1144 } 1145 } 1146 1147 GlobalVariable *GV = new GlobalVariable( 1148 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr, 1149 GlobalVariable::NotThreadLocal, AddrSpace); 1150 1151 if (Name.empty()) 1152 NumberedVals.push_back(GV); 1153 1154 // Set the parsed properties on the global. 1155 if (Init) 1156 GV->setInitializer(Init); 1157 GV->setConstant(IsConstant); 1158 GV->setLinkage((GlobalValue::LinkageTypes)Linkage); 1159 maybeSetDSOLocal(DSOLocal, *GV); 1160 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility); 1161 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 1162 GV->setExternallyInitialized(IsExternallyInitialized); 1163 GV->setThreadLocalMode(TLM); 1164 GV->setUnnamedAddr(UnnamedAddr); 1165 1166 if (GVal) { 1167 if (!GVal->getType()->isOpaque() && GVal->getValueType() != Ty) 1168 return error( 1169 TyLoc, 1170 "forward reference and definition of global have different types"); 1171 1172 GVal->replaceAllUsesWith(GV); 1173 GVal->eraseFromParent(); 1174 } 1175 1176 // parse attributes on the global. 1177 while (Lex.getKind() == lltok::comma) { 1178 Lex.Lex(); 1179 1180 if (Lex.getKind() == lltok::kw_section) { 1181 Lex.Lex(); 1182 GV->setSection(Lex.getStrVal()); 1183 if (parseToken(lltok::StringConstant, "expected global section string")) 1184 return true; 1185 } else if (Lex.getKind() == lltok::kw_partition) { 1186 Lex.Lex(); 1187 GV->setPartition(Lex.getStrVal()); 1188 if (parseToken(lltok::StringConstant, "expected partition string")) 1189 return true; 1190 } else if (Lex.getKind() == lltok::kw_align) { 1191 MaybeAlign Alignment; 1192 if (parseOptionalAlignment(Alignment)) 1193 return true; 1194 GV->setAlignment(Alignment); 1195 } else if (Lex.getKind() == lltok::MetadataVar) { 1196 if (parseGlobalObjectMetadataAttachment(*GV)) 1197 return true; 1198 } else { 1199 Comdat *C; 1200 if (parseOptionalComdat(Name, C)) 1201 return true; 1202 if (C) 1203 GV->setComdat(C); 1204 else 1205 return tokError("unknown global variable property!"); 1206 } 1207 } 1208 1209 AttrBuilder Attrs; 1210 LocTy BuiltinLoc; 1211 std::vector<unsigned> FwdRefAttrGrps; 1212 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc)) 1213 return true; 1214 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) { 1215 GV->setAttributes(AttributeSet::get(Context, Attrs)); 1216 ForwardRefAttrGroups[GV] = FwdRefAttrGrps; 1217 } 1218 1219 return false; 1220 } 1221 1222 /// parseUnnamedAttrGrp 1223 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}' 1224 bool LLParser::parseUnnamedAttrGrp() { 1225 assert(Lex.getKind() == lltok::kw_attributes); 1226 LocTy AttrGrpLoc = Lex.getLoc(); 1227 Lex.Lex(); 1228 1229 if (Lex.getKind() != lltok::AttrGrpID) 1230 return tokError("expected attribute group id"); 1231 1232 unsigned VarID = Lex.getUIntVal(); 1233 std::vector<unsigned> unused; 1234 LocTy BuiltinLoc; 1235 Lex.Lex(); 1236 1237 if (parseToken(lltok::equal, "expected '=' here") || 1238 parseToken(lltok::lbrace, "expected '{' here") || 1239 parseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true, 1240 BuiltinLoc) || 1241 parseToken(lltok::rbrace, "expected end of attribute group")) 1242 return true; 1243 1244 if (!NumberedAttrBuilders[VarID].hasAttributes()) 1245 return error(AttrGrpLoc, "attribute group has no attributes"); 1246 1247 return false; 1248 } 1249 1250 static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) { 1251 switch (Kind) { 1252 #define GET_ATTR_NAMES 1253 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 1254 case lltok::kw_##DISPLAY_NAME: \ 1255 return Attribute::ENUM_NAME; 1256 #include "llvm/IR/Attributes.inc" 1257 default: 1258 return Attribute::None; 1259 } 1260 } 1261 1262 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B, 1263 bool InAttrGroup) { 1264 if (Attribute::isTypeAttrKind(Attr)) 1265 return parseRequiredTypeAttr(B, Lex.getKind(), Attr); 1266 1267 switch (Attr) { 1268 case Attribute::Alignment: { 1269 MaybeAlign Alignment; 1270 if (InAttrGroup) { 1271 uint32_t Value = 0; 1272 Lex.Lex(); 1273 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value)) 1274 return true; 1275 Alignment = Align(Value); 1276 } else { 1277 if (parseOptionalAlignment(Alignment, true)) 1278 return true; 1279 } 1280 B.addAlignmentAttr(Alignment); 1281 return false; 1282 } 1283 case Attribute::StackAlignment: { 1284 unsigned Alignment; 1285 if (InAttrGroup) { 1286 Lex.Lex(); 1287 if (parseToken(lltok::equal, "expected '=' here") || 1288 parseUInt32(Alignment)) 1289 return true; 1290 } else { 1291 if (parseOptionalStackAlignment(Alignment)) 1292 return true; 1293 } 1294 B.addStackAlignmentAttr(Alignment); 1295 return false; 1296 } 1297 case Attribute::AllocSize: { 1298 unsigned ElemSizeArg; 1299 Optional<unsigned> NumElemsArg; 1300 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg)) 1301 return true; 1302 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); 1303 return false; 1304 } 1305 case Attribute::VScaleRange: { 1306 unsigned MinValue, MaxValue; 1307 if (parseVScaleRangeArguments(MinValue, MaxValue)) 1308 return true; 1309 B.addVScaleRangeAttr(MinValue, MaxValue); 1310 return false; 1311 } 1312 case Attribute::Dereferenceable: { 1313 uint64_t Bytes; 1314 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes)) 1315 return true; 1316 B.addDereferenceableAttr(Bytes); 1317 return false; 1318 } 1319 case Attribute::DereferenceableOrNull: { 1320 uint64_t Bytes; 1321 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes)) 1322 return true; 1323 B.addDereferenceableOrNullAttr(Bytes); 1324 return false; 1325 } 1326 default: 1327 B.addAttribute(Attr); 1328 Lex.Lex(); 1329 return false; 1330 } 1331 } 1332 1333 /// parseFnAttributeValuePairs 1334 /// ::= <attr> | <attr> '=' <value> 1335 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B, 1336 std::vector<unsigned> &FwdRefAttrGrps, 1337 bool InAttrGrp, LocTy &BuiltinLoc) { 1338 bool HaveError = false; 1339 1340 B.clear(); 1341 1342 while (true) { 1343 lltok::Kind Token = Lex.getKind(); 1344 if (Token == lltok::rbrace) 1345 return HaveError; // Finished. 1346 1347 if (Token == lltok::StringConstant) { 1348 if (parseStringAttribute(B)) 1349 return true; 1350 continue; 1351 } 1352 1353 if (Token == lltok::AttrGrpID) { 1354 // Allow a function to reference an attribute group: 1355 // 1356 // define void @foo() #1 { ... } 1357 if (InAttrGrp) { 1358 HaveError |= error( 1359 Lex.getLoc(), 1360 "cannot have an attribute group reference in an attribute group"); 1361 } else { 1362 // Save the reference to the attribute group. We'll fill it in later. 1363 FwdRefAttrGrps.push_back(Lex.getUIntVal()); 1364 } 1365 Lex.Lex(); 1366 continue; 1367 } 1368 1369 SMLoc Loc = Lex.getLoc(); 1370 if (Token == lltok::kw_builtin) 1371 BuiltinLoc = Loc; 1372 1373 Attribute::AttrKind Attr = tokenToAttribute(Token); 1374 if (Attr == Attribute::None) { 1375 if (!InAttrGrp) 1376 return HaveError; 1377 return error(Lex.getLoc(), "unterminated attribute group"); 1378 } 1379 1380 if (parseEnumAttribute(Attr, B, InAttrGrp)) 1381 return true; 1382 1383 // As a hack, we allow function alignment to be initially parsed as an 1384 // attribute on a function declaration/definition or added to an attribute 1385 // group and later moved to the alignment field. 1386 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment) 1387 HaveError |= error(Loc, "this attribute does not apply to functions"); 1388 } 1389 } 1390 1391 //===----------------------------------------------------------------------===// 1392 // GlobalValue Reference/Resolution Routines. 1393 //===----------------------------------------------------------------------===// 1394 1395 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) { 1396 // For opaque pointers, the used global type does not matter. We will later 1397 // RAUW it with a global/function of the correct type. 1398 if (PTy->isOpaque()) 1399 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false, 1400 GlobalValue::ExternalWeakLinkage, nullptr, "", 1401 nullptr, GlobalVariable::NotThreadLocal, 1402 PTy->getAddressSpace()); 1403 1404 if (auto *FT = dyn_cast<FunctionType>(PTy->getPointerElementType())) 1405 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, 1406 PTy->getAddressSpace(), "", M); 1407 else 1408 return new GlobalVariable(*M, PTy->getPointerElementType(), false, 1409 GlobalValue::ExternalWeakLinkage, nullptr, "", 1410 nullptr, GlobalVariable::NotThreadLocal, 1411 PTy->getAddressSpace()); 1412 } 1413 1414 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty, 1415 Value *Val) { 1416 Type *ValTy = Val->getType(); 1417 if (ValTy == Ty) 1418 return Val; 1419 if (Ty->isLabelTy()) 1420 error(Loc, "'" + Name + "' is not a basic block"); 1421 else 1422 error(Loc, "'" + Name + "' defined with type '" + 1423 getTypeString(Val->getType()) + "' but expected '" + 1424 getTypeString(Ty) + "'"); 1425 return nullptr; 1426 } 1427 1428 /// getGlobalVal - Get a value with the specified name or ID, creating a 1429 /// forward reference record if needed. This can return null if the value 1430 /// exists but does not have the right type. 1431 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty, 1432 LocTy Loc) { 1433 PointerType *PTy = dyn_cast<PointerType>(Ty); 1434 if (!PTy) { 1435 error(Loc, "global variable reference must have pointer type"); 1436 return nullptr; 1437 } 1438 1439 // Look this name up in the normal function symbol table. 1440 GlobalValue *Val = 1441 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name)); 1442 1443 // If this is a forward reference for the value, see if we already created a 1444 // forward ref record. 1445 if (!Val) { 1446 auto I = ForwardRefVals.find(Name); 1447 if (I != ForwardRefVals.end()) 1448 Val = I->second.first; 1449 } 1450 1451 // If we have the value in the symbol table or fwd-ref table, return it. 1452 if (Val) 1453 return cast_or_null<GlobalValue>( 1454 checkValidVariableType(Loc, "@" + Name, Ty, Val)); 1455 1456 // Otherwise, create a new forward reference for this value and remember it. 1457 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy); 1458 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 1459 return FwdVal; 1460 } 1461 1462 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) { 1463 PointerType *PTy = dyn_cast<PointerType>(Ty); 1464 if (!PTy) { 1465 error(Loc, "global variable reference must have pointer type"); 1466 return nullptr; 1467 } 1468 1469 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 1470 1471 // If this is a forward reference for the value, see if we already created a 1472 // forward ref record. 1473 if (!Val) { 1474 auto I = ForwardRefValIDs.find(ID); 1475 if (I != ForwardRefValIDs.end()) 1476 Val = I->second.first; 1477 } 1478 1479 // If we have the value in the symbol table or fwd-ref table, return it. 1480 if (Val) 1481 return cast_or_null<GlobalValue>( 1482 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val)); 1483 1484 // Otherwise, create a new forward reference for this value and remember it. 1485 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy); 1486 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 1487 return FwdVal; 1488 } 1489 1490 //===----------------------------------------------------------------------===// 1491 // Comdat Reference/Resolution Routines. 1492 //===----------------------------------------------------------------------===// 1493 1494 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) { 1495 // Look this name up in the comdat symbol table. 1496 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable(); 1497 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name); 1498 if (I != ComdatSymTab.end()) 1499 return &I->second; 1500 1501 // Otherwise, create a new forward reference for this value and remember it. 1502 Comdat *C = M->getOrInsertComdat(Name); 1503 ForwardRefComdats[Name] = Loc; 1504 return C; 1505 } 1506 1507 //===----------------------------------------------------------------------===// 1508 // Helper Routines. 1509 //===----------------------------------------------------------------------===// 1510 1511 /// parseToken - If the current token has the specified kind, eat it and return 1512 /// success. Otherwise, emit the specified error and return failure. 1513 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) { 1514 if (Lex.getKind() != T) 1515 return tokError(ErrMsg); 1516 Lex.Lex(); 1517 return false; 1518 } 1519 1520 /// parseStringConstant 1521 /// ::= StringConstant 1522 bool LLParser::parseStringConstant(std::string &Result) { 1523 if (Lex.getKind() != lltok::StringConstant) 1524 return tokError("expected string constant"); 1525 Result = Lex.getStrVal(); 1526 Lex.Lex(); 1527 return false; 1528 } 1529 1530 /// parseUInt32 1531 /// ::= uint32 1532 bool LLParser::parseUInt32(uint32_t &Val) { 1533 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1534 return tokError("expected integer"); 1535 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1); 1536 if (Val64 != unsigned(Val64)) 1537 return tokError("expected 32-bit integer (too large)"); 1538 Val = Val64; 1539 Lex.Lex(); 1540 return false; 1541 } 1542 1543 /// parseUInt64 1544 /// ::= uint64 1545 bool LLParser::parseUInt64(uint64_t &Val) { 1546 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 1547 return tokError("expected integer"); 1548 Val = Lex.getAPSIntVal().getLimitedValue(); 1549 Lex.Lex(); 1550 return false; 1551 } 1552 1553 /// parseTLSModel 1554 /// := 'localdynamic' 1555 /// := 'initialexec' 1556 /// := 'localexec' 1557 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) { 1558 switch (Lex.getKind()) { 1559 default: 1560 return tokError("expected localdynamic, initialexec or localexec"); 1561 case lltok::kw_localdynamic: 1562 TLM = GlobalVariable::LocalDynamicTLSModel; 1563 break; 1564 case lltok::kw_initialexec: 1565 TLM = GlobalVariable::InitialExecTLSModel; 1566 break; 1567 case lltok::kw_localexec: 1568 TLM = GlobalVariable::LocalExecTLSModel; 1569 break; 1570 } 1571 1572 Lex.Lex(); 1573 return false; 1574 } 1575 1576 /// parseOptionalThreadLocal 1577 /// := /*empty*/ 1578 /// := 'thread_local' 1579 /// := 'thread_local' '(' tlsmodel ')' 1580 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) { 1581 TLM = GlobalVariable::NotThreadLocal; 1582 if (!EatIfPresent(lltok::kw_thread_local)) 1583 return false; 1584 1585 TLM = GlobalVariable::GeneralDynamicTLSModel; 1586 if (Lex.getKind() == lltok::lparen) { 1587 Lex.Lex(); 1588 return parseTLSModel(TLM) || 1589 parseToken(lltok::rparen, "expected ')' after thread local model"); 1590 } 1591 return false; 1592 } 1593 1594 /// parseOptionalAddrSpace 1595 /// := /*empty*/ 1596 /// := 'addrspace' '(' uint32 ')' 1597 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) { 1598 AddrSpace = DefaultAS; 1599 if (!EatIfPresent(lltok::kw_addrspace)) 1600 return false; 1601 return parseToken(lltok::lparen, "expected '(' in address space") || 1602 parseUInt32(AddrSpace) || 1603 parseToken(lltok::rparen, "expected ')' in address space"); 1604 } 1605 1606 /// parseStringAttribute 1607 /// := StringConstant 1608 /// := StringConstant '=' StringConstant 1609 bool LLParser::parseStringAttribute(AttrBuilder &B) { 1610 std::string Attr = Lex.getStrVal(); 1611 Lex.Lex(); 1612 std::string Val; 1613 if (EatIfPresent(lltok::equal) && parseStringConstant(Val)) 1614 return true; 1615 B.addAttribute(Attr, Val); 1616 return false; 1617 } 1618 1619 /// Parse a potentially empty list of parameter or return attributes. 1620 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) { 1621 bool HaveError = false; 1622 1623 B.clear(); 1624 1625 while (true) { 1626 lltok::Kind Token = Lex.getKind(); 1627 if (Token == lltok::StringConstant) { 1628 if (parseStringAttribute(B)) 1629 return true; 1630 continue; 1631 } 1632 1633 SMLoc Loc = Lex.getLoc(); 1634 Attribute::AttrKind Attr = tokenToAttribute(Token); 1635 if (Attr == Attribute::None) 1636 return HaveError; 1637 1638 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false)) 1639 return true; 1640 1641 if (IsParam && !Attribute::canUseAsParamAttr(Attr)) 1642 HaveError |= error(Loc, "this attribute does not apply to parameters"); 1643 if (!IsParam && !Attribute::canUseAsRetAttr(Attr)) 1644 HaveError |= error(Loc, "this attribute does not apply to return values"); 1645 } 1646 } 1647 1648 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) { 1649 HasLinkage = true; 1650 switch (Kind) { 1651 default: 1652 HasLinkage = false; 1653 return GlobalValue::ExternalLinkage; 1654 case lltok::kw_private: 1655 return GlobalValue::PrivateLinkage; 1656 case lltok::kw_internal: 1657 return GlobalValue::InternalLinkage; 1658 case lltok::kw_weak: 1659 return GlobalValue::WeakAnyLinkage; 1660 case lltok::kw_weak_odr: 1661 return GlobalValue::WeakODRLinkage; 1662 case lltok::kw_linkonce: 1663 return GlobalValue::LinkOnceAnyLinkage; 1664 case lltok::kw_linkonce_odr: 1665 return GlobalValue::LinkOnceODRLinkage; 1666 case lltok::kw_available_externally: 1667 return GlobalValue::AvailableExternallyLinkage; 1668 case lltok::kw_appending: 1669 return GlobalValue::AppendingLinkage; 1670 case lltok::kw_common: 1671 return GlobalValue::CommonLinkage; 1672 case lltok::kw_extern_weak: 1673 return GlobalValue::ExternalWeakLinkage; 1674 case lltok::kw_external: 1675 return GlobalValue::ExternalLinkage; 1676 } 1677 } 1678 1679 /// parseOptionalLinkage 1680 /// ::= /*empty*/ 1681 /// ::= 'private' 1682 /// ::= 'internal' 1683 /// ::= 'weak' 1684 /// ::= 'weak_odr' 1685 /// ::= 'linkonce' 1686 /// ::= 'linkonce_odr' 1687 /// ::= 'available_externally' 1688 /// ::= 'appending' 1689 /// ::= 'common' 1690 /// ::= 'extern_weak' 1691 /// ::= 'external' 1692 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage, 1693 unsigned &Visibility, 1694 unsigned &DLLStorageClass, bool &DSOLocal) { 1695 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 1696 if (HasLinkage) 1697 Lex.Lex(); 1698 parseOptionalDSOLocal(DSOLocal); 1699 parseOptionalVisibility(Visibility); 1700 parseOptionalDLLStorageClass(DLLStorageClass); 1701 1702 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) { 1703 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch"); 1704 } 1705 1706 return false; 1707 } 1708 1709 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) { 1710 switch (Lex.getKind()) { 1711 default: 1712 DSOLocal = false; 1713 break; 1714 case lltok::kw_dso_local: 1715 DSOLocal = true; 1716 Lex.Lex(); 1717 break; 1718 case lltok::kw_dso_preemptable: 1719 DSOLocal = false; 1720 Lex.Lex(); 1721 break; 1722 } 1723 } 1724 1725 /// parseOptionalVisibility 1726 /// ::= /*empty*/ 1727 /// ::= 'default' 1728 /// ::= 'hidden' 1729 /// ::= 'protected' 1730 /// 1731 void LLParser::parseOptionalVisibility(unsigned &Res) { 1732 switch (Lex.getKind()) { 1733 default: 1734 Res = GlobalValue::DefaultVisibility; 1735 return; 1736 case lltok::kw_default: 1737 Res = GlobalValue::DefaultVisibility; 1738 break; 1739 case lltok::kw_hidden: 1740 Res = GlobalValue::HiddenVisibility; 1741 break; 1742 case lltok::kw_protected: 1743 Res = GlobalValue::ProtectedVisibility; 1744 break; 1745 } 1746 Lex.Lex(); 1747 } 1748 1749 /// parseOptionalDLLStorageClass 1750 /// ::= /*empty*/ 1751 /// ::= 'dllimport' 1752 /// ::= 'dllexport' 1753 /// 1754 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) { 1755 switch (Lex.getKind()) { 1756 default: 1757 Res = GlobalValue::DefaultStorageClass; 1758 return; 1759 case lltok::kw_dllimport: 1760 Res = GlobalValue::DLLImportStorageClass; 1761 break; 1762 case lltok::kw_dllexport: 1763 Res = GlobalValue::DLLExportStorageClass; 1764 break; 1765 } 1766 Lex.Lex(); 1767 } 1768 1769 /// parseOptionalCallingConv 1770 /// ::= /*empty*/ 1771 /// ::= 'ccc' 1772 /// ::= 'fastcc' 1773 /// ::= 'intel_ocl_bicc' 1774 /// ::= 'coldcc' 1775 /// ::= 'cfguard_checkcc' 1776 /// ::= 'x86_stdcallcc' 1777 /// ::= 'x86_fastcallcc' 1778 /// ::= 'x86_thiscallcc' 1779 /// ::= 'x86_vectorcallcc' 1780 /// ::= 'arm_apcscc' 1781 /// ::= 'arm_aapcscc' 1782 /// ::= 'arm_aapcs_vfpcc' 1783 /// ::= 'aarch64_vector_pcs' 1784 /// ::= 'aarch64_sve_vector_pcs' 1785 /// ::= 'msp430_intrcc' 1786 /// ::= 'avr_intrcc' 1787 /// ::= 'avr_signalcc' 1788 /// ::= 'ptx_kernel' 1789 /// ::= 'ptx_device' 1790 /// ::= 'spir_func' 1791 /// ::= 'spir_kernel' 1792 /// ::= 'x86_64_sysvcc' 1793 /// ::= 'win64cc' 1794 /// ::= 'webkit_jscc' 1795 /// ::= 'anyregcc' 1796 /// ::= 'preserve_mostcc' 1797 /// ::= 'preserve_allcc' 1798 /// ::= 'ghccc' 1799 /// ::= 'swiftcc' 1800 /// ::= 'swifttailcc' 1801 /// ::= 'x86_intrcc' 1802 /// ::= 'hhvmcc' 1803 /// ::= 'hhvm_ccc' 1804 /// ::= 'cxx_fast_tlscc' 1805 /// ::= 'amdgpu_vs' 1806 /// ::= 'amdgpu_ls' 1807 /// ::= 'amdgpu_hs' 1808 /// ::= 'amdgpu_es' 1809 /// ::= 'amdgpu_gs' 1810 /// ::= 'amdgpu_ps' 1811 /// ::= 'amdgpu_cs' 1812 /// ::= 'amdgpu_kernel' 1813 /// ::= 'tailcc' 1814 /// ::= 'cc' UINT 1815 /// 1816 bool LLParser::parseOptionalCallingConv(unsigned &CC) { 1817 switch (Lex.getKind()) { 1818 default: CC = CallingConv::C; return false; 1819 case lltok::kw_ccc: CC = CallingConv::C; break; 1820 case lltok::kw_fastcc: CC = CallingConv::Fast; break; 1821 case lltok::kw_coldcc: CC = CallingConv::Cold; break; 1822 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break; 1823 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break; 1824 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break; 1825 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break; 1826 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break; 1827 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break; 1828 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break; 1829 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break; 1830 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break; 1831 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break; 1832 case lltok::kw_aarch64_sve_vector_pcs: 1833 CC = CallingConv::AArch64_SVE_VectorCall; 1834 break; 1835 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break; 1836 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break; 1837 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break; 1838 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break; 1839 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break; 1840 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break; 1841 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break; 1842 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break; 1843 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break; 1844 case lltok::kw_win64cc: CC = CallingConv::Win64; break; 1845 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break; 1846 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break; 1847 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break; 1848 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break; 1849 case lltok::kw_ghccc: CC = CallingConv::GHC; break; 1850 case lltok::kw_swiftcc: CC = CallingConv::Swift; break; 1851 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break; 1852 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break; 1853 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break; 1854 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break; 1855 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break; 1856 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break; 1857 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break; 1858 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break; 1859 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break; 1860 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break; 1861 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break; 1862 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break; 1863 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break; 1864 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break; 1865 case lltok::kw_tailcc: CC = CallingConv::Tail; break; 1866 case lltok::kw_cc: { 1867 Lex.Lex(); 1868 return parseUInt32(CC); 1869 } 1870 } 1871 1872 Lex.Lex(); 1873 return false; 1874 } 1875 1876 /// parseMetadataAttachment 1877 /// ::= !dbg !42 1878 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) { 1879 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment"); 1880 1881 std::string Name = Lex.getStrVal(); 1882 Kind = M->getMDKindID(Name); 1883 Lex.Lex(); 1884 1885 return parseMDNode(MD); 1886 } 1887 1888 /// parseInstructionMetadata 1889 /// ::= !dbg !42 (',' !dbg !57)* 1890 bool LLParser::parseInstructionMetadata(Instruction &Inst) { 1891 do { 1892 if (Lex.getKind() != lltok::MetadataVar) 1893 return tokError("expected metadata after comma"); 1894 1895 unsigned MDK; 1896 MDNode *N; 1897 if (parseMetadataAttachment(MDK, N)) 1898 return true; 1899 1900 Inst.setMetadata(MDK, N); 1901 if (MDK == LLVMContext::MD_tbaa) 1902 InstsWithTBAATag.push_back(&Inst); 1903 1904 // If this is the end of the list, we're done. 1905 } while (EatIfPresent(lltok::comma)); 1906 return false; 1907 } 1908 1909 /// parseGlobalObjectMetadataAttachment 1910 /// ::= !dbg !57 1911 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) { 1912 unsigned MDK; 1913 MDNode *N; 1914 if (parseMetadataAttachment(MDK, N)) 1915 return true; 1916 1917 GO.addMetadata(MDK, *N); 1918 return false; 1919 } 1920 1921 /// parseOptionalFunctionMetadata 1922 /// ::= (!dbg !57)* 1923 bool LLParser::parseOptionalFunctionMetadata(Function &F) { 1924 while (Lex.getKind() == lltok::MetadataVar) 1925 if (parseGlobalObjectMetadataAttachment(F)) 1926 return true; 1927 return false; 1928 } 1929 1930 /// parseOptionalAlignment 1931 /// ::= /* empty */ 1932 /// ::= 'align' 4 1933 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) { 1934 Alignment = None; 1935 if (!EatIfPresent(lltok::kw_align)) 1936 return false; 1937 LocTy AlignLoc = Lex.getLoc(); 1938 uint64_t Value = 0; 1939 1940 LocTy ParenLoc = Lex.getLoc(); 1941 bool HaveParens = false; 1942 if (AllowParens) { 1943 if (EatIfPresent(lltok::lparen)) 1944 HaveParens = true; 1945 } 1946 1947 if (parseUInt64(Value)) 1948 return true; 1949 1950 if (HaveParens && !EatIfPresent(lltok::rparen)) 1951 return error(ParenLoc, "expected ')'"); 1952 1953 if (!isPowerOf2_64(Value)) 1954 return error(AlignLoc, "alignment is not a power of two"); 1955 if (Value > Value::MaximumAlignment) 1956 return error(AlignLoc, "huge alignments are not supported yet"); 1957 Alignment = Align(Value); 1958 return false; 1959 } 1960 1961 /// parseOptionalDerefAttrBytes 1962 /// ::= /* empty */ 1963 /// ::= AttrKind '(' 4 ')' 1964 /// 1965 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'. 1966 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind, 1967 uint64_t &Bytes) { 1968 assert((AttrKind == lltok::kw_dereferenceable || 1969 AttrKind == lltok::kw_dereferenceable_or_null) && 1970 "contract!"); 1971 1972 Bytes = 0; 1973 if (!EatIfPresent(AttrKind)) 1974 return false; 1975 LocTy ParenLoc = Lex.getLoc(); 1976 if (!EatIfPresent(lltok::lparen)) 1977 return error(ParenLoc, "expected '('"); 1978 LocTy DerefLoc = Lex.getLoc(); 1979 if (parseUInt64(Bytes)) 1980 return true; 1981 ParenLoc = Lex.getLoc(); 1982 if (!EatIfPresent(lltok::rparen)) 1983 return error(ParenLoc, "expected ')'"); 1984 if (!Bytes) 1985 return error(DerefLoc, "dereferenceable bytes must be non-zero"); 1986 return false; 1987 } 1988 1989 /// parseOptionalCommaAlign 1990 /// ::= 1991 /// ::= ',' align 4 1992 /// 1993 /// This returns with AteExtraComma set to true if it ate an excess comma at the 1994 /// end. 1995 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment, 1996 bool &AteExtraComma) { 1997 AteExtraComma = false; 1998 while (EatIfPresent(lltok::comma)) { 1999 // Metadata at the end is an early exit. 2000 if (Lex.getKind() == lltok::MetadataVar) { 2001 AteExtraComma = true; 2002 return false; 2003 } 2004 2005 if (Lex.getKind() != lltok::kw_align) 2006 return error(Lex.getLoc(), "expected metadata or 'align'"); 2007 2008 if (parseOptionalAlignment(Alignment)) 2009 return true; 2010 } 2011 2012 return false; 2013 } 2014 2015 /// parseOptionalCommaAddrSpace 2016 /// ::= 2017 /// ::= ',' addrspace(1) 2018 /// 2019 /// This returns with AteExtraComma set to true if it ate an excess comma at the 2020 /// end. 2021 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc, 2022 bool &AteExtraComma) { 2023 AteExtraComma = false; 2024 while (EatIfPresent(lltok::comma)) { 2025 // Metadata at the end is an early exit. 2026 if (Lex.getKind() == lltok::MetadataVar) { 2027 AteExtraComma = true; 2028 return false; 2029 } 2030 2031 Loc = Lex.getLoc(); 2032 if (Lex.getKind() != lltok::kw_addrspace) 2033 return error(Lex.getLoc(), "expected metadata or 'addrspace'"); 2034 2035 if (parseOptionalAddrSpace(AddrSpace)) 2036 return true; 2037 } 2038 2039 return false; 2040 } 2041 2042 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg, 2043 Optional<unsigned> &HowManyArg) { 2044 Lex.Lex(); 2045 2046 auto StartParen = Lex.getLoc(); 2047 if (!EatIfPresent(lltok::lparen)) 2048 return error(StartParen, "expected '('"); 2049 2050 if (parseUInt32(BaseSizeArg)) 2051 return true; 2052 2053 if (EatIfPresent(lltok::comma)) { 2054 auto HowManyAt = Lex.getLoc(); 2055 unsigned HowMany; 2056 if (parseUInt32(HowMany)) 2057 return true; 2058 if (HowMany == BaseSizeArg) 2059 return error(HowManyAt, 2060 "'allocsize' indices can't refer to the same parameter"); 2061 HowManyArg = HowMany; 2062 } else 2063 HowManyArg = None; 2064 2065 auto EndParen = Lex.getLoc(); 2066 if (!EatIfPresent(lltok::rparen)) 2067 return error(EndParen, "expected ')'"); 2068 return false; 2069 } 2070 2071 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue, 2072 unsigned &MaxValue) { 2073 Lex.Lex(); 2074 2075 auto StartParen = Lex.getLoc(); 2076 if (!EatIfPresent(lltok::lparen)) 2077 return error(StartParen, "expected '('"); 2078 2079 if (parseUInt32(MinValue)) 2080 return true; 2081 2082 if (EatIfPresent(lltok::comma)) { 2083 if (parseUInt32(MaxValue)) 2084 return true; 2085 } else 2086 MaxValue = MinValue; 2087 2088 auto EndParen = Lex.getLoc(); 2089 if (!EatIfPresent(lltok::rparen)) 2090 return error(EndParen, "expected ')'"); 2091 return false; 2092 } 2093 2094 /// parseScopeAndOrdering 2095 /// if isAtomic: ::= SyncScope? AtomicOrdering 2096 /// else: ::= 2097 /// 2098 /// This sets Scope and Ordering to the parsed values. 2099 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID, 2100 AtomicOrdering &Ordering) { 2101 if (!IsAtomic) 2102 return false; 2103 2104 return parseScope(SSID) || parseOrdering(Ordering); 2105 } 2106 2107 /// parseScope 2108 /// ::= syncscope("singlethread" | "<target scope>")? 2109 /// 2110 /// This sets synchronization scope ID to the ID of the parsed value. 2111 bool LLParser::parseScope(SyncScope::ID &SSID) { 2112 SSID = SyncScope::System; 2113 if (EatIfPresent(lltok::kw_syncscope)) { 2114 auto StartParenAt = Lex.getLoc(); 2115 if (!EatIfPresent(lltok::lparen)) 2116 return error(StartParenAt, "Expected '(' in syncscope"); 2117 2118 std::string SSN; 2119 auto SSNAt = Lex.getLoc(); 2120 if (parseStringConstant(SSN)) 2121 return error(SSNAt, "Expected synchronization scope name"); 2122 2123 auto EndParenAt = Lex.getLoc(); 2124 if (!EatIfPresent(lltok::rparen)) 2125 return error(EndParenAt, "Expected ')' in syncscope"); 2126 2127 SSID = Context.getOrInsertSyncScopeID(SSN); 2128 } 2129 2130 return false; 2131 } 2132 2133 /// parseOrdering 2134 /// ::= AtomicOrdering 2135 /// 2136 /// This sets Ordering to the parsed value. 2137 bool LLParser::parseOrdering(AtomicOrdering &Ordering) { 2138 switch (Lex.getKind()) { 2139 default: 2140 return tokError("Expected ordering on atomic instruction"); 2141 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break; 2142 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break; 2143 // Not specified yet: 2144 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break; 2145 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break; 2146 case lltok::kw_release: Ordering = AtomicOrdering::Release; break; 2147 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break; 2148 case lltok::kw_seq_cst: 2149 Ordering = AtomicOrdering::SequentiallyConsistent; 2150 break; 2151 } 2152 Lex.Lex(); 2153 return false; 2154 } 2155 2156 /// parseOptionalStackAlignment 2157 /// ::= /* empty */ 2158 /// ::= 'alignstack' '(' 4 ')' 2159 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) { 2160 Alignment = 0; 2161 if (!EatIfPresent(lltok::kw_alignstack)) 2162 return false; 2163 LocTy ParenLoc = Lex.getLoc(); 2164 if (!EatIfPresent(lltok::lparen)) 2165 return error(ParenLoc, "expected '('"); 2166 LocTy AlignLoc = Lex.getLoc(); 2167 if (parseUInt32(Alignment)) 2168 return true; 2169 ParenLoc = Lex.getLoc(); 2170 if (!EatIfPresent(lltok::rparen)) 2171 return error(ParenLoc, "expected ')'"); 2172 if (!isPowerOf2_32(Alignment)) 2173 return error(AlignLoc, "stack alignment is not a power of two"); 2174 return false; 2175 } 2176 2177 /// parseIndexList - This parses the index list for an insert/extractvalue 2178 /// instruction. This sets AteExtraComma in the case where we eat an extra 2179 /// comma at the end of the line and find that it is followed by metadata. 2180 /// Clients that don't allow metadata can call the version of this function that 2181 /// only takes one argument. 2182 /// 2183 /// parseIndexList 2184 /// ::= (',' uint32)+ 2185 /// 2186 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices, 2187 bool &AteExtraComma) { 2188 AteExtraComma = false; 2189 2190 if (Lex.getKind() != lltok::comma) 2191 return tokError("expected ',' as start of index list"); 2192 2193 while (EatIfPresent(lltok::comma)) { 2194 if (Lex.getKind() == lltok::MetadataVar) { 2195 if (Indices.empty()) 2196 return tokError("expected index"); 2197 AteExtraComma = true; 2198 return false; 2199 } 2200 unsigned Idx = 0; 2201 if (parseUInt32(Idx)) 2202 return true; 2203 Indices.push_back(Idx); 2204 } 2205 2206 return false; 2207 } 2208 2209 //===----------------------------------------------------------------------===// 2210 // Type Parsing. 2211 //===----------------------------------------------------------------------===// 2212 2213 /// parseType - parse a type. 2214 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) { 2215 SMLoc TypeLoc = Lex.getLoc(); 2216 switch (Lex.getKind()) { 2217 default: 2218 return tokError(Msg); 2219 case lltok::Type: 2220 // Type ::= 'float' | 'void' (etc) 2221 Result = Lex.getTyVal(); 2222 Lex.Lex(); 2223 2224 // Handle "ptr" opaque pointer type. 2225 // 2226 // Type ::= ptr ('addrspace' '(' uint32 ')')? 2227 if (Result->isOpaquePointerTy()) { 2228 unsigned AddrSpace; 2229 if (parseOptionalAddrSpace(AddrSpace)) 2230 return true; 2231 Result = PointerType::get(getContext(), AddrSpace); 2232 2233 // Give a nice error for 'ptr*'. 2234 if (Lex.getKind() == lltok::star) 2235 return tokError("ptr* is invalid - use ptr instead"); 2236 2237 // Fall through to parsing the type suffixes only if this 'ptr' is a 2238 // function return. Otherwise, return success, implicitly rejecting other 2239 // suffixes. 2240 if (Lex.getKind() != lltok::lparen) 2241 return false; 2242 } 2243 break; 2244 case lltok::lbrace: 2245 // Type ::= StructType 2246 if (parseAnonStructType(Result, false)) 2247 return true; 2248 break; 2249 case lltok::lsquare: 2250 // Type ::= '[' ... ']' 2251 Lex.Lex(); // eat the lsquare. 2252 if (parseArrayVectorType(Result, false)) 2253 return true; 2254 break; 2255 case lltok::less: // Either vector or packed struct. 2256 // Type ::= '<' ... '>' 2257 Lex.Lex(); 2258 if (Lex.getKind() == lltok::lbrace) { 2259 if (parseAnonStructType(Result, true) || 2260 parseToken(lltok::greater, "expected '>' at end of packed struct")) 2261 return true; 2262 } else if (parseArrayVectorType(Result, true)) 2263 return true; 2264 break; 2265 case lltok::LocalVar: { 2266 // Type ::= %foo 2267 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()]; 2268 2269 // If the type hasn't been defined yet, create a forward definition and 2270 // remember where that forward def'n was seen (in case it never is defined). 2271 if (!Entry.first) { 2272 Entry.first = StructType::create(Context, Lex.getStrVal()); 2273 Entry.second = Lex.getLoc(); 2274 } 2275 Result = Entry.first; 2276 Lex.Lex(); 2277 break; 2278 } 2279 2280 case lltok::LocalVarID: { 2281 // Type ::= %4 2282 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()]; 2283 2284 // If the type hasn't been defined yet, create a forward definition and 2285 // remember where that forward def'n was seen (in case it never is defined). 2286 if (!Entry.first) { 2287 Entry.first = StructType::create(Context); 2288 Entry.second = Lex.getLoc(); 2289 } 2290 Result = Entry.first; 2291 Lex.Lex(); 2292 break; 2293 } 2294 } 2295 2296 // parse the type suffixes. 2297 while (true) { 2298 switch (Lex.getKind()) { 2299 // End of type. 2300 default: 2301 if (!AllowVoid && Result->isVoidTy()) 2302 return error(TypeLoc, "void type only allowed for function results"); 2303 return false; 2304 2305 // Type ::= Type '*' 2306 case lltok::star: 2307 if (Result->isLabelTy()) 2308 return tokError("basic block pointers are invalid"); 2309 if (Result->isVoidTy()) 2310 return tokError("pointers to void are invalid - use i8* instead"); 2311 if (!PointerType::isValidElementType(Result)) 2312 return tokError("pointer to this type is invalid"); 2313 Result = PointerType::getUnqual(Result); 2314 Lex.Lex(); 2315 break; 2316 2317 // Type ::= Type 'addrspace' '(' uint32 ')' '*' 2318 case lltok::kw_addrspace: { 2319 if (Result->isLabelTy()) 2320 return tokError("basic block pointers are invalid"); 2321 if (Result->isVoidTy()) 2322 return tokError("pointers to void are invalid; use i8* instead"); 2323 if (!PointerType::isValidElementType(Result)) 2324 return tokError("pointer to this type is invalid"); 2325 unsigned AddrSpace; 2326 if (parseOptionalAddrSpace(AddrSpace) || 2327 parseToken(lltok::star, "expected '*' in address space")) 2328 return true; 2329 2330 Result = PointerType::get(Result, AddrSpace); 2331 break; 2332 } 2333 2334 /// Types '(' ArgTypeListI ')' OptFuncAttrs 2335 case lltok::lparen: 2336 if (parseFunctionType(Result)) 2337 return true; 2338 break; 2339 } 2340 } 2341 } 2342 2343 /// parseParameterList 2344 /// ::= '(' ')' 2345 /// ::= '(' Arg (',' Arg)* ')' 2346 /// Arg 2347 /// ::= Type OptionalAttributes Value OptionalAttributes 2348 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList, 2349 PerFunctionState &PFS, bool IsMustTailCall, 2350 bool InVarArgsFunc) { 2351 if (parseToken(lltok::lparen, "expected '(' in call")) 2352 return true; 2353 2354 while (Lex.getKind() != lltok::rparen) { 2355 // If this isn't the first argument, we need a comma. 2356 if (!ArgList.empty() && 2357 parseToken(lltok::comma, "expected ',' in argument list")) 2358 return true; 2359 2360 // parse an ellipsis if this is a musttail call in a variadic function. 2361 if (Lex.getKind() == lltok::dotdotdot) { 2362 const char *Msg = "unexpected ellipsis in argument list for "; 2363 if (!IsMustTailCall) 2364 return tokError(Twine(Msg) + "non-musttail call"); 2365 if (!InVarArgsFunc) 2366 return tokError(Twine(Msg) + "musttail call in non-varargs function"); 2367 Lex.Lex(); // Lex the '...', it is purely for readability. 2368 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2369 } 2370 2371 // parse the argument. 2372 LocTy ArgLoc; 2373 Type *ArgTy = nullptr; 2374 AttrBuilder ArgAttrs; 2375 Value *V; 2376 if (parseType(ArgTy, ArgLoc)) 2377 return true; 2378 2379 if (ArgTy->isMetadataTy()) { 2380 if (parseMetadataAsValue(V, PFS)) 2381 return true; 2382 } else { 2383 // Otherwise, handle normal operands. 2384 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS)) 2385 return true; 2386 } 2387 ArgList.push_back(ParamInfo( 2388 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs))); 2389 } 2390 2391 if (IsMustTailCall && InVarArgsFunc) 2392 return tokError("expected '...' at end of argument list for musttail call " 2393 "in varargs function"); 2394 2395 Lex.Lex(); // Lex the ')'. 2396 return false; 2397 } 2398 2399 /// parseRequiredTypeAttr 2400 /// ::= attrname(<ty>) 2401 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken, 2402 Attribute::AttrKind AttrKind) { 2403 Type *Ty = nullptr; 2404 if (!EatIfPresent(AttrToken)) 2405 return true; 2406 if (!EatIfPresent(lltok::lparen)) 2407 return error(Lex.getLoc(), "expected '('"); 2408 if (parseType(Ty)) 2409 return true; 2410 if (!EatIfPresent(lltok::rparen)) 2411 return error(Lex.getLoc(), "expected ')'"); 2412 2413 B.addTypeAttr(AttrKind, Ty); 2414 return false; 2415 } 2416 2417 /// parseOptionalOperandBundles 2418 /// ::= /*empty*/ 2419 /// ::= '[' OperandBundle [, OperandBundle ]* ']' 2420 /// 2421 /// OperandBundle 2422 /// ::= bundle-tag '(' ')' 2423 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')' 2424 /// 2425 /// bundle-tag ::= String Constant 2426 bool LLParser::parseOptionalOperandBundles( 2427 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) { 2428 LocTy BeginLoc = Lex.getLoc(); 2429 if (!EatIfPresent(lltok::lsquare)) 2430 return false; 2431 2432 while (Lex.getKind() != lltok::rsquare) { 2433 // If this isn't the first operand bundle, we need a comma. 2434 if (!BundleList.empty() && 2435 parseToken(lltok::comma, "expected ',' in input list")) 2436 return true; 2437 2438 std::string Tag; 2439 if (parseStringConstant(Tag)) 2440 return true; 2441 2442 if (parseToken(lltok::lparen, "expected '(' in operand bundle")) 2443 return true; 2444 2445 std::vector<Value *> Inputs; 2446 while (Lex.getKind() != lltok::rparen) { 2447 // If this isn't the first input, we need a comma. 2448 if (!Inputs.empty() && 2449 parseToken(lltok::comma, "expected ',' in input list")) 2450 return true; 2451 2452 Type *Ty = nullptr; 2453 Value *Input = nullptr; 2454 if (parseType(Ty) || parseValue(Ty, Input, PFS)) 2455 return true; 2456 Inputs.push_back(Input); 2457 } 2458 2459 BundleList.emplace_back(std::move(Tag), std::move(Inputs)); 2460 2461 Lex.Lex(); // Lex the ')'. 2462 } 2463 2464 if (BundleList.empty()) 2465 return error(BeginLoc, "operand bundle set must not be empty"); 2466 2467 Lex.Lex(); // Lex the ']'. 2468 return false; 2469 } 2470 2471 /// parseArgumentList - parse the argument list for a function type or function 2472 /// prototype. 2473 /// ::= '(' ArgTypeListI ')' 2474 /// ArgTypeListI 2475 /// ::= /*empty*/ 2476 /// ::= '...' 2477 /// ::= ArgTypeList ',' '...' 2478 /// ::= ArgType (',' ArgType)* 2479 /// 2480 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 2481 bool &IsVarArg) { 2482 unsigned CurValID = 0; 2483 IsVarArg = false; 2484 assert(Lex.getKind() == lltok::lparen); 2485 Lex.Lex(); // eat the (. 2486 2487 if (Lex.getKind() == lltok::rparen) { 2488 // empty 2489 } else if (Lex.getKind() == lltok::dotdotdot) { 2490 IsVarArg = true; 2491 Lex.Lex(); 2492 } else { 2493 LocTy TypeLoc = Lex.getLoc(); 2494 Type *ArgTy = nullptr; 2495 AttrBuilder Attrs; 2496 std::string Name; 2497 2498 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2499 return true; 2500 2501 if (ArgTy->isVoidTy()) 2502 return error(TypeLoc, "argument can not have void type"); 2503 2504 if (Lex.getKind() == lltok::LocalVar) { 2505 Name = Lex.getStrVal(); 2506 Lex.Lex(); 2507 } else if (Lex.getKind() == lltok::LocalVarID) { 2508 if (Lex.getUIntVal() != CurValID) 2509 return error(TypeLoc, "argument expected to be numbered '%" + 2510 Twine(CurValID) + "'"); 2511 ++CurValID; 2512 Lex.Lex(); 2513 } 2514 2515 if (!FunctionType::isValidArgumentType(ArgTy)) 2516 return error(TypeLoc, "invalid type for function argument"); 2517 2518 ArgList.emplace_back(TypeLoc, ArgTy, 2519 AttributeSet::get(ArgTy->getContext(), Attrs), 2520 std::move(Name)); 2521 2522 while (EatIfPresent(lltok::comma)) { 2523 // Handle ... at end of arg list. 2524 if (EatIfPresent(lltok::dotdotdot)) { 2525 IsVarArg = true; 2526 break; 2527 } 2528 2529 // Otherwise must be an argument type. 2530 TypeLoc = Lex.getLoc(); 2531 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 2532 return true; 2533 2534 if (ArgTy->isVoidTy()) 2535 return error(TypeLoc, "argument can not have void type"); 2536 2537 if (Lex.getKind() == lltok::LocalVar) { 2538 Name = Lex.getStrVal(); 2539 Lex.Lex(); 2540 } else { 2541 if (Lex.getKind() == lltok::LocalVarID) { 2542 if (Lex.getUIntVal() != CurValID) 2543 return error(TypeLoc, "argument expected to be numbered '%" + 2544 Twine(CurValID) + "'"); 2545 Lex.Lex(); 2546 } 2547 ++CurValID; 2548 Name = ""; 2549 } 2550 2551 if (!ArgTy->isFirstClassType()) 2552 return error(TypeLoc, "invalid type for function argument"); 2553 2554 ArgList.emplace_back(TypeLoc, ArgTy, 2555 AttributeSet::get(ArgTy->getContext(), Attrs), 2556 std::move(Name)); 2557 } 2558 } 2559 2560 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 2561 } 2562 2563 /// parseFunctionType 2564 /// ::= Type ArgumentList OptionalAttrs 2565 bool LLParser::parseFunctionType(Type *&Result) { 2566 assert(Lex.getKind() == lltok::lparen); 2567 2568 if (!FunctionType::isValidReturnType(Result)) 2569 return tokError("invalid function return type"); 2570 2571 SmallVector<ArgInfo, 8> ArgList; 2572 bool IsVarArg; 2573 if (parseArgumentList(ArgList, IsVarArg)) 2574 return true; 2575 2576 // Reject names on the arguments lists. 2577 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 2578 if (!ArgList[i].Name.empty()) 2579 return error(ArgList[i].Loc, "argument name invalid in function type"); 2580 if (ArgList[i].Attrs.hasAttributes()) 2581 return error(ArgList[i].Loc, 2582 "argument attributes invalid in function type"); 2583 } 2584 2585 SmallVector<Type*, 16> ArgListTy; 2586 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 2587 ArgListTy.push_back(ArgList[i].Ty); 2588 2589 Result = FunctionType::get(Result, ArgListTy, IsVarArg); 2590 return false; 2591 } 2592 2593 /// parseAnonStructType - parse an anonymous struct type, which is inlined into 2594 /// other structs. 2595 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) { 2596 SmallVector<Type*, 8> Elts; 2597 if (parseStructBody(Elts)) 2598 return true; 2599 2600 Result = StructType::get(Context, Elts, Packed); 2601 return false; 2602 } 2603 2604 /// parseStructDefinition - parse a struct in a 'type' definition. 2605 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name, 2606 std::pair<Type *, LocTy> &Entry, 2607 Type *&ResultTy) { 2608 // If the type was already defined, diagnose the redefinition. 2609 if (Entry.first && !Entry.second.isValid()) 2610 return error(TypeLoc, "redefinition of type"); 2611 2612 // If we have opaque, just return without filling in the definition for the 2613 // struct. This counts as a definition as far as the .ll file goes. 2614 if (EatIfPresent(lltok::kw_opaque)) { 2615 // This type is being defined, so clear the location to indicate this. 2616 Entry.second = SMLoc(); 2617 2618 // If this type number has never been uttered, create it. 2619 if (!Entry.first) 2620 Entry.first = StructType::create(Context, Name); 2621 ResultTy = Entry.first; 2622 return false; 2623 } 2624 2625 // If the type starts with '<', then it is either a packed struct or a vector. 2626 bool isPacked = EatIfPresent(lltok::less); 2627 2628 // If we don't have a struct, then we have a random type alias, which we 2629 // accept for compatibility with old files. These types are not allowed to be 2630 // forward referenced and not allowed to be recursive. 2631 if (Lex.getKind() != lltok::lbrace) { 2632 if (Entry.first) 2633 return error(TypeLoc, "forward references to non-struct type"); 2634 2635 ResultTy = nullptr; 2636 if (isPacked) 2637 return parseArrayVectorType(ResultTy, true); 2638 return parseType(ResultTy); 2639 } 2640 2641 // This type is being defined, so clear the location to indicate this. 2642 Entry.second = SMLoc(); 2643 2644 // If this type number has never been uttered, create it. 2645 if (!Entry.first) 2646 Entry.first = StructType::create(Context, Name); 2647 2648 StructType *STy = cast<StructType>(Entry.first); 2649 2650 SmallVector<Type*, 8> Body; 2651 if (parseStructBody(Body) || 2652 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct"))) 2653 return true; 2654 2655 STy->setBody(Body, isPacked); 2656 ResultTy = STy; 2657 return false; 2658 } 2659 2660 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere. 2661 /// StructType 2662 /// ::= '{' '}' 2663 /// ::= '{' Type (',' Type)* '}' 2664 /// ::= '<' '{' '}' '>' 2665 /// ::= '<' '{' Type (',' Type)* '}' '>' 2666 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) { 2667 assert(Lex.getKind() == lltok::lbrace); 2668 Lex.Lex(); // Consume the '{' 2669 2670 // Handle the empty struct. 2671 if (EatIfPresent(lltok::rbrace)) 2672 return false; 2673 2674 LocTy EltTyLoc = Lex.getLoc(); 2675 Type *Ty = nullptr; 2676 if (parseType(Ty)) 2677 return true; 2678 Body.push_back(Ty); 2679 2680 if (!StructType::isValidElementType(Ty)) 2681 return error(EltTyLoc, "invalid element type for struct"); 2682 2683 while (EatIfPresent(lltok::comma)) { 2684 EltTyLoc = Lex.getLoc(); 2685 if (parseType(Ty)) 2686 return true; 2687 2688 if (!StructType::isValidElementType(Ty)) 2689 return error(EltTyLoc, "invalid element type for struct"); 2690 2691 Body.push_back(Ty); 2692 } 2693 2694 return parseToken(lltok::rbrace, "expected '}' at end of struct"); 2695 } 2696 2697 /// parseArrayVectorType - parse an array or vector type, assuming the first 2698 /// token has already been consumed. 2699 /// Type 2700 /// ::= '[' APSINTVAL 'x' Types ']' 2701 /// ::= '<' APSINTVAL 'x' Types '>' 2702 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>' 2703 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) { 2704 bool Scalable = false; 2705 2706 if (IsVector && Lex.getKind() == lltok::kw_vscale) { 2707 Lex.Lex(); // consume the 'vscale' 2708 if (parseToken(lltok::kw_x, "expected 'x' after vscale")) 2709 return true; 2710 2711 Scalable = true; 2712 } 2713 2714 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 2715 Lex.getAPSIntVal().getBitWidth() > 64) 2716 return tokError("expected number in address space"); 2717 2718 LocTy SizeLoc = Lex.getLoc(); 2719 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 2720 Lex.Lex(); 2721 2722 if (parseToken(lltok::kw_x, "expected 'x' after element count")) 2723 return true; 2724 2725 LocTy TypeLoc = Lex.getLoc(); 2726 Type *EltTy = nullptr; 2727 if (parseType(EltTy)) 2728 return true; 2729 2730 if (parseToken(IsVector ? lltok::greater : lltok::rsquare, 2731 "expected end of sequential type")) 2732 return true; 2733 2734 if (IsVector) { 2735 if (Size == 0) 2736 return error(SizeLoc, "zero element vector is illegal"); 2737 if ((unsigned)Size != Size) 2738 return error(SizeLoc, "size too large for vector"); 2739 if (!VectorType::isValidElementType(EltTy)) 2740 return error(TypeLoc, "invalid vector element type"); 2741 Result = VectorType::get(EltTy, unsigned(Size), Scalable); 2742 } else { 2743 if (!ArrayType::isValidElementType(EltTy)) 2744 return error(TypeLoc, "invalid array element type"); 2745 Result = ArrayType::get(EltTy, Size); 2746 } 2747 return false; 2748 } 2749 2750 //===----------------------------------------------------------------------===// 2751 // Function Semantic Analysis. 2752 //===----------------------------------------------------------------------===// 2753 2754 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 2755 int functionNumber) 2756 : P(p), F(f), FunctionNumber(functionNumber) { 2757 2758 // Insert unnamed arguments into the NumberedVals list. 2759 for (Argument &A : F.args()) 2760 if (!A.hasName()) 2761 NumberedVals.push_back(&A); 2762 } 2763 2764 LLParser::PerFunctionState::~PerFunctionState() { 2765 // If there were any forward referenced non-basicblock values, delete them. 2766 2767 for (const auto &P : ForwardRefVals) { 2768 if (isa<BasicBlock>(P.second.first)) 2769 continue; 2770 P.second.first->replaceAllUsesWith( 2771 UndefValue::get(P.second.first->getType())); 2772 P.second.first->deleteValue(); 2773 } 2774 2775 for (const auto &P : ForwardRefValIDs) { 2776 if (isa<BasicBlock>(P.second.first)) 2777 continue; 2778 P.second.first->replaceAllUsesWith( 2779 UndefValue::get(P.second.first->getType())); 2780 P.second.first->deleteValue(); 2781 } 2782 } 2783 2784 bool LLParser::PerFunctionState::finishFunction() { 2785 if (!ForwardRefVals.empty()) 2786 return P.error(ForwardRefVals.begin()->second.second, 2787 "use of undefined value '%" + ForwardRefVals.begin()->first + 2788 "'"); 2789 if (!ForwardRefValIDs.empty()) 2790 return P.error(ForwardRefValIDs.begin()->second.second, 2791 "use of undefined value '%" + 2792 Twine(ForwardRefValIDs.begin()->first) + "'"); 2793 return false; 2794 } 2795 2796 /// getVal - Get a value with the specified name or ID, creating a 2797 /// forward reference record if needed. This can return null if the value 2798 /// exists but does not have the right type. 2799 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty, 2800 LocTy Loc) { 2801 // Look this name up in the normal function symbol table. 2802 Value *Val = F.getValueSymbolTable()->lookup(Name); 2803 2804 // If this is a forward reference for the value, see if we already created a 2805 // forward ref record. 2806 if (!Val) { 2807 auto I = ForwardRefVals.find(Name); 2808 if (I != ForwardRefVals.end()) 2809 Val = I->second.first; 2810 } 2811 2812 // If we have the value in the symbol table or fwd-ref table, return it. 2813 if (Val) 2814 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val); 2815 2816 // Don't make placeholders with invalid type. 2817 if (!Ty->isFirstClassType()) { 2818 P.error(Loc, "invalid use of a non-first-class type"); 2819 return nullptr; 2820 } 2821 2822 // Otherwise, create a new forward reference for this value and remember it. 2823 Value *FwdVal; 2824 if (Ty->isLabelTy()) { 2825 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 2826 } else { 2827 FwdVal = new Argument(Ty, Name); 2828 } 2829 2830 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 2831 return FwdVal; 2832 } 2833 2834 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) { 2835 // Look this name up in the normal function symbol table. 2836 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr; 2837 2838 // If this is a forward reference for the value, see if we already created a 2839 // forward ref record. 2840 if (!Val) { 2841 auto I = ForwardRefValIDs.find(ID); 2842 if (I != ForwardRefValIDs.end()) 2843 Val = I->second.first; 2844 } 2845 2846 // If we have the value in the symbol table or fwd-ref table, return it. 2847 if (Val) 2848 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val); 2849 2850 if (!Ty->isFirstClassType()) { 2851 P.error(Loc, "invalid use of a non-first-class type"); 2852 return nullptr; 2853 } 2854 2855 // Otherwise, create a new forward reference for this value and remember it. 2856 Value *FwdVal; 2857 if (Ty->isLabelTy()) { 2858 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 2859 } else { 2860 FwdVal = new Argument(Ty); 2861 } 2862 2863 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 2864 return FwdVal; 2865 } 2866 2867 /// setInstName - After an instruction is parsed and inserted into its 2868 /// basic block, this installs its name. 2869 bool LLParser::PerFunctionState::setInstName(int NameID, 2870 const std::string &NameStr, 2871 LocTy NameLoc, Instruction *Inst) { 2872 // If this instruction has void type, it cannot have a name or ID specified. 2873 if (Inst->getType()->isVoidTy()) { 2874 if (NameID != -1 || !NameStr.empty()) 2875 return P.error(NameLoc, "instructions returning void cannot have a name"); 2876 return false; 2877 } 2878 2879 // If this was a numbered instruction, verify that the instruction is the 2880 // expected value and resolve any forward references. 2881 if (NameStr.empty()) { 2882 // If neither a name nor an ID was specified, just use the next ID. 2883 if (NameID == -1) 2884 NameID = NumberedVals.size(); 2885 2886 if (unsigned(NameID) != NumberedVals.size()) 2887 return P.error(NameLoc, "instruction expected to be numbered '%" + 2888 Twine(NumberedVals.size()) + "'"); 2889 2890 auto FI = ForwardRefValIDs.find(NameID); 2891 if (FI != ForwardRefValIDs.end()) { 2892 Value *Sentinel = FI->second.first; 2893 if (Sentinel->getType() != Inst->getType()) 2894 return P.error(NameLoc, "instruction forward referenced with type '" + 2895 getTypeString(FI->second.first->getType()) + 2896 "'"); 2897 2898 Sentinel->replaceAllUsesWith(Inst); 2899 Sentinel->deleteValue(); 2900 ForwardRefValIDs.erase(FI); 2901 } 2902 2903 NumberedVals.push_back(Inst); 2904 return false; 2905 } 2906 2907 // Otherwise, the instruction had a name. Resolve forward refs and set it. 2908 auto FI = ForwardRefVals.find(NameStr); 2909 if (FI != ForwardRefVals.end()) { 2910 Value *Sentinel = FI->second.first; 2911 if (Sentinel->getType() != Inst->getType()) 2912 return P.error(NameLoc, "instruction forward referenced with type '" + 2913 getTypeString(FI->second.first->getType()) + 2914 "'"); 2915 2916 Sentinel->replaceAllUsesWith(Inst); 2917 Sentinel->deleteValue(); 2918 ForwardRefVals.erase(FI); 2919 } 2920 2921 // Set the name on the instruction. 2922 Inst->setName(NameStr); 2923 2924 if (Inst->getName() != NameStr) 2925 return P.error(NameLoc, "multiple definition of local value named '" + 2926 NameStr + "'"); 2927 return false; 2928 } 2929 2930 /// getBB - Get a basic block with the specified name or ID, creating a 2931 /// forward reference record if needed. 2932 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name, 2933 LocTy Loc) { 2934 return dyn_cast_or_null<BasicBlock>( 2935 getVal(Name, Type::getLabelTy(F.getContext()), Loc)); 2936 } 2937 2938 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) { 2939 return dyn_cast_or_null<BasicBlock>( 2940 getVal(ID, Type::getLabelTy(F.getContext()), Loc)); 2941 } 2942 2943 /// defineBB - Define the specified basic block, which is either named or 2944 /// unnamed. If there is an error, this returns null otherwise it returns 2945 /// the block being defined. 2946 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name, 2947 int NameID, LocTy Loc) { 2948 BasicBlock *BB; 2949 if (Name.empty()) { 2950 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) { 2951 P.error(Loc, "label expected to be numbered '" + 2952 Twine(NumberedVals.size()) + "'"); 2953 return nullptr; 2954 } 2955 BB = getBB(NumberedVals.size(), Loc); 2956 if (!BB) { 2957 P.error(Loc, "unable to create block numbered '" + 2958 Twine(NumberedVals.size()) + "'"); 2959 return nullptr; 2960 } 2961 } else { 2962 BB = getBB(Name, Loc); 2963 if (!BB) { 2964 P.error(Loc, "unable to create block named '" + Name + "'"); 2965 return nullptr; 2966 } 2967 } 2968 2969 // Move the block to the end of the function. Forward ref'd blocks are 2970 // inserted wherever they happen to be referenced. 2971 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB); 2972 2973 // Remove the block from forward ref sets. 2974 if (Name.empty()) { 2975 ForwardRefValIDs.erase(NumberedVals.size()); 2976 NumberedVals.push_back(BB); 2977 } else { 2978 // BB forward references are already in the function symbol table. 2979 ForwardRefVals.erase(Name); 2980 } 2981 2982 return BB; 2983 } 2984 2985 //===----------------------------------------------------------------------===// 2986 // Constants. 2987 //===----------------------------------------------------------------------===// 2988 2989 /// parseValID - parse an abstract value that doesn't necessarily have a 2990 /// type implied. For example, if we parse "4" we don't know what integer type 2991 /// it has. The value will later be combined with its type and checked for 2992 /// basic correctness. PFS is used to convert function-local operands of 2993 /// metadata (since metadata operands are not just parsed here but also 2994 /// converted to values). PFS can be null when we are not parsing metadata 2995 /// values inside a function. 2996 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) { 2997 ID.Loc = Lex.getLoc(); 2998 switch (Lex.getKind()) { 2999 default: 3000 return tokError("expected value token"); 3001 case lltok::GlobalID: // @42 3002 ID.UIntVal = Lex.getUIntVal(); 3003 ID.Kind = ValID::t_GlobalID; 3004 break; 3005 case lltok::GlobalVar: // @foo 3006 ID.StrVal = Lex.getStrVal(); 3007 ID.Kind = ValID::t_GlobalName; 3008 break; 3009 case lltok::LocalVarID: // %42 3010 ID.UIntVal = Lex.getUIntVal(); 3011 ID.Kind = ValID::t_LocalID; 3012 break; 3013 case lltok::LocalVar: // %foo 3014 ID.StrVal = Lex.getStrVal(); 3015 ID.Kind = ValID::t_LocalName; 3016 break; 3017 case lltok::APSInt: 3018 ID.APSIntVal = Lex.getAPSIntVal(); 3019 ID.Kind = ValID::t_APSInt; 3020 break; 3021 case lltok::APFloat: 3022 ID.APFloatVal = Lex.getAPFloatVal(); 3023 ID.Kind = ValID::t_APFloat; 3024 break; 3025 case lltok::kw_true: 3026 ID.ConstantVal = ConstantInt::getTrue(Context); 3027 ID.Kind = ValID::t_Constant; 3028 break; 3029 case lltok::kw_false: 3030 ID.ConstantVal = ConstantInt::getFalse(Context); 3031 ID.Kind = ValID::t_Constant; 3032 break; 3033 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 3034 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 3035 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break; 3036 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 3037 case lltok::kw_none: ID.Kind = ValID::t_None; break; 3038 3039 case lltok::lbrace: { 3040 // ValID ::= '{' ConstVector '}' 3041 Lex.Lex(); 3042 SmallVector<Constant*, 16> Elts; 3043 if (parseGlobalValueVector(Elts) || 3044 parseToken(lltok::rbrace, "expected end of struct constant")) 3045 return true; 3046 3047 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3048 ID.UIntVal = Elts.size(); 3049 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3050 Elts.size() * sizeof(Elts[0])); 3051 ID.Kind = ValID::t_ConstantStruct; 3052 return false; 3053 } 3054 case lltok::less: { 3055 // ValID ::= '<' ConstVector '>' --> Vector. 3056 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 3057 Lex.Lex(); 3058 bool isPackedStruct = EatIfPresent(lltok::lbrace); 3059 3060 SmallVector<Constant*, 16> Elts; 3061 LocTy FirstEltLoc = Lex.getLoc(); 3062 if (parseGlobalValueVector(Elts) || 3063 (isPackedStruct && 3064 parseToken(lltok::rbrace, "expected end of packed struct")) || 3065 parseToken(lltok::greater, "expected end of constant")) 3066 return true; 3067 3068 if (isPackedStruct) { 3069 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3070 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3071 Elts.size() * sizeof(Elts[0])); 3072 ID.UIntVal = Elts.size(); 3073 ID.Kind = ValID::t_PackedConstantStruct; 3074 return false; 3075 } 3076 3077 if (Elts.empty()) 3078 return error(ID.Loc, "constant vector must not be empty"); 3079 3080 if (!Elts[0]->getType()->isIntegerTy() && 3081 !Elts[0]->getType()->isFloatingPointTy() && 3082 !Elts[0]->getType()->isPointerTy()) 3083 return error( 3084 FirstEltLoc, 3085 "vector elements must have integer, pointer or floating point type"); 3086 3087 // Verify that all the vector elements have the same type. 3088 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 3089 if (Elts[i]->getType() != Elts[0]->getType()) 3090 return error(FirstEltLoc, "vector element #" + Twine(i) + 3091 " is not of type '" + 3092 getTypeString(Elts[0]->getType())); 3093 3094 ID.ConstantVal = ConstantVector::get(Elts); 3095 ID.Kind = ValID::t_Constant; 3096 return false; 3097 } 3098 case lltok::lsquare: { // Array Constant 3099 Lex.Lex(); 3100 SmallVector<Constant*, 16> Elts; 3101 LocTy FirstEltLoc = Lex.getLoc(); 3102 if (parseGlobalValueVector(Elts) || 3103 parseToken(lltok::rsquare, "expected end of array constant")) 3104 return true; 3105 3106 // Handle empty element. 3107 if (Elts.empty()) { 3108 // Use undef instead of an array because it's inconvenient to determine 3109 // the element type at this point, there being no elements to examine. 3110 ID.Kind = ValID::t_EmptyArray; 3111 return false; 3112 } 3113 3114 if (!Elts[0]->getType()->isFirstClassType()) 3115 return error(FirstEltLoc, "invalid array element type: " + 3116 getTypeString(Elts[0]->getType())); 3117 3118 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 3119 3120 // Verify all elements are correct type! 3121 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 3122 if (Elts[i]->getType() != Elts[0]->getType()) 3123 return error(FirstEltLoc, "array element #" + Twine(i) + 3124 " is not of type '" + 3125 getTypeString(Elts[0]->getType())); 3126 } 3127 3128 ID.ConstantVal = ConstantArray::get(ATy, Elts); 3129 ID.Kind = ValID::t_Constant; 3130 return false; 3131 } 3132 case lltok::kw_c: // c "foo" 3133 Lex.Lex(); 3134 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 3135 false); 3136 if (parseToken(lltok::StringConstant, "expected string")) 3137 return true; 3138 ID.Kind = ValID::t_Constant; 3139 return false; 3140 3141 case lltok::kw_asm: { 3142 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 3143 // STRINGCONSTANT 3144 bool HasSideEffect, AlignStack, AsmDialect, CanThrow; 3145 Lex.Lex(); 3146 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 3147 parseOptionalToken(lltok::kw_alignstack, AlignStack) || 3148 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 3149 parseOptionalToken(lltok::kw_unwind, CanThrow) || 3150 parseStringConstant(ID.StrVal) || 3151 parseToken(lltok::comma, "expected comma in inline asm expression") || 3152 parseToken(lltok::StringConstant, "expected constraint string")) 3153 return true; 3154 ID.StrVal2 = Lex.getStrVal(); 3155 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) | 3156 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3); 3157 ID.Kind = ValID::t_InlineAsm; 3158 return false; 3159 } 3160 3161 case lltok::kw_blockaddress: { 3162 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 3163 Lex.Lex(); 3164 3165 ValID Fn, Label; 3166 3167 if (parseToken(lltok::lparen, "expected '(' in block address expression") || 3168 parseValID(Fn, PFS) || 3169 parseToken(lltok::comma, 3170 "expected comma in block address expression") || 3171 parseValID(Label, PFS) || 3172 parseToken(lltok::rparen, "expected ')' in block address expression")) 3173 return true; 3174 3175 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3176 return error(Fn.Loc, "expected function name in blockaddress"); 3177 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 3178 return error(Label.Loc, "expected basic block name in blockaddress"); 3179 3180 // Try to find the function (but skip it if it's forward-referenced). 3181 GlobalValue *GV = nullptr; 3182 if (Fn.Kind == ValID::t_GlobalID) { 3183 if (Fn.UIntVal < NumberedVals.size()) 3184 GV = NumberedVals[Fn.UIntVal]; 3185 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3186 GV = M->getNamedValue(Fn.StrVal); 3187 } 3188 Function *F = nullptr; 3189 if (GV) { 3190 // Confirm that it's actually a function with a definition. 3191 if (!isa<Function>(GV)) 3192 return error(Fn.Loc, "expected function name in blockaddress"); 3193 F = cast<Function>(GV); 3194 if (F->isDeclaration()) 3195 return error(Fn.Loc, "cannot take blockaddress inside a declaration"); 3196 } 3197 3198 if (!F) { 3199 // Make a global variable as a placeholder for this reference. 3200 GlobalValue *&FwdRef = 3201 ForwardRefBlockAddresses.insert(std::make_pair( 3202 std::move(Fn), 3203 std::map<ValID, GlobalValue *>())) 3204 .first->second.insert(std::make_pair(std::move(Label), nullptr)) 3205 .first->second; 3206 if (!FwdRef) { 3207 unsigned FwdDeclAS; 3208 if (ExpectedTy) { 3209 // If we know the type that the blockaddress is being assigned to, 3210 // we can use the address space of that type. 3211 if (!ExpectedTy->isPointerTy()) 3212 return error(ID.Loc, 3213 "type of blockaddress must be a pointer and not '" + 3214 getTypeString(ExpectedTy) + "'"); 3215 FwdDeclAS = ExpectedTy->getPointerAddressSpace(); 3216 } else if (PFS) { 3217 // Otherwise, we default the address space of the current function. 3218 FwdDeclAS = PFS->getFunction().getAddressSpace(); 3219 } else { 3220 llvm_unreachable("Unknown address space for blockaddress"); 3221 } 3222 FwdRef = new GlobalVariable( 3223 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage, 3224 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS); 3225 } 3226 3227 ID.ConstantVal = FwdRef; 3228 ID.Kind = ValID::t_Constant; 3229 return false; 3230 } 3231 3232 // We found the function; now find the basic block. Don't use PFS, since we 3233 // might be inside a constant expression. 3234 BasicBlock *BB; 3235 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { 3236 if (Label.Kind == ValID::t_LocalID) 3237 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc); 3238 else 3239 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc); 3240 if (!BB) 3241 return error(Label.Loc, "referenced value is not a basic block"); 3242 } else { 3243 if (Label.Kind == ValID::t_LocalID) 3244 return error(Label.Loc, "cannot take address of numeric label after " 3245 "the function is defined"); 3246 BB = dyn_cast_or_null<BasicBlock>( 3247 F->getValueSymbolTable()->lookup(Label.StrVal)); 3248 if (!BB) 3249 return error(Label.Loc, "referenced value is not a basic block"); 3250 } 3251 3252 ID.ConstantVal = BlockAddress::get(F, BB); 3253 ID.Kind = ValID::t_Constant; 3254 return false; 3255 } 3256 3257 case lltok::kw_dso_local_equivalent: { 3258 // ValID ::= 'dso_local_equivalent' @foo 3259 Lex.Lex(); 3260 3261 ValID Fn; 3262 3263 if (parseValID(Fn, PFS)) 3264 return true; 3265 3266 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3267 return error(Fn.Loc, 3268 "expected global value name in dso_local_equivalent"); 3269 3270 // Try to find the function (but skip it if it's forward-referenced). 3271 GlobalValue *GV = nullptr; 3272 if (Fn.Kind == ValID::t_GlobalID) { 3273 if (Fn.UIntVal < NumberedVals.size()) 3274 GV = NumberedVals[Fn.UIntVal]; 3275 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3276 GV = M->getNamedValue(Fn.StrVal); 3277 } 3278 3279 assert(GV && "Could not find a corresponding global variable"); 3280 3281 if (!GV->getValueType()->isFunctionTy()) 3282 return error(Fn.Loc, "expected a function, alias to function, or ifunc " 3283 "in dso_local_equivalent"); 3284 3285 ID.ConstantVal = DSOLocalEquivalent::get(GV); 3286 ID.Kind = ValID::t_Constant; 3287 return false; 3288 } 3289 3290 case lltok::kw_trunc: 3291 case lltok::kw_zext: 3292 case lltok::kw_sext: 3293 case lltok::kw_fptrunc: 3294 case lltok::kw_fpext: 3295 case lltok::kw_bitcast: 3296 case lltok::kw_addrspacecast: 3297 case lltok::kw_uitofp: 3298 case lltok::kw_sitofp: 3299 case lltok::kw_fptoui: 3300 case lltok::kw_fptosi: 3301 case lltok::kw_inttoptr: 3302 case lltok::kw_ptrtoint: { 3303 unsigned Opc = Lex.getUIntVal(); 3304 Type *DestTy = nullptr; 3305 Constant *SrcVal; 3306 Lex.Lex(); 3307 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") || 3308 parseGlobalTypeAndValue(SrcVal) || 3309 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 3310 parseType(DestTy) || 3311 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 3312 return true; 3313 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 3314 return error(ID.Loc, "invalid cast opcode for cast from '" + 3315 getTypeString(SrcVal->getType()) + "' to '" + 3316 getTypeString(DestTy) + "'"); 3317 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 3318 SrcVal, DestTy); 3319 ID.Kind = ValID::t_Constant; 3320 return false; 3321 } 3322 case lltok::kw_extractvalue: { 3323 Lex.Lex(); 3324 Constant *Val; 3325 SmallVector<unsigned, 4> Indices; 3326 if (parseToken(lltok::lparen, 3327 "expected '(' in extractvalue constantexpr") || 3328 parseGlobalTypeAndValue(Val) || parseIndexList(Indices) || 3329 parseToken(lltok::rparen, "expected ')' in extractvalue constantexpr")) 3330 return true; 3331 3332 if (!Val->getType()->isAggregateType()) 3333 return error(ID.Loc, "extractvalue operand must be aggregate type"); 3334 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 3335 return error(ID.Loc, "invalid indices for extractvalue"); 3336 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices); 3337 ID.Kind = ValID::t_Constant; 3338 return false; 3339 } 3340 case lltok::kw_insertvalue: { 3341 Lex.Lex(); 3342 Constant *Val0, *Val1; 3343 SmallVector<unsigned, 4> Indices; 3344 if (parseToken(lltok::lparen, "expected '(' in insertvalue constantexpr") || 3345 parseGlobalTypeAndValue(Val0) || 3346 parseToken(lltok::comma, 3347 "expected comma in insertvalue constantexpr") || 3348 parseGlobalTypeAndValue(Val1) || parseIndexList(Indices) || 3349 parseToken(lltok::rparen, "expected ')' in insertvalue constantexpr")) 3350 return true; 3351 if (!Val0->getType()->isAggregateType()) 3352 return error(ID.Loc, "insertvalue operand must be aggregate type"); 3353 Type *IndexedType = 3354 ExtractValueInst::getIndexedType(Val0->getType(), Indices); 3355 if (!IndexedType) 3356 return error(ID.Loc, "invalid indices for insertvalue"); 3357 if (IndexedType != Val1->getType()) 3358 return error(ID.Loc, "insertvalue operand and field disagree in type: '" + 3359 getTypeString(Val1->getType()) + 3360 "' instead of '" + getTypeString(IndexedType) + 3361 "'"); 3362 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices); 3363 ID.Kind = ValID::t_Constant; 3364 return false; 3365 } 3366 case lltok::kw_icmp: 3367 case lltok::kw_fcmp: { 3368 unsigned PredVal, Opc = Lex.getUIntVal(); 3369 Constant *Val0, *Val1; 3370 Lex.Lex(); 3371 if (parseCmpPredicate(PredVal, Opc) || 3372 parseToken(lltok::lparen, "expected '(' in compare constantexpr") || 3373 parseGlobalTypeAndValue(Val0) || 3374 parseToken(lltok::comma, "expected comma in compare constantexpr") || 3375 parseGlobalTypeAndValue(Val1) || 3376 parseToken(lltok::rparen, "expected ')' in compare constantexpr")) 3377 return true; 3378 3379 if (Val0->getType() != Val1->getType()) 3380 return error(ID.Loc, "compare operands must have the same type"); 3381 3382 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal; 3383 3384 if (Opc == Instruction::FCmp) { 3385 if (!Val0->getType()->isFPOrFPVectorTy()) 3386 return error(ID.Loc, "fcmp requires floating point operands"); 3387 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1); 3388 } else { 3389 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!"); 3390 if (!Val0->getType()->isIntOrIntVectorTy() && 3391 !Val0->getType()->isPtrOrPtrVectorTy()) 3392 return error(ID.Loc, "icmp requires pointer or integer operands"); 3393 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1); 3394 } 3395 ID.Kind = ValID::t_Constant; 3396 return false; 3397 } 3398 3399 // Unary Operators. 3400 case lltok::kw_fneg: { 3401 unsigned Opc = Lex.getUIntVal(); 3402 Constant *Val; 3403 Lex.Lex(); 3404 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") || 3405 parseGlobalTypeAndValue(Val) || 3406 parseToken(lltok::rparen, "expected ')' in unary constantexpr")) 3407 return true; 3408 3409 // Check that the type is valid for the operator. 3410 switch (Opc) { 3411 case Instruction::FNeg: 3412 if (!Val->getType()->isFPOrFPVectorTy()) 3413 return error(ID.Loc, "constexpr requires fp operands"); 3414 break; 3415 default: llvm_unreachable("Unknown unary operator!"); 3416 } 3417 unsigned Flags = 0; 3418 Constant *C = ConstantExpr::get(Opc, Val, Flags); 3419 ID.ConstantVal = C; 3420 ID.Kind = ValID::t_Constant; 3421 return false; 3422 } 3423 // Binary Operators. 3424 case lltok::kw_add: 3425 case lltok::kw_fadd: 3426 case lltok::kw_sub: 3427 case lltok::kw_fsub: 3428 case lltok::kw_mul: 3429 case lltok::kw_fmul: 3430 case lltok::kw_udiv: 3431 case lltok::kw_sdiv: 3432 case lltok::kw_fdiv: 3433 case lltok::kw_urem: 3434 case lltok::kw_srem: 3435 case lltok::kw_frem: 3436 case lltok::kw_shl: 3437 case lltok::kw_lshr: 3438 case lltok::kw_ashr: { 3439 bool NUW = false; 3440 bool NSW = false; 3441 bool Exact = false; 3442 unsigned Opc = Lex.getUIntVal(); 3443 Constant *Val0, *Val1; 3444 Lex.Lex(); 3445 if (Opc == Instruction::Add || Opc == Instruction::Sub || 3446 Opc == Instruction::Mul || Opc == Instruction::Shl) { 3447 if (EatIfPresent(lltok::kw_nuw)) 3448 NUW = true; 3449 if (EatIfPresent(lltok::kw_nsw)) { 3450 NSW = true; 3451 if (EatIfPresent(lltok::kw_nuw)) 3452 NUW = true; 3453 } 3454 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || 3455 Opc == Instruction::LShr || Opc == Instruction::AShr) { 3456 if (EatIfPresent(lltok::kw_exact)) 3457 Exact = true; 3458 } 3459 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") || 3460 parseGlobalTypeAndValue(Val0) || 3461 parseToken(lltok::comma, "expected comma in binary constantexpr") || 3462 parseGlobalTypeAndValue(Val1) || 3463 parseToken(lltok::rparen, "expected ')' in binary constantexpr")) 3464 return true; 3465 if (Val0->getType() != Val1->getType()) 3466 return error(ID.Loc, "operands of constexpr must have same type"); 3467 // Check that the type is valid for the operator. 3468 switch (Opc) { 3469 case Instruction::Add: 3470 case Instruction::Sub: 3471 case Instruction::Mul: 3472 case Instruction::UDiv: 3473 case Instruction::SDiv: 3474 case Instruction::URem: 3475 case Instruction::SRem: 3476 case Instruction::Shl: 3477 case Instruction::AShr: 3478 case Instruction::LShr: 3479 if (!Val0->getType()->isIntOrIntVectorTy()) 3480 return error(ID.Loc, "constexpr requires integer operands"); 3481 break; 3482 case Instruction::FAdd: 3483 case Instruction::FSub: 3484 case Instruction::FMul: 3485 case Instruction::FDiv: 3486 case Instruction::FRem: 3487 if (!Val0->getType()->isFPOrFPVectorTy()) 3488 return error(ID.Loc, "constexpr requires fp operands"); 3489 break; 3490 default: llvm_unreachable("Unknown binary operator!"); 3491 } 3492 unsigned Flags = 0; 3493 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3494 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 3495 if (Exact) Flags |= PossiblyExactOperator::IsExact; 3496 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags); 3497 ID.ConstantVal = C; 3498 ID.Kind = ValID::t_Constant; 3499 return false; 3500 } 3501 3502 // Logical Operations 3503 case lltok::kw_and: 3504 case lltok::kw_or: 3505 case lltok::kw_xor: { 3506 unsigned Opc = Lex.getUIntVal(); 3507 Constant *Val0, *Val1; 3508 Lex.Lex(); 3509 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") || 3510 parseGlobalTypeAndValue(Val0) || 3511 parseToken(lltok::comma, "expected comma in logical constantexpr") || 3512 parseGlobalTypeAndValue(Val1) || 3513 parseToken(lltok::rparen, "expected ')' in logical constantexpr")) 3514 return true; 3515 if (Val0->getType() != Val1->getType()) 3516 return error(ID.Loc, "operands of constexpr must have same type"); 3517 if (!Val0->getType()->isIntOrIntVectorTy()) 3518 return error(ID.Loc, 3519 "constexpr requires integer or integer vector operands"); 3520 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1); 3521 ID.Kind = ValID::t_Constant; 3522 return false; 3523 } 3524 3525 case lltok::kw_getelementptr: 3526 case lltok::kw_shufflevector: 3527 case lltok::kw_insertelement: 3528 case lltok::kw_extractelement: 3529 case lltok::kw_select: { 3530 unsigned Opc = Lex.getUIntVal(); 3531 SmallVector<Constant*, 16> Elts; 3532 bool InBounds = false; 3533 Type *Ty; 3534 Lex.Lex(); 3535 3536 if (Opc == Instruction::GetElementPtr) 3537 InBounds = EatIfPresent(lltok::kw_inbounds); 3538 3539 if (parseToken(lltok::lparen, "expected '(' in constantexpr")) 3540 return true; 3541 3542 LocTy ExplicitTypeLoc = Lex.getLoc(); 3543 if (Opc == Instruction::GetElementPtr) { 3544 if (parseType(Ty) || 3545 parseToken(lltok::comma, "expected comma after getelementptr's type")) 3546 return true; 3547 } 3548 3549 Optional<unsigned> InRangeOp; 3550 if (parseGlobalValueVector( 3551 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) || 3552 parseToken(lltok::rparen, "expected ')' in constantexpr")) 3553 return true; 3554 3555 if (Opc == Instruction::GetElementPtr) { 3556 if (Elts.size() == 0 || 3557 !Elts[0]->getType()->isPtrOrPtrVectorTy()) 3558 return error(ID.Loc, "base of getelementptr must be a pointer"); 3559 3560 Type *BaseType = Elts[0]->getType(); 3561 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType()); 3562 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) { 3563 return error( 3564 ExplicitTypeLoc, 3565 typeComparisonErrorMessage( 3566 "explicit pointee type doesn't match operand's pointee type", 3567 Ty, BasePointerType->getElementType())); 3568 } 3569 3570 unsigned GEPWidth = 3571 BaseType->isVectorTy() 3572 ? cast<FixedVectorType>(BaseType)->getNumElements() 3573 : 0; 3574 3575 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 3576 for (Constant *Val : Indices) { 3577 Type *ValTy = Val->getType(); 3578 if (!ValTy->isIntOrIntVectorTy()) 3579 return error(ID.Loc, "getelementptr index must be an integer"); 3580 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) { 3581 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements(); 3582 if (GEPWidth && (ValNumEl != GEPWidth)) 3583 return error( 3584 ID.Loc, 3585 "getelementptr vector index has a wrong number of elements"); 3586 // GEPWidth may have been unknown because the base is a scalar, 3587 // but it is known now. 3588 GEPWidth = ValNumEl; 3589 } 3590 } 3591 3592 SmallPtrSet<Type*, 4> Visited; 3593 if (!Indices.empty() && !Ty->isSized(&Visited)) 3594 return error(ID.Loc, "base element of getelementptr must be sized"); 3595 3596 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 3597 return error(ID.Loc, "invalid getelementptr indices"); 3598 3599 if (InRangeOp) { 3600 if (*InRangeOp == 0) 3601 return error(ID.Loc, 3602 "inrange keyword may not appear on pointer operand"); 3603 --*InRangeOp; 3604 } 3605 3606 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, 3607 InBounds, InRangeOp); 3608 } else if (Opc == Instruction::Select) { 3609 if (Elts.size() != 3) 3610 return error(ID.Loc, "expected three operands to select"); 3611 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1], 3612 Elts[2])) 3613 return error(ID.Loc, Reason); 3614 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]); 3615 } else if (Opc == Instruction::ShuffleVector) { 3616 if (Elts.size() != 3) 3617 return error(ID.Loc, "expected three operands to shufflevector"); 3618 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3619 return error(ID.Loc, "invalid operands to shufflevector"); 3620 SmallVector<int, 16> Mask; 3621 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask); 3622 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask); 3623 } else if (Opc == Instruction::ExtractElement) { 3624 if (Elts.size() != 2) 3625 return error(ID.Loc, "expected two operands to extractelement"); 3626 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 3627 return error(ID.Loc, "invalid extractelement operands"); 3628 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 3629 } else { 3630 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 3631 if (Elts.size() != 3) 3632 return error(ID.Loc, "expected three operands to insertelement"); 3633 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 3634 return error(ID.Loc, "invalid insertelement operands"); 3635 ID.ConstantVal = 3636 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 3637 } 3638 3639 ID.Kind = ValID::t_Constant; 3640 return false; 3641 } 3642 } 3643 3644 Lex.Lex(); 3645 return false; 3646 } 3647 3648 /// parseGlobalValue - parse a global value with the specified type. 3649 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) { 3650 C = nullptr; 3651 ValID ID; 3652 Value *V = nullptr; 3653 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) || 3654 convertValIDToValue(Ty, ID, V, nullptr); 3655 if (V && !(C = dyn_cast<Constant>(V))) 3656 return error(ID.Loc, "global values must be constants"); 3657 return Parsed; 3658 } 3659 3660 bool LLParser::parseGlobalTypeAndValue(Constant *&V) { 3661 Type *Ty = nullptr; 3662 return parseType(Ty) || parseGlobalValue(Ty, V); 3663 } 3664 3665 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 3666 C = nullptr; 3667 3668 LocTy KwLoc = Lex.getLoc(); 3669 if (!EatIfPresent(lltok::kw_comdat)) 3670 return false; 3671 3672 if (EatIfPresent(lltok::lparen)) { 3673 if (Lex.getKind() != lltok::ComdatVar) 3674 return tokError("expected comdat variable"); 3675 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 3676 Lex.Lex(); 3677 if (parseToken(lltok::rparen, "expected ')' after comdat var")) 3678 return true; 3679 } else { 3680 if (GlobalName.empty()) 3681 return tokError("comdat cannot be unnamed"); 3682 C = getComdat(std::string(GlobalName), KwLoc); 3683 } 3684 3685 return false; 3686 } 3687 3688 /// parseGlobalValueVector 3689 /// ::= /*empty*/ 3690 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)* 3691 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts, 3692 Optional<unsigned> *InRangeOp) { 3693 // Empty list. 3694 if (Lex.getKind() == lltok::rbrace || 3695 Lex.getKind() == lltok::rsquare || 3696 Lex.getKind() == lltok::greater || 3697 Lex.getKind() == lltok::rparen) 3698 return false; 3699 3700 do { 3701 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange)) 3702 *InRangeOp = Elts.size(); 3703 3704 Constant *C; 3705 if (parseGlobalTypeAndValue(C)) 3706 return true; 3707 Elts.push_back(C); 3708 } while (EatIfPresent(lltok::comma)); 3709 3710 return false; 3711 } 3712 3713 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) { 3714 SmallVector<Metadata *, 16> Elts; 3715 if (parseMDNodeVector(Elts)) 3716 return true; 3717 3718 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 3719 return false; 3720 } 3721 3722 /// MDNode: 3723 /// ::= !{ ... } 3724 /// ::= !7 3725 /// ::= !DILocation(...) 3726 bool LLParser::parseMDNode(MDNode *&N) { 3727 if (Lex.getKind() == lltok::MetadataVar) 3728 return parseSpecializedMDNode(N); 3729 3730 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N); 3731 } 3732 3733 bool LLParser::parseMDNodeTail(MDNode *&N) { 3734 // !{ ... } 3735 if (Lex.getKind() == lltok::lbrace) 3736 return parseMDTuple(N); 3737 3738 // !42 3739 return parseMDNodeID(N); 3740 } 3741 3742 namespace { 3743 3744 /// Structure to represent an optional metadata field. 3745 template <class FieldTy> struct MDFieldImpl { 3746 typedef MDFieldImpl ImplTy; 3747 FieldTy Val; 3748 bool Seen; 3749 3750 void assign(FieldTy Val) { 3751 Seen = true; 3752 this->Val = std::move(Val); 3753 } 3754 3755 explicit MDFieldImpl(FieldTy Default) 3756 : Val(std::move(Default)), Seen(false) {} 3757 }; 3758 3759 /// Structure to represent an optional metadata field that 3760 /// can be of either type (A or B) and encapsulates the 3761 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 3762 /// to reimplement the specifics for representing each Field. 3763 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 3764 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 3765 FieldTypeA A; 3766 FieldTypeB B; 3767 bool Seen; 3768 3769 enum { 3770 IsInvalid = 0, 3771 IsTypeA = 1, 3772 IsTypeB = 2 3773 } WhatIs; 3774 3775 void assign(FieldTypeA A) { 3776 Seen = true; 3777 this->A = std::move(A); 3778 WhatIs = IsTypeA; 3779 } 3780 3781 void assign(FieldTypeB B) { 3782 Seen = true; 3783 this->B = std::move(B); 3784 WhatIs = IsTypeB; 3785 } 3786 3787 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 3788 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 3789 WhatIs(IsInvalid) {} 3790 }; 3791 3792 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 3793 uint64_t Max; 3794 3795 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 3796 : ImplTy(Default), Max(Max) {} 3797 }; 3798 3799 struct LineField : public MDUnsignedField { 3800 LineField() : MDUnsignedField(0, UINT32_MAX) {} 3801 }; 3802 3803 struct ColumnField : public MDUnsignedField { 3804 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 3805 }; 3806 3807 struct DwarfTagField : public MDUnsignedField { 3808 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 3809 DwarfTagField(dwarf::Tag DefaultTag) 3810 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 3811 }; 3812 3813 struct DwarfMacinfoTypeField : public MDUnsignedField { 3814 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 3815 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 3816 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 3817 }; 3818 3819 struct DwarfAttEncodingField : public MDUnsignedField { 3820 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 3821 }; 3822 3823 struct DwarfVirtualityField : public MDUnsignedField { 3824 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 3825 }; 3826 3827 struct DwarfLangField : public MDUnsignedField { 3828 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 3829 }; 3830 3831 struct DwarfCCField : public MDUnsignedField { 3832 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 3833 }; 3834 3835 struct EmissionKindField : public MDUnsignedField { 3836 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 3837 }; 3838 3839 struct NameTableKindField : public MDUnsignedField { 3840 NameTableKindField() 3841 : MDUnsignedField( 3842 0, (unsigned) 3843 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 3844 }; 3845 3846 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 3847 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 3848 }; 3849 3850 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 3851 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 3852 }; 3853 3854 struct MDAPSIntField : public MDFieldImpl<APSInt> { 3855 MDAPSIntField() : ImplTy(APSInt()) {} 3856 }; 3857 3858 struct MDSignedField : public MDFieldImpl<int64_t> { 3859 int64_t Min; 3860 int64_t Max; 3861 3862 MDSignedField(int64_t Default = 0) 3863 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {} 3864 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 3865 : ImplTy(Default), Min(Min), Max(Max) {} 3866 }; 3867 3868 struct MDBoolField : public MDFieldImpl<bool> { 3869 MDBoolField(bool Default = false) : ImplTy(Default) {} 3870 }; 3871 3872 struct MDField : public MDFieldImpl<Metadata *> { 3873 bool AllowNull; 3874 3875 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 3876 }; 3877 3878 struct MDStringField : public MDFieldImpl<MDString *> { 3879 bool AllowEmpty; 3880 MDStringField(bool AllowEmpty = true) 3881 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 3882 }; 3883 3884 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 3885 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 3886 }; 3887 3888 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 3889 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 3890 }; 3891 3892 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 3893 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 3894 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 3895 3896 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 3897 bool AllowNull = true) 3898 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 3899 3900 bool isMDSignedField() const { return WhatIs == IsTypeA; } 3901 bool isMDField() const { return WhatIs == IsTypeB; } 3902 int64_t getMDSignedValue() const { 3903 assert(isMDSignedField() && "Wrong field type"); 3904 return A.Val; 3905 } 3906 Metadata *getMDFieldValue() const { 3907 assert(isMDField() && "Wrong field type"); 3908 return B.Val; 3909 } 3910 }; 3911 3912 } // end anonymous namespace 3913 3914 namespace llvm { 3915 3916 template <> 3917 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { 3918 if (Lex.getKind() != lltok::APSInt) 3919 return tokError("expected integer"); 3920 3921 Result.assign(Lex.getAPSIntVal()); 3922 Lex.Lex(); 3923 return false; 3924 } 3925 3926 template <> 3927 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 3928 MDUnsignedField &Result) { 3929 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 3930 return tokError("expected unsigned integer"); 3931 3932 auto &U = Lex.getAPSIntVal(); 3933 if (U.ugt(Result.Max)) 3934 return tokError("value for '" + Name + "' too large, limit is " + 3935 Twine(Result.Max)); 3936 Result.assign(U.getZExtValue()); 3937 assert(Result.Val <= Result.Max && "Expected value in range"); 3938 Lex.Lex(); 3939 return false; 3940 } 3941 3942 template <> 3943 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) { 3944 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3945 } 3946 template <> 3947 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 3948 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3949 } 3950 3951 template <> 3952 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 3953 if (Lex.getKind() == lltok::APSInt) 3954 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3955 3956 if (Lex.getKind() != lltok::DwarfTag) 3957 return tokError("expected DWARF tag"); 3958 3959 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 3960 if (Tag == dwarf::DW_TAG_invalid) 3961 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 3962 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 3963 3964 Result.assign(Tag); 3965 Lex.Lex(); 3966 return false; 3967 } 3968 3969 template <> 3970 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 3971 DwarfMacinfoTypeField &Result) { 3972 if (Lex.getKind() == lltok::APSInt) 3973 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3974 3975 if (Lex.getKind() != lltok::DwarfMacinfo) 3976 return tokError("expected DWARF macinfo type"); 3977 3978 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 3979 if (Macinfo == dwarf::DW_MACINFO_invalid) 3980 return tokError("invalid DWARF macinfo type" + Twine(" '") + 3981 Lex.getStrVal() + "'"); 3982 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 3983 3984 Result.assign(Macinfo); 3985 Lex.Lex(); 3986 return false; 3987 } 3988 3989 template <> 3990 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 3991 DwarfVirtualityField &Result) { 3992 if (Lex.getKind() == lltok::APSInt) 3993 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 3994 3995 if (Lex.getKind() != lltok::DwarfVirtuality) 3996 return tokError("expected DWARF virtuality code"); 3997 3998 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 3999 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4000 return tokError("invalid DWARF virtuality code" + Twine(" '") + 4001 Lex.getStrVal() + "'"); 4002 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4003 Result.assign(Virtuality); 4004 Lex.Lex(); 4005 return false; 4006 } 4007 4008 template <> 4009 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4010 if (Lex.getKind() == lltok::APSInt) 4011 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4012 4013 if (Lex.getKind() != lltok::DwarfLang) 4014 return tokError("expected DWARF language"); 4015 4016 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4017 if (!Lang) 4018 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4019 "'"); 4020 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4021 Result.assign(Lang); 4022 Lex.Lex(); 4023 return false; 4024 } 4025 4026 template <> 4027 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4028 if (Lex.getKind() == lltok::APSInt) 4029 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4030 4031 if (Lex.getKind() != lltok::DwarfCC) 4032 return tokError("expected DWARF calling convention"); 4033 4034 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4035 if (!CC) 4036 return tokError("invalid DWARF calling convention" + Twine(" '") + 4037 Lex.getStrVal() + "'"); 4038 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4039 Result.assign(CC); 4040 Lex.Lex(); 4041 return false; 4042 } 4043 4044 template <> 4045 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4046 EmissionKindField &Result) { 4047 if (Lex.getKind() == lltok::APSInt) 4048 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4049 4050 if (Lex.getKind() != lltok::EmissionKind) 4051 return tokError("expected emission kind"); 4052 4053 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4054 if (!Kind) 4055 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4056 "'"); 4057 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4058 Result.assign(*Kind); 4059 Lex.Lex(); 4060 return false; 4061 } 4062 4063 template <> 4064 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4065 NameTableKindField &Result) { 4066 if (Lex.getKind() == lltok::APSInt) 4067 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4068 4069 if (Lex.getKind() != lltok::NameTableKind) 4070 return tokError("expected nameTable kind"); 4071 4072 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4073 if (!Kind) 4074 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4075 "'"); 4076 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4077 Result.assign((unsigned)*Kind); 4078 Lex.Lex(); 4079 return false; 4080 } 4081 4082 template <> 4083 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4084 DwarfAttEncodingField &Result) { 4085 if (Lex.getKind() == lltok::APSInt) 4086 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4087 4088 if (Lex.getKind() != lltok::DwarfAttEncoding) 4089 return tokError("expected DWARF type attribute encoding"); 4090 4091 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4092 if (!Encoding) 4093 return tokError("invalid DWARF type attribute encoding" + Twine(" '") + 4094 Lex.getStrVal() + "'"); 4095 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4096 Result.assign(Encoding); 4097 Lex.Lex(); 4098 return false; 4099 } 4100 4101 /// DIFlagField 4102 /// ::= uint32 4103 /// ::= DIFlagVector 4104 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4105 template <> 4106 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4107 4108 // parser for a single flag. 4109 auto parseFlag = [&](DINode::DIFlags &Val) { 4110 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4111 uint32_t TempVal = static_cast<uint32_t>(Val); 4112 bool Res = parseUInt32(TempVal); 4113 Val = static_cast<DINode::DIFlags>(TempVal); 4114 return Res; 4115 } 4116 4117 if (Lex.getKind() != lltok::DIFlag) 4118 return tokError("expected debug info flag"); 4119 4120 Val = DINode::getFlag(Lex.getStrVal()); 4121 if (!Val) 4122 return tokError(Twine("invalid debug info flag flag '") + 4123 Lex.getStrVal() + "'"); 4124 Lex.Lex(); 4125 return false; 4126 }; 4127 4128 // parse the flags and combine them together. 4129 DINode::DIFlags Combined = DINode::FlagZero; 4130 do { 4131 DINode::DIFlags Val; 4132 if (parseFlag(Val)) 4133 return true; 4134 Combined |= Val; 4135 } while (EatIfPresent(lltok::bar)); 4136 4137 Result.assign(Combined); 4138 return false; 4139 } 4140 4141 /// DISPFlagField 4142 /// ::= uint32 4143 /// ::= DISPFlagVector 4144 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4145 template <> 4146 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4147 4148 // parser for a single flag. 4149 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4150 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4151 uint32_t TempVal = static_cast<uint32_t>(Val); 4152 bool Res = parseUInt32(TempVal); 4153 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4154 return Res; 4155 } 4156 4157 if (Lex.getKind() != lltok::DISPFlag) 4158 return tokError("expected debug info flag"); 4159 4160 Val = DISubprogram::getFlag(Lex.getStrVal()); 4161 if (!Val) 4162 return tokError(Twine("invalid subprogram debug info flag '") + 4163 Lex.getStrVal() + "'"); 4164 Lex.Lex(); 4165 return false; 4166 }; 4167 4168 // parse the flags and combine them together. 4169 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4170 do { 4171 DISubprogram::DISPFlags Val; 4172 if (parseFlag(Val)) 4173 return true; 4174 Combined |= Val; 4175 } while (EatIfPresent(lltok::bar)); 4176 4177 Result.assign(Combined); 4178 return false; 4179 } 4180 4181 template <> 4182 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) { 4183 if (Lex.getKind() != lltok::APSInt) 4184 return tokError("expected signed integer"); 4185 4186 auto &S = Lex.getAPSIntVal(); 4187 if (S < Result.Min) 4188 return tokError("value for '" + Name + "' too small, limit is " + 4189 Twine(Result.Min)); 4190 if (S > Result.Max) 4191 return tokError("value for '" + Name + "' too large, limit is " + 4192 Twine(Result.Max)); 4193 Result.assign(S.getExtValue()); 4194 assert(Result.Val >= Result.Min && "Expected value in range"); 4195 assert(Result.Val <= Result.Max && "Expected value in range"); 4196 Lex.Lex(); 4197 return false; 4198 } 4199 4200 template <> 4201 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 4202 switch (Lex.getKind()) { 4203 default: 4204 return tokError("expected 'true' or 'false'"); 4205 case lltok::kw_true: 4206 Result.assign(true); 4207 break; 4208 case lltok::kw_false: 4209 Result.assign(false); 4210 break; 4211 } 4212 Lex.Lex(); 4213 return false; 4214 } 4215 4216 template <> 4217 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) { 4218 if (Lex.getKind() == lltok::kw_null) { 4219 if (!Result.AllowNull) 4220 return tokError("'" + Name + "' cannot be null"); 4221 Lex.Lex(); 4222 Result.assign(nullptr); 4223 return false; 4224 } 4225 4226 Metadata *MD; 4227 if (parseMetadata(MD, nullptr)) 4228 return true; 4229 4230 Result.assign(MD); 4231 return false; 4232 } 4233 4234 template <> 4235 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4236 MDSignedOrMDField &Result) { 4237 // Try to parse a signed int. 4238 if (Lex.getKind() == lltok::APSInt) { 4239 MDSignedField Res = Result.A; 4240 if (!parseMDField(Loc, Name, Res)) { 4241 Result.assign(Res); 4242 return false; 4243 } 4244 return true; 4245 } 4246 4247 // Otherwise, try to parse as an MDField. 4248 MDField Res = Result.B; 4249 if (!parseMDField(Loc, Name, Res)) { 4250 Result.assign(Res); 4251 return false; 4252 } 4253 4254 return true; 4255 } 4256 4257 template <> 4258 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 4259 LocTy ValueLoc = Lex.getLoc(); 4260 std::string S; 4261 if (parseStringConstant(S)) 4262 return true; 4263 4264 if (!Result.AllowEmpty && S.empty()) 4265 return error(ValueLoc, "'" + Name + "' cannot be empty"); 4266 4267 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 4268 return false; 4269 } 4270 4271 template <> 4272 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 4273 SmallVector<Metadata *, 4> MDs; 4274 if (parseMDNodeVector(MDs)) 4275 return true; 4276 4277 Result.assign(std::move(MDs)); 4278 return false; 4279 } 4280 4281 template <> 4282 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4283 ChecksumKindField &Result) { 4284 Optional<DIFile::ChecksumKind> CSKind = 4285 DIFile::getChecksumKind(Lex.getStrVal()); 4286 4287 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 4288 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() + 4289 "'"); 4290 4291 Result.assign(*CSKind); 4292 Lex.Lex(); 4293 return false; 4294 } 4295 4296 } // end namespace llvm 4297 4298 template <class ParserTy> 4299 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) { 4300 do { 4301 if (Lex.getKind() != lltok::LabelStr) 4302 return tokError("expected field label here"); 4303 4304 if (ParseField()) 4305 return true; 4306 } while (EatIfPresent(lltok::comma)); 4307 4308 return false; 4309 } 4310 4311 template <class ParserTy> 4312 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) { 4313 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4314 Lex.Lex(); 4315 4316 if (parseToken(lltok::lparen, "expected '(' here")) 4317 return true; 4318 if (Lex.getKind() != lltok::rparen) 4319 if (parseMDFieldsImplBody(ParseField)) 4320 return true; 4321 4322 ClosingLoc = Lex.getLoc(); 4323 return parseToken(lltok::rparen, "expected ')' here"); 4324 } 4325 4326 template <class FieldTy> 4327 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) { 4328 if (Result.Seen) 4329 return tokError("field '" + Name + "' cannot be specified more than once"); 4330 4331 LocTy Loc = Lex.getLoc(); 4332 Lex.Lex(); 4333 return parseMDField(Loc, Name, Result); 4334 } 4335 4336 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 4337 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 4338 4339 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 4340 if (Lex.getStrVal() == #CLASS) \ 4341 return parse##CLASS(N, IsDistinct); 4342 #include "llvm/IR/Metadata.def" 4343 4344 return tokError("expected metadata type"); 4345 } 4346 4347 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 4348 #define NOP_FIELD(NAME, TYPE, INIT) 4349 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 4350 if (!NAME.Seen) \ 4351 return error(ClosingLoc, "missing required field '" #NAME "'"); 4352 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 4353 if (Lex.getStrVal() == #NAME) \ 4354 return parseMDField(#NAME, NAME); 4355 #define PARSE_MD_FIELDS() \ 4356 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 4357 do { \ 4358 LocTy ClosingLoc; \ 4359 if (parseMDFieldsImpl( \ 4360 [&]() -> bool { \ 4361 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 4362 return tokError(Twine("invalid field '") + Lex.getStrVal() + \ 4363 "'"); \ 4364 }, \ 4365 ClosingLoc)) \ 4366 return true; \ 4367 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 4368 } while (false) 4369 #define GET_OR_DISTINCT(CLASS, ARGS) \ 4370 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 4371 4372 /// parseDILocationFields: 4373 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 4374 /// isImplicitCode: true) 4375 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) { 4376 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4377 OPTIONAL(line, LineField, ); \ 4378 OPTIONAL(column, ColumnField, ); \ 4379 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4380 OPTIONAL(inlinedAt, MDField, ); \ 4381 OPTIONAL(isImplicitCode, MDBoolField, (false)); 4382 PARSE_MD_FIELDS(); 4383 #undef VISIT_MD_FIELDS 4384 4385 Result = 4386 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 4387 inlinedAt.Val, isImplicitCode.Val)); 4388 return false; 4389 } 4390 4391 /// parseGenericDINode: 4392 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 4393 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) { 4394 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4395 REQUIRED(tag, DwarfTagField, ); \ 4396 OPTIONAL(header, MDStringField, ); \ 4397 OPTIONAL(operands, MDFieldList, ); 4398 PARSE_MD_FIELDS(); 4399 #undef VISIT_MD_FIELDS 4400 4401 Result = GET_OR_DISTINCT(GenericDINode, 4402 (Context, tag.Val, header.Val, operands.Val)); 4403 return false; 4404 } 4405 4406 /// parseDISubrange: 4407 /// ::= !DISubrange(count: 30, lowerBound: 2) 4408 /// ::= !DISubrange(count: !node, lowerBound: 2) 4409 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) 4410 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) { 4411 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4412 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 4413 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4414 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4415 OPTIONAL(stride, MDSignedOrMDField, ); 4416 PARSE_MD_FIELDS(); 4417 #undef VISIT_MD_FIELDS 4418 4419 Metadata *Count = nullptr; 4420 Metadata *LowerBound = nullptr; 4421 Metadata *UpperBound = nullptr; 4422 Metadata *Stride = nullptr; 4423 4424 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4425 if (Bound.isMDSignedField()) 4426 return ConstantAsMetadata::get(ConstantInt::getSigned( 4427 Type::getInt64Ty(Context), Bound.getMDSignedValue())); 4428 if (Bound.isMDField()) 4429 return Bound.getMDFieldValue(); 4430 return nullptr; 4431 }; 4432 4433 Count = convToMetadata(count); 4434 LowerBound = convToMetadata(lowerBound); 4435 UpperBound = convToMetadata(upperBound); 4436 Stride = convToMetadata(stride); 4437 4438 Result = GET_OR_DISTINCT(DISubrange, 4439 (Context, Count, LowerBound, UpperBound, Stride)); 4440 4441 return false; 4442 } 4443 4444 /// parseDIGenericSubrange: 4445 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride: 4446 /// !node3) 4447 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) { 4448 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4449 OPTIONAL(count, MDSignedOrMDField, ); \ 4450 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 4451 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 4452 OPTIONAL(stride, MDSignedOrMDField, ); 4453 PARSE_MD_FIELDS(); 4454 #undef VISIT_MD_FIELDS 4455 4456 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * { 4457 if (Bound.isMDSignedField()) 4458 return DIExpression::get( 4459 Context, {dwarf::DW_OP_consts, 4460 static_cast<uint64_t>(Bound.getMDSignedValue())}); 4461 if (Bound.isMDField()) 4462 return Bound.getMDFieldValue(); 4463 return nullptr; 4464 }; 4465 4466 Metadata *Count = ConvToMetadata(count); 4467 Metadata *LowerBound = ConvToMetadata(lowerBound); 4468 Metadata *UpperBound = ConvToMetadata(upperBound); 4469 Metadata *Stride = ConvToMetadata(stride); 4470 4471 Result = GET_OR_DISTINCT(DIGenericSubrange, 4472 (Context, Count, LowerBound, UpperBound, Stride)); 4473 4474 return false; 4475 } 4476 4477 /// parseDIEnumerator: 4478 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 4479 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) { 4480 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4481 REQUIRED(name, MDStringField, ); \ 4482 REQUIRED(value, MDAPSIntField, ); \ 4483 OPTIONAL(isUnsigned, MDBoolField, (false)); 4484 PARSE_MD_FIELDS(); 4485 #undef VISIT_MD_FIELDS 4486 4487 if (isUnsigned.Val && value.Val.isNegative()) 4488 return tokError("unsigned enumerator with negative value"); 4489 4490 APSInt Value(value.Val); 4491 // Add a leading zero so that unsigned values with the msb set are not 4492 // mistaken for negative values when used for signed enumerators. 4493 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) 4494 Value = Value.zext(Value.getBitWidth() + 1); 4495 4496 Result = 4497 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 4498 4499 return false; 4500 } 4501 4502 /// parseDIBasicType: 4503 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 4504 /// encoding: DW_ATE_encoding, flags: 0) 4505 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) { 4506 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4507 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 4508 OPTIONAL(name, MDStringField, ); \ 4509 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4510 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4511 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 4512 OPTIONAL(flags, DIFlagField, ); 4513 PARSE_MD_FIELDS(); 4514 #undef VISIT_MD_FIELDS 4515 4516 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 4517 align.Val, encoding.Val, flags.Val)); 4518 return false; 4519 } 4520 4521 /// parseDIStringType: 4522 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32) 4523 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) { 4524 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4525 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \ 4526 OPTIONAL(name, MDStringField, ); \ 4527 OPTIONAL(stringLength, MDField, ); \ 4528 OPTIONAL(stringLengthExpression, MDField, ); \ 4529 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4530 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4531 OPTIONAL(encoding, DwarfAttEncodingField, ); 4532 PARSE_MD_FIELDS(); 4533 #undef VISIT_MD_FIELDS 4534 4535 Result = GET_OR_DISTINCT(DIStringType, 4536 (Context, tag.Val, name.Val, stringLength.Val, 4537 stringLengthExpression.Val, size.Val, align.Val, 4538 encoding.Val)); 4539 return false; 4540 } 4541 4542 /// parseDIDerivedType: 4543 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 4544 /// line: 7, scope: !1, baseType: !2, size: 32, 4545 /// align: 32, offset: 0, flags: 0, extraData: !3, 4546 /// dwarfAddressSpace: 3) 4547 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) { 4548 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4549 REQUIRED(tag, DwarfTagField, ); \ 4550 OPTIONAL(name, MDStringField, ); \ 4551 OPTIONAL(file, MDField, ); \ 4552 OPTIONAL(line, LineField, ); \ 4553 OPTIONAL(scope, MDField, ); \ 4554 REQUIRED(baseType, MDField, ); \ 4555 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4556 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4557 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4558 OPTIONAL(flags, DIFlagField, ); \ 4559 OPTIONAL(extraData, MDField, ); \ 4560 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \ 4561 OPTIONAL(annotations, MDField, ); 4562 PARSE_MD_FIELDS(); 4563 #undef VISIT_MD_FIELDS 4564 4565 Optional<unsigned> DWARFAddressSpace; 4566 if (dwarfAddressSpace.Val != UINT32_MAX) 4567 DWARFAddressSpace = dwarfAddressSpace.Val; 4568 4569 Result = GET_OR_DISTINCT(DIDerivedType, 4570 (Context, tag.Val, name.Val, file.Val, line.Val, 4571 scope.Val, baseType.Val, size.Val, align.Val, 4572 offset.Val, DWARFAddressSpace, flags.Val, 4573 extraData.Val, annotations.Val)); 4574 return false; 4575 } 4576 4577 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) { 4578 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4579 REQUIRED(tag, DwarfTagField, ); \ 4580 OPTIONAL(name, MDStringField, ); \ 4581 OPTIONAL(file, MDField, ); \ 4582 OPTIONAL(line, LineField, ); \ 4583 OPTIONAL(scope, MDField, ); \ 4584 OPTIONAL(baseType, MDField, ); \ 4585 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 4586 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4587 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 4588 OPTIONAL(flags, DIFlagField, ); \ 4589 OPTIONAL(elements, MDField, ); \ 4590 OPTIONAL(runtimeLang, DwarfLangField, ); \ 4591 OPTIONAL(vtableHolder, MDField, ); \ 4592 OPTIONAL(templateParams, MDField, ); \ 4593 OPTIONAL(identifier, MDStringField, ); \ 4594 OPTIONAL(discriminator, MDField, ); \ 4595 OPTIONAL(dataLocation, MDField, ); \ 4596 OPTIONAL(associated, MDField, ); \ 4597 OPTIONAL(allocated, MDField, ); \ 4598 OPTIONAL(rank, MDSignedOrMDField, ); \ 4599 OPTIONAL(annotations, MDField, ); 4600 PARSE_MD_FIELDS(); 4601 #undef VISIT_MD_FIELDS 4602 4603 Metadata *Rank = nullptr; 4604 if (rank.isMDSignedField()) 4605 Rank = ConstantAsMetadata::get(ConstantInt::getSigned( 4606 Type::getInt64Ty(Context), rank.getMDSignedValue())); 4607 else if (rank.isMDField()) 4608 Rank = rank.getMDFieldValue(); 4609 4610 // If this has an identifier try to build an ODR type. 4611 if (identifier.Val) 4612 if (auto *CT = DICompositeType::buildODRType( 4613 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 4614 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val, 4615 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val, 4616 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 4617 Rank, annotations.Val)) { 4618 Result = CT; 4619 return false; 4620 } 4621 4622 // Create a new node, and save it in the context if it belongs in the type 4623 // map. 4624 Result = GET_OR_DISTINCT( 4625 DICompositeType, 4626 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 4627 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 4628 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 4629 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank, 4630 annotations.Val)); 4631 return false; 4632 } 4633 4634 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) { 4635 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4636 OPTIONAL(flags, DIFlagField, ); \ 4637 OPTIONAL(cc, DwarfCCField, ); \ 4638 REQUIRED(types, MDField, ); 4639 PARSE_MD_FIELDS(); 4640 #undef VISIT_MD_FIELDS 4641 4642 Result = GET_OR_DISTINCT(DISubroutineType, 4643 (Context, flags.Val, cc.Val, types.Val)); 4644 return false; 4645 } 4646 4647 /// parseDIFileType: 4648 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 4649 /// checksumkind: CSK_MD5, 4650 /// checksum: "000102030405060708090a0b0c0d0e0f", 4651 /// source: "source file contents") 4652 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) { 4653 // The default constructed value for checksumkind is required, but will never 4654 // be used, as the parser checks if the field was actually Seen before using 4655 // the Val. 4656 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4657 REQUIRED(filename, MDStringField, ); \ 4658 REQUIRED(directory, MDStringField, ); \ 4659 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 4660 OPTIONAL(checksum, MDStringField, ); \ 4661 OPTIONAL(source, MDStringField, ); 4662 PARSE_MD_FIELDS(); 4663 #undef VISIT_MD_FIELDS 4664 4665 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 4666 if (checksumkind.Seen && checksum.Seen) 4667 OptChecksum.emplace(checksumkind.Val, checksum.Val); 4668 else if (checksumkind.Seen || checksum.Seen) 4669 return Lex.Error("'checksumkind' and 'checksum' must be provided together"); 4670 4671 Optional<MDString *> OptSource; 4672 if (source.Seen) 4673 OptSource = source.Val; 4674 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val, 4675 OptChecksum, OptSource)); 4676 return false; 4677 } 4678 4679 /// parseDICompileUnit: 4680 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 4681 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 4682 /// splitDebugFilename: "abc.debug", 4683 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 4684 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 4685 /// sysroot: "/", sdk: "MacOSX.sdk") 4686 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) { 4687 if (!IsDistinct) 4688 return Lex.Error("missing 'distinct', required for !DICompileUnit"); 4689 4690 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4691 REQUIRED(language, DwarfLangField, ); \ 4692 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 4693 OPTIONAL(producer, MDStringField, ); \ 4694 OPTIONAL(isOptimized, MDBoolField, ); \ 4695 OPTIONAL(flags, MDStringField, ); \ 4696 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 4697 OPTIONAL(splitDebugFilename, MDStringField, ); \ 4698 OPTIONAL(emissionKind, EmissionKindField, ); \ 4699 OPTIONAL(enums, MDField, ); \ 4700 OPTIONAL(retainedTypes, MDField, ); \ 4701 OPTIONAL(globals, MDField, ); \ 4702 OPTIONAL(imports, MDField, ); \ 4703 OPTIONAL(macros, MDField, ); \ 4704 OPTIONAL(dwoId, MDUnsignedField, ); \ 4705 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 4706 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 4707 OPTIONAL(nameTableKind, NameTableKindField, ); \ 4708 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ 4709 OPTIONAL(sysroot, MDStringField, ); \ 4710 OPTIONAL(sdk, MDStringField, ); 4711 PARSE_MD_FIELDS(); 4712 #undef VISIT_MD_FIELDS 4713 4714 Result = DICompileUnit::getDistinct( 4715 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 4716 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 4717 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 4718 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 4719 rangesBaseAddress.Val, sysroot.Val, sdk.Val); 4720 return false; 4721 } 4722 4723 /// parseDISubprogram: 4724 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 4725 /// file: !1, line: 7, type: !2, isLocal: false, 4726 /// isDefinition: true, scopeLine: 8, containingType: !3, 4727 /// virtuality: DW_VIRTUALTIY_pure_virtual, 4728 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 4729 /// spFlags: 10, isOptimized: false, templateParams: !4, 4730 /// declaration: !5, retainedNodes: !6, thrownTypes: !7, 4731 /// annotations: !8) 4732 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) { 4733 auto Loc = Lex.getLoc(); 4734 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4735 OPTIONAL(scope, MDField, ); \ 4736 OPTIONAL(name, MDStringField, ); \ 4737 OPTIONAL(linkageName, MDStringField, ); \ 4738 OPTIONAL(file, MDField, ); \ 4739 OPTIONAL(line, LineField, ); \ 4740 OPTIONAL(type, MDField, ); \ 4741 OPTIONAL(isLocal, MDBoolField, ); \ 4742 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4743 OPTIONAL(scopeLine, LineField, ); \ 4744 OPTIONAL(containingType, MDField, ); \ 4745 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 4746 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 4747 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 4748 OPTIONAL(flags, DIFlagField, ); \ 4749 OPTIONAL(spFlags, DISPFlagField, ); \ 4750 OPTIONAL(isOptimized, MDBoolField, ); \ 4751 OPTIONAL(unit, MDField, ); \ 4752 OPTIONAL(templateParams, MDField, ); \ 4753 OPTIONAL(declaration, MDField, ); \ 4754 OPTIONAL(retainedNodes, MDField, ); \ 4755 OPTIONAL(thrownTypes, MDField, ); \ 4756 OPTIONAL(annotations, MDField, ); 4757 PARSE_MD_FIELDS(); 4758 #undef VISIT_MD_FIELDS 4759 4760 // An explicit spFlags field takes precedence over individual fields in 4761 // older IR versions. 4762 DISubprogram::DISPFlags SPFlags = 4763 spFlags.Seen ? spFlags.Val 4764 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 4765 isOptimized.Val, virtuality.Val); 4766 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 4767 return Lex.Error( 4768 Loc, 4769 "missing 'distinct', required for !DISubprogram that is a Definition"); 4770 Result = GET_OR_DISTINCT( 4771 DISubprogram, 4772 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 4773 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 4774 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 4775 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val)); 4776 return false; 4777 } 4778 4779 /// parseDILexicalBlock: 4780 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 4781 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 4782 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4783 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4784 OPTIONAL(file, MDField, ); \ 4785 OPTIONAL(line, LineField, ); \ 4786 OPTIONAL(column, ColumnField, ); 4787 PARSE_MD_FIELDS(); 4788 #undef VISIT_MD_FIELDS 4789 4790 Result = GET_OR_DISTINCT( 4791 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 4792 return false; 4793 } 4794 4795 /// parseDILexicalBlockFile: 4796 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 4797 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 4798 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4799 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4800 OPTIONAL(file, MDField, ); \ 4801 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 4802 PARSE_MD_FIELDS(); 4803 #undef VISIT_MD_FIELDS 4804 4805 Result = GET_OR_DISTINCT(DILexicalBlockFile, 4806 (Context, scope.Val, file.Val, discriminator.Val)); 4807 return false; 4808 } 4809 4810 /// parseDICommonBlock: 4811 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 4812 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) { 4813 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4814 REQUIRED(scope, MDField, ); \ 4815 OPTIONAL(declaration, MDField, ); \ 4816 OPTIONAL(name, MDStringField, ); \ 4817 OPTIONAL(file, MDField, ); \ 4818 OPTIONAL(line, LineField, ); 4819 PARSE_MD_FIELDS(); 4820 #undef VISIT_MD_FIELDS 4821 4822 Result = GET_OR_DISTINCT(DICommonBlock, 4823 (Context, scope.Val, declaration.Val, name.Val, 4824 file.Val, line.Val)); 4825 return false; 4826 } 4827 4828 /// parseDINamespace: 4829 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 4830 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) { 4831 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4832 REQUIRED(scope, MDField, ); \ 4833 OPTIONAL(name, MDStringField, ); \ 4834 OPTIONAL(exportSymbols, MDBoolField, ); 4835 PARSE_MD_FIELDS(); 4836 #undef VISIT_MD_FIELDS 4837 4838 Result = GET_OR_DISTINCT(DINamespace, 4839 (Context, scope.Val, name.Val, exportSymbols.Val)); 4840 return false; 4841 } 4842 4843 /// parseDIMacro: 4844 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: 4845 /// "SomeValue") 4846 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) { 4847 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4848 REQUIRED(type, DwarfMacinfoTypeField, ); \ 4849 OPTIONAL(line, LineField, ); \ 4850 REQUIRED(name, MDStringField, ); \ 4851 OPTIONAL(value, MDStringField, ); 4852 PARSE_MD_FIELDS(); 4853 #undef VISIT_MD_FIELDS 4854 4855 Result = GET_OR_DISTINCT(DIMacro, 4856 (Context, type.Val, line.Val, name.Val, value.Val)); 4857 return false; 4858 } 4859 4860 /// parseDIMacroFile: 4861 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 4862 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) { 4863 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4864 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 4865 OPTIONAL(line, LineField, ); \ 4866 REQUIRED(file, MDField, ); \ 4867 OPTIONAL(nodes, MDField, ); 4868 PARSE_MD_FIELDS(); 4869 #undef VISIT_MD_FIELDS 4870 4871 Result = GET_OR_DISTINCT(DIMacroFile, 4872 (Context, type.Val, line.Val, file.Val, nodes.Val)); 4873 return false; 4874 } 4875 4876 /// parseDIModule: 4877 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: 4878 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", 4879 /// file: !1, line: 4, isDecl: false) 4880 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) { 4881 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4882 REQUIRED(scope, MDField, ); \ 4883 REQUIRED(name, MDStringField, ); \ 4884 OPTIONAL(configMacros, MDStringField, ); \ 4885 OPTIONAL(includePath, MDStringField, ); \ 4886 OPTIONAL(apinotes, MDStringField, ); \ 4887 OPTIONAL(file, MDField, ); \ 4888 OPTIONAL(line, LineField, ); \ 4889 OPTIONAL(isDecl, MDBoolField, ); 4890 PARSE_MD_FIELDS(); 4891 #undef VISIT_MD_FIELDS 4892 4893 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, 4894 configMacros.Val, includePath.Val, 4895 apinotes.Val, line.Val, isDecl.Val)); 4896 return false; 4897 } 4898 4899 /// parseDITemplateTypeParameter: 4900 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 4901 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 4902 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4903 OPTIONAL(name, MDStringField, ); \ 4904 REQUIRED(type, MDField, ); \ 4905 OPTIONAL(defaulted, MDBoolField, ); 4906 PARSE_MD_FIELDS(); 4907 #undef VISIT_MD_FIELDS 4908 4909 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 4910 (Context, name.Val, type.Val, defaulted.Val)); 4911 return false; 4912 } 4913 4914 /// parseDITemplateValueParameter: 4915 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 4916 /// name: "V", type: !1, defaulted: false, 4917 /// value: i32 7) 4918 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 4919 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4920 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 4921 OPTIONAL(name, MDStringField, ); \ 4922 OPTIONAL(type, MDField, ); \ 4923 OPTIONAL(defaulted, MDBoolField, ); \ 4924 REQUIRED(value, MDField, ); 4925 4926 PARSE_MD_FIELDS(); 4927 #undef VISIT_MD_FIELDS 4928 4929 Result = GET_OR_DISTINCT( 4930 DITemplateValueParameter, 4931 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 4932 return false; 4933 } 4934 4935 /// parseDIGlobalVariable: 4936 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 4937 /// file: !1, line: 7, type: !2, isLocal: false, 4938 /// isDefinition: true, templateParams: !3, 4939 /// declaration: !4, align: 8) 4940 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 4941 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4942 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \ 4943 OPTIONAL(scope, MDField, ); \ 4944 OPTIONAL(linkageName, MDStringField, ); \ 4945 OPTIONAL(file, MDField, ); \ 4946 OPTIONAL(line, LineField, ); \ 4947 OPTIONAL(type, MDField, ); \ 4948 OPTIONAL(isLocal, MDBoolField, ); \ 4949 OPTIONAL(isDefinition, MDBoolField, (true)); \ 4950 OPTIONAL(templateParams, MDField, ); \ 4951 OPTIONAL(declaration, MDField, ); \ 4952 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4953 OPTIONAL(annotations, MDField, ); 4954 PARSE_MD_FIELDS(); 4955 #undef VISIT_MD_FIELDS 4956 4957 Result = 4958 GET_OR_DISTINCT(DIGlobalVariable, 4959 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 4960 line.Val, type.Val, isLocal.Val, isDefinition.Val, 4961 declaration.Val, templateParams.Val, align.Val, 4962 annotations.Val)); 4963 return false; 4964 } 4965 4966 /// parseDILocalVariable: 4967 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 4968 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4969 /// align: 8) 4970 /// ::= !DILocalVariable(scope: !0, name: "foo", 4971 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 4972 /// align: 8) 4973 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) { 4974 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4975 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4976 OPTIONAL(name, MDStringField, ); \ 4977 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 4978 OPTIONAL(file, MDField, ); \ 4979 OPTIONAL(line, LineField, ); \ 4980 OPTIONAL(type, MDField, ); \ 4981 OPTIONAL(flags, DIFlagField, ); \ 4982 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 4983 OPTIONAL(annotations, MDField, ); 4984 PARSE_MD_FIELDS(); 4985 #undef VISIT_MD_FIELDS 4986 4987 Result = GET_OR_DISTINCT(DILocalVariable, 4988 (Context, scope.Val, name.Val, file.Val, line.Val, 4989 type.Val, arg.Val, flags.Val, align.Val, 4990 annotations.Val)); 4991 return false; 4992 } 4993 4994 /// parseDILabel: 4995 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 4996 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) { 4997 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 4998 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 4999 REQUIRED(name, MDStringField, ); \ 5000 REQUIRED(file, MDField, ); \ 5001 REQUIRED(line, LineField, ); 5002 PARSE_MD_FIELDS(); 5003 #undef VISIT_MD_FIELDS 5004 5005 Result = GET_OR_DISTINCT(DILabel, 5006 (Context, scope.Val, name.Val, file.Val, line.Val)); 5007 return false; 5008 } 5009 5010 /// parseDIExpression: 5011 /// ::= !DIExpression(0, 7, -1) 5012 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) { 5013 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5014 Lex.Lex(); 5015 5016 if (parseToken(lltok::lparen, "expected '(' here")) 5017 return true; 5018 5019 SmallVector<uint64_t, 8> Elements; 5020 if (Lex.getKind() != lltok::rparen) 5021 do { 5022 if (Lex.getKind() == lltok::DwarfOp) { 5023 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 5024 Lex.Lex(); 5025 Elements.push_back(Op); 5026 continue; 5027 } 5028 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 5029 } 5030 5031 if (Lex.getKind() == lltok::DwarfAttEncoding) { 5032 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 5033 Lex.Lex(); 5034 Elements.push_back(Op); 5035 continue; 5036 } 5037 return tokError(Twine("invalid DWARF attribute encoding '") + 5038 Lex.getStrVal() + "'"); 5039 } 5040 5041 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 5042 return tokError("expected unsigned integer"); 5043 5044 auto &U = Lex.getAPSIntVal(); 5045 if (U.ugt(UINT64_MAX)) 5046 return tokError("element too large, limit is " + Twine(UINT64_MAX)); 5047 Elements.push_back(U.getZExtValue()); 5048 Lex.Lex(); 5049 } while (EatIfPresent(lltok::comma)); 5050 5051 if (parseToken(lltok::rparen, "expected ')' here")) 5052 return true; 5053 5054 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 5055 return false; 5056 } 5057 5058 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) { 5059 return parseDIArgList(Result, IsDistinct, nullptr); 5060 } 5061 /// ParseDIArgList: 5062 /// ::= !DIArgList(i32 7, i64 %0) 5063 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct, 5064 PerFunctionState *PFS) { 5065 assert(PFS && "Expected valid function state"); 5066 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5067 Lex.Lex(); 5068 5069 if (parseToken(lltok::lparen, "expected '(' here")) 5070 return true; 5071 5072 SmallVector<ValueAsMetadata *, 4> Args; 5073 if (Lex.getKind() != lltok::rparen) 5074 do { 5075 Metadata *MD; 5076 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS)) 5077 return true; 5078 Args.push_back(dyn_cast<ValueAsMetadata>(MD)); 5079 } while (EatIfPresent(lltok::comma)); 5080 5081 if (parseToken(lltok::rparen, "expected ')' here")) 5082 return true; 5083 5084 Result = GET_OR_DISTINCT(DIArgList, (Context, Args)); 5085 return false; 5086 } 5087 5088 /// parseDIGlobalVariableExpression: 5089 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5090 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result, 5091 bool IsDistinct) { 5092 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5093 REQUIRED(var, MDField, ); \ 5094 REQUIRED(expr, MDField, ); 5095 PARSE_MD_FIELDS(); 5096 #undef VISIT_MD_FIELDS 5097 5098 Result = 5099 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5100 return false; 5101 } 5102 5103 /// parseDIObjCProperty: 5104 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5105 /// getter: "getFoo", attributes: 7, type: !2) 5106 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5107 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5108 OPTIONAL(name, MDStringField, ); \ 5109 OPTIONAL(file, MDField, ); \ 5110 OPTIONAL(line, LineField, ); \ 5111 OPTIONAL(setter, MDStringField, ); \ 5112 OPTIONAL(getter, MDStringField, ); \ 5113 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5114 OPTIONAL(type, MDField, ); 5115 PARSE_MD_FIELDS(); 5116 #undef VISIT_MD_FIELDS 5117 5118 Result = GET_OR_DISTINCT(DIObjCProperty, 5119 (Context, name.Val, file.Val, line.Val, setter.Val, 5120 getter.Val, attributes.Val, type.Val)); 5121 return false; 5122 } 5123 5124 /// parseDIImportedEntity: 5125 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5126 /// line: 7, name: "foo", elements: !2) 5127 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5128 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5129 REQUIRED(tag, DwarfTagField, ); \ 5130 REQUIRED(scope, MDField, ); \ 5131 OPTIONAL(entity, MDField, ); \ 5132 OPTIONAL(file, MDField, ); \ 5133 OPTIONAL(line, LineField, ); \ 5134 OPTIONAL(name, MDStringField, ); \ 5135 OPTIONAL(elements, MDField, ); 5136 PARSE_MD_FIELDS(); 5137 #undef VISIT_MD_FIELDS 5138 5139 Result = GET_OR_DISTINCT(DIImportedEntity, 5140 (Context, tag.Val, scope.Val, entity.Val, file.Val, 5141 line.Val, name.Val, elements.Val)); 5142 return false; 5143 } 5144 5145 #undef PARSE_MD_FIELD 5146 #undef NOP_FIELD 5147 #undef REQUIRE_FIELD 5148 #undef DECLARE_FIELD 5149 5150 /// parseMetadataAsValue 5151 /// ::= metadata i32 %local 5152 /// ::= metadata i32 @global 5153 /// ::= metadata i32 7 5154 /// ::= metadata !0 5155 /// ::= metadata !{...} 5156 /// ::= metadata !"string" 5157 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 5158 // Note: the type 'metadata' has already been parsed. 5159 Metadata *MD; 5160 if (parseMetadata(MD, &PFS)) 5161 return true; 5162 5163 V = MetadataAsValue::get(Context, MD); 5164 return false; 5165 } 5166 5167 /// parseValueAsMetadata 5168 /// ::= i32 %local 5169 /// ::= i32 @global 5170 /// ::= i32 7 5171 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 5172 PerFunctionState *PFS) { 5173 Type *Ty; 5174 LocTy Loc; 5175 if (parseType(Ty, TypeMsg, Loc)) 5176 return true; 5177 if (Ty->isMetadataTy()) 5178 return error(Loc, "invalid metadata-value-metadata roundtrip"); 5179 5180 Value *V; 5181 if (parseValue(Ty, V, PFS)) 5182 return true; 5183 5184 MD = ValueAsMetadata::get(V); 5185 return false; 5186 } 5187 5188 /// parseMetadata 5189 /// ::= i32 %local 5190 /// ::= i32 @global 5191 /// ::= i32 7 5192 /// ::= !42 5193 /// ::= !{...} 5194 /// ::= !"string" 5195 /// ::= !DILocation(...) 5196 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) { 5197 if (Lex.getKind() == lltok::MetadataVar) { 5198 MDNode *N; 5199 // DIArgLists are a special case, as they are a list of ValueAsMetadata and 5200 // so parsing this requires a Function State. 5201 if (Lex.getStrVal() == "DIArgList") { 5202 if (parseDIArgList(N, false, PFS)) 5203 return true; 5204 } else if (parseSpecializedMDNode(N)) { 5205 return true; 5206 } 5207 MD = N; 5208 return false; 5209 } 5210 5211 // ValueAsMetadata: 5212 // <type> <value> 5213 if (Lex.getKind() != lltok::exclaim) 5214 return parseValueAsMetadata(MD, "expected metadata operand", PFS); 5215 5216 // '!'. 5217 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 5218 Lex.Lex(); 5219 5220 // MDString: 5221 // ::= '!' STRINGCONSTANT 5222 if (Lex.getKind() == lltok::StringConstant) { 5223 MDString *S; 5224 if (parseMDString(S)) 5225 return true; 5226 MD = S; 5227 return false; 5228 } 5229 5230 // MDNode: 5231 // !{ ... } 5232 // !7 5233 MDNode *N; 5234 if (parseMDNodeTail(N)) 5235 return true; 5236 MD = N; 5237 return false; 5238 } 5239 5240 //===----------------------------------------------------------------------===// 5241 // Function Parsing. 5242 //===----------------------------------------------------------------------===// 5243 5244 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V, 5245 PerFunctionState *PFS) { 5246 if (Ty->isFunctionTy()) 5247 return error(ID.Loc, "functions are not values, refer to them as pointers"); 5248 5249 switch (ID.Kind) { 5250 case ValID::t_LocalID: 5251 if (!PFS) 5252 return error(ID.Loc, "invalid use of function-local name"); 5253 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc); 5254 return V == nullptr; 5255 case ValID::t_LocalName: 5256 if (!PFS) 5257 return error(ID.Loc, "invalid use of function-local name"); 5258 V = PFS->getVal(ID.StrVal, Ty, ID.Loc); 5259 return V == nullptr; 5260 case ValID::t_InlineAsm: { 5261 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2)) 5262 return error(ID.Loc, "invalid type for inline asm constraint string"); 5263 V = InlineAsm::get( 5264 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1, 5265 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1); 5266 return false; 5267 } 5268 case ValID::t_GlobalName: 5269 V = getGlobalVal(ID.StrVal, Ty, ID.Loc); 5270 return V == nullptr; 5271 case ValID::t_GlobalID: 5272 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc); 5273 return V == nullptr; 5274 case ValID::t_APSInt: 5275 if (!Ty->isIntegerTy()) 5276 return error(ID.Loc, "integer constant must have integer type"); 5277 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 5278 V = ConstantInt::get(Context, ID.APSIntVal); 5279 return false; 5280 case ValID::t_APFloat: 5281 if (!Ty->isFloatingPointTy() || 5282 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 5283 return error(ID.Loc, "floating point constant invalid for type"); 5284 5285 // The lexer has no type info, so builds all half, bfloat, float, and double 5286 // FP constants as double. Fix this here. Long double does not need this. 5287 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 5288 // Check for signaling before potentially converting and losing that info. 5289 bool IsSNAN = ID.APFloatVal.isSignaling(); 5290 bool Ignored; 5291 if (Ty->isHalfTy()) 5292 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 5293 &Ignored); 5294 else if (Ty->isBFloatTy()) 5295 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, 5296 &Ignored); 5297 else if (Ty->isFloatTy()) 5298 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 5299 &Ignored); 5300 if (IsSNAN) { 5301 // The convert call above may quiet an SNaN, so manufacture another 5302 // SNaN. The bitcast works because the payload (significand) parameter 5303 // is truncated to fit. 5304 APInt Payload = ID.APFloatVal.bitcastToAPInt(); 5305 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(), 5306 ID.APFloatVal.isNegative(), &Payload); 5307 } 5308 } 5309 V = ConstantFP::get(Context, ID.APFloatVal); 5310 5311 if (V->getType() != Ty) 5312 return error(ID.Loc, "floating point constant does not have type '" + 5313 getTypeString(Ty) + "'"); 5314 5315 return false; 5316 case ValID::t_Null: 5317 if (!Ty->isPointerTy()) 5318 return error(ID.Loc, "null must be a pointer type"); 5319 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 5320 return false; 5321 case ValID::t_Undef: 5322 // FIXME: LabelTy should not be a first-class type. 5323 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5324 return error(ID.Loc, "invalid type for undef constant"); 5325 V = UndefValue::get(Ty); 5326 return false; 5327 case ValID::t_EmptyArray: 5328 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 5329 return error(ID.Loc, "invalid empty array initializer"); 5330 V = UndefValue::get(Ty); 5331 return false; 5332 case ValID::t_Zero: 5333 // FIXME: LabelTy should not be a first-class type. 5334 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5335 return error(ID.Loc, "invalid type for null constant"); 5336 V = Constant::getNullValue(Ty); 5337 return false; 5338 case ValID::t_None: 5339 if (!Ty->isTokenTy()) 5340 return error(ID.Loc, "invalid type for none constant"); 5341 V = Constant::getNullValue(Ty); 5342 return false; 5343 case ValID::t_Poison: 5344 // FIXME: LabelTy should not be a first-class type. 5345 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 5346 return error(ID.Loc, "invalid type for poison constant"); 5347 V = PoisonValue::get(Ty); 5348 return false; 5349 case ValID::t_Constant: 5350 if (ID.ConstantVal->getType() != Ty) 5351 return error(ID.Loc, "constant expression type mismatch: got type '" + 5352 getTypeString(ID.ConstantVal->getType()) + 5353 "' but expected '" + getTypeString(Ty) + "'"); 5354 V = ID.ConstantVal; 5355 return false; 5356 case ValID::t_ConstantStruct: 5357 case ValID::t_PackedConstantStruct: 5358 if (StructType *ST = dyn_cast<StructType>(Ty)) { 5359 if (ST->getNumElements() != ID.UIntVal) 5360 return error(ID.Loc, 5361 "initializer with struct type has wrong # elements"); 5362 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 5363 return error(ID.Loc, "packed'ness of initializer and type don't match"); 5364 5365 // Verify that the elements are compatible with the structtype. 5366 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 5367 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 5368 return error( 5369 ID.Loc, 5370 "element " + Twine(i) + 5371 " of struct initializer doesn't match struct element type"); 5372 5373 V = ConstantStruct::get( 5374 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 5375 } else 5376 return error(ID.Loc, "constant expression type mismatch"); 5377 return false; 5378 } 5379 llvm_unreachable("Invalid ValID"); 5380 } 5381 5382 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 5383 C = nullptr; 5384 ValID ID; 5385 auto Loc = Lex.getLoc(); 5386 if (parseValID(ID, /*PFS=*/nullptr)) 5387 return true; 5388 switch (ID.Kind) { 5389 case ValID::t_APSInt: 5390 case ValID::t_APFloat: 5391 case ValID::t_Undef: 5392 case ValID::t_Constant: 5393 case ValID::t_ConstantStruct: 5394 case ValID::t_PackedConstantStruct: { 5395 Value *V; 5396 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr)) 5397 return true; 5398 assert(isa<Constant>(V) && "Expected a constant value"); 5399 C = cast<Constant>(V); 5400 return false; 5401 } 5402 case ValID::t_Null: 5403 C = Constant::getNullValue(Ty); 5404 return false; 5405 default: 5406 return error(Loc, "expected a constant value"); 5407 } 5408 } 5409 5410 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 5411 V = nullptr; 5412 ValID ID; 5413 return parseValID(ID, PFS, Ty) || 5414 convertValIDToValue(Ty, ID, V, PFS); 5415 } 5416 5417 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { 5418 Type *Ty = nullptr; 5419 return parseType(Ty) || parseValue(Ty, V, PFS); 5420 } 5421 5422 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 5423 PerFunctionState &PFS) { 5424 Value *V; 5425 Loc = Lex.getLoc(); 5426 if (parseTypeAndValue(V, PFS)) 5427 return true; 5428 if (!isa<BasicBlock>(V)) 5429 return error(Loc, "expected a basic block"); 5430 BB = cast<BasicBlock>(V); 5431 return false; 5432 } 5433 5434 /// FunctionHeader 5435 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 5436 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 5437 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 5438 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 5439 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) { 5440 // parse the linkage. 5441 LocTy LinkageLoc = Lex.getLoc(); 5442 unsigned Linkage; 5443 unsigned Visibility; 5444 unsigned DLLStorageClass; 5445 bool DSOLocal; 5446 AttrBuilder RetAttrs; 5447 unsigned CC; 5448 bool HasLinkage; 5449 Type *RetType = nullptr; 5450 LocTy RetTypeLoc = Lex.getLoc(); 5451 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 5452 DSOLocal) || 5453 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 5454 parseType(RetType, RetTypeLoc, true /*void allowed*/)) 5455 return true; 5456 5457 // Verify that the linkage is ok. 5458 switch ((GlobalValue::LinkageTypes)Linkage) { 5459 case GlobalValue::ExternalLinkage: 5460 break; // always ok. 5461 case GlobalValue::ExternalWeakLinkage: 5462 if (IsDefine) 5463 return error(LinkageLoc, "invalid linkage for function definition"); 5464 break; 5465 case GlobalValue::PrivateLinkage: 5466 case GlobalValue::InternalLinkage: 5467 case GlobalValue::AvailableExternallyLinkage: 5468 case GlobalValue::LinkOnceAnyLinkage: 5469 case GlobalValue::LinkOnceODRLinkage: 5470 case GlobalValue::WeakAnyLinkage: 5471 case GlobalValue::WeakODRLinkage: 5472 if (!IsDefine) 5473 return error(LinkageLoc, "invalid linkage for function declaration"); 5474 break; 5475 case GlobalValue::AppendingLinkage: 5476 case GlobalValue::CommonLinkage: 5477 return error(LinkageLoc, "invalid function linkage type"); 5478 } 5479 5480 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 5481 return error(LinkageLoc, 5482 "symbol with local linkage must have default visibility"); 5483 5484 if (!FunctionType::isValidReturnType(RetType)) 5485 return error(RetTypeLoc, "invalid function return type"); 5486 5487 LocTy NameLoc = Lex.getLoc(); 5488 5489 std::string FunctionName; 5490 if (Lex.getKind() == lltok::GlobalVar) { 5491 FunctionName = Lex.getStrVal(); 5492 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 5493 unsigned NameID = Lex.getUIntVal(); 5494 5495 if (NameID != NumberedVals.size()) 5496 return tokError("function expected to be numbered '%" + 5497 Twine(NumberedVals.size()) + "'"); 5498 } else { 5499 return tokError("expected function name"); 5500 } 5501 5502 Lex.Lex(); 5503 5504 if (Lex.getKind() != lltok::lparen) 5505 return tokError("expected '(' in function argument list"); 5506 5507 SmallVector<ArgInfo, 8> ArgList; 5508 bool IsVarArg; 5509 AttrBuilder FuncAttrs; 5510 std::vector<unsigned> FwdRefAttrGrps; 5511 LocTy BuiltinLoc; 5512 std::string Section; 5513 std::string Partition; 5514 MaybeAlign Alignment; 5515 std::string GC; 5516 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 5517 unsigned AddrSpace = 0; 5518 Constant *Prefix = nullptr; 5519 Constant *Prologue = nullptr; 5520 Constant *PersonalityFn = nullptr; 5521 Comdat *C; 5522 5523 if (parseArgumentList(ArgList, IsVarArg) || 5524 parseOptionalUnnamedAddr(UnnamedAddr) || 5525 parseOptionalProgramAddrSpace(AddrSpace) || 5526 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 5527 BuiltinLoc) || 5528 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) || 5529 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) || 5530 parseOptionalComdat(FunctionName, C) || 5531 parseOptionalAlignment(Alignment) || 5532 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) || 5533 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) || 5534 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) || 5535 (EatIfPresent(lltok::kw_personality) && 5536 parseGlobalTypeAndValue(PersonalityFn))) 5537 return true; 5538 5539 if (FuncAttrs.contains(Attribute::Builtin)) 5540 return error(BuiltinLoc, "'builtin' attribute not valid on function"); 5541 5542 // If the alignment was parsed as an attribute, move to the alignment field. 5543 if (FuncAttrs.hasAlignmentAttr()) { 5544 Alignment = FuncAttrs.getAlignment(); 5545 FuncAttrs.removeAttribute(Attribute::Alignment); 5546 } 5547 5548 // Okay, if we got here, the function is syntactically valid. Convert types 5549 // and do semantic checks. 5550 std::vector<Type*> ParamTypeList; 5551 SmallVector<AttributeSet, 8> Attrs; 5552 5553 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 5554 ParamTypeList.push_back(ArgList[i].Ty); 5555 Attrs.push_back(ArgList[i].Attrs); 5556 } 5557 5558 AttributeList PAL = 5559 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 5560 AttributeSet::get(Context, RetAttrs), Attrs); 5561 5562 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy()) 5563 return error(RetTypeLoc, "functions with 'sret' argument must return void"); 5564 5565 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg); 5566 PointerType *PFT = PointerType::get(FT, AddrSpace); 5567 5568 Fn = nullptr; 5569 GlobalValue *FwdFn = nullptr; 5570 if (!FunctionName.empty()) { 5571 // If this was a definition of a forward reference, remove the definition 5572 // from the forward reference table and fill in the forward ref. 5573 auto FRVI = ForwardRefVals.find(FunctionName); 5574 if (FRVI != ForwardRefVals.end()) { 5575 FwdFn = FRVI->second.first; 5576 if (!FwdFn->getType()->isOpaque()) { 5577 if (!FwdFn->getType()->getPointerElementType()->isFunctionTy()) 5578 return error(FRVI->second.second, "invalid forward reference to " 5579 "function as global value!"); 5580 if (FwdFn->getType() != PFT) 5581 return error(FRVI->second.second, 5582 "invalid forward reference to " 5583 "function '" + 5584 FunctionName + 5585 "' with wrong type: " 5586 "expected '" + 5587 getTypeString(PFT) + "' but was '" + 5588 getTypeString(FwdFn->getType()) + "'"); 5589 } 5590 ForwardRefVals.erase(FRVI); 5591 } else if ((Fn = M->getFunction(FunctionName))) { 5592 // Reject redefinitions. 5593 return error(NameLoc, 5594 "invalid redefinition of function '" + FunctionName + "'"); 5595 } else if (M->getNamedValue(FunctionName)) { 5596 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 5597 } 5598 5599 } else { 5600 // If this is a definition of a forward referenced function, make sure the 5601 // types agree. 5602 auto I = ForwardRefValIDs.find(NumberedVals.size()); 5603 if (I != ForwardRefValIDs.end()) { 5604 FwdFn = cast<Function>(I->second.first); 5605 if (!FwdFn->getType()->isOpaque() && FwdFn->getType() != PFT) 5606 return error(NameLoc, "type of definition and forward reference of '@" + 5607 Twine(NumberedVals.size()) + 5608 "' disagree: " 5609 "expected '" + 5610 getTypeString(PFT) + "' but was '" + 5611 getTypeString(FwdFn->getType()) + "'"); 5612 ForwardRefValIDs.erase(I); 5613 } 5614 } 5615 5616 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 5617 FunctionName, M); 5618 5619 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 5620 5621 if (FunctionName.empty()) 5622 NumberedVals.push_back(Fn); 5623 5624 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 5625 maybeSetDSOLocal(DSOLocal, *Fn); 5626 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 5627 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 5628 Fn->setCallingConv(CC); 5629 Fn->setAttributes(PAL); 5630 Fn->setUnnamedAddr(UnnamedAddr); 5631 Fn->setAlignment(MaybeAlign(Alignment)); 5632 Fn->setSection(Section); 5633 Fn->setPartition(Partition); 5634 Fn->setComdat(C); 5635 Fn->setPersonalityFn(PersonalityFn); 5636 if (!GC.empty()) Fn->setGC(GC); 5637 Fn->setPrefixData(Prefix); 5638 Fn->setPrologueData(Prologue); 5639 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 5640 5641 // Add all of the arguments we parsed to the function. 5642 Function::arg_iterator ArgIt = Fn->arg_begin(); 5643 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 5644 // If the argument has a name, insert it into the argument symbol table. 5645 if (ArgList[i].Name.empty()) continue; 5646 5647 // Set the name, if it conflicted, it will be auto-renamed. 5648 ArgIt->setName(ArgList[i].Name); 5649 5650 if (ArgIt->getName() != ArgList[i].Name) 5651 return error(ArgList[i].Loc, 5652 "redefinition of argument '%" + ArgList[i].Name + "'"); 5653 } 5654 5655 if (FwdFn) { 5656 FwdFn->replaceAllUsesWith(Fn); 5657 FwdFn->eraseFromParent(); 5658 } 5659 5660 if (IsDefine) 5661 return false; 5662 5663 // Check the declaration has no block address forward references. 5664 ValID ID; 5665 if (FunctionName.empty()) { 5666 ID.Kind = ValID::t_GlobalID; 5667 ID.UIntVal = NumberedVals.size() - 1; 5668 } else { 5669 ID.Kind = ValID::t_GlobalName; 5670 ID.StrVal = FunctionName; 5671 } 5672 auto Blocks = ForwardRefBlockAddresses.find(ID); 5673 if (Blocks != ForwardRefBlockAddresses.end()) 5674 return error(Blocks->first.Loc, 5675 "cannot take blockaddress inside a declaration"); 5676 return false; 5677 } 5678 5679 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 5680 ValID ID; 5681 if (FunctionNumber == -1) { 5682 ID.Kind = ValID::t_GlobalName; 5683 ID.StrVal = std::string(F.getName()); 5684 } else { 5685 ID.Kind = ValID::t_GlobalID; 5686 ID.UIntVal = FunctionNumber; 5687 } 5688 5689 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 5690 if (Blocks == P.ForwardRefBlockAddresses.end()) 5691 return false; 5692 5693 for (const auto &I : Blocks->second) { 5694 const ValID &BBID = I.first; 5695 GlobalValue *GV = I.second; 5696 5697 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 5698 "Expected local id or name"); 5699 BasicBlock *BB; 5700 if (BBID.Kind == ValID::t_LocalName) 5701 BB = getBB(BBID.StrVal, BBID.Loc); 5702 else 5703 BB = getBB(BBID.UIntVal, BBID.Loc); 5704 if (!BB) 5705 return P.error(BBID.Loc, "referenced value is not a basic block"); 5706 5707 Value *ResolvedVal = BlockAddress::get(&F, BB); 5708 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(), 5709 ResolvedVal); 5710 if (!ResolvedVal) 5711 return true; 5712 GV->replaceAllUsesWith(ResolvedVal); 5713 GV->eraseFromParent(); 5714 } 5715 5716 P.ForwardRefBlockAddresses.erase(Blocks); 5717 return false; 5718 } 5719 5720 /// parseFunctionBody 5721 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 5722 bool LLParser::parseFunctionBody(Function &Fn) { 5723 if (Lex.getKind() != lltok::lbrace) 5724 return tokError("expected '{' in function body"); 5725 Lex.Lex(); // eat the {. 5726 5727 int FunctionNumber = -1; 5728 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1; 5729 5730 PerFunctionState PFS(*this, Fn, FunctionNumber); 5731 5732 // Resolve block addresses and allow basic blocks to be forward-declared 5733 // within this function. 5734 if (PFS.resolveForwardRefBlockAddresses()) 5735 return true; 5736 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS); 5737 5738 // We need at least one basic block. 5739 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 5740 return tokError("function body requires at least one basic block"); 5741 5742 while (Lex.getKind() != lltok::rbrace && 5743 Lex.getKind() != lltok::kw_uselistorder) 5744 if (parseBasicBlock(PFS)) 5745 return true; 5746 5747 while (Lex.getKind() != lltok::rbrace) 5748 if (parseUseListOrder(&PFS)) 5749 return true; 5750 5751 // Eat the }. 5752 Lex.Lex(); 5753 5754 // Verify function is ok. 5755 return PFS.finishFunction(); 5756 } 5757 5758 /// parseBasicBlock 5759 /// ::= (LabelStr|LabelID)? Instruction* 5760 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 5761 // If this basic block starts out with a name, remember it. 5762 std::string Name; 5763 int NameID = -1; 5764 LocTy NameLoc = Lex.getLoc(); 5765 if (Lex.getKind() == lltok::LabelStr) { 5766 Name = Lex.getStrVal(); 5767 Lex.Lex(); 5768 } else if (Lex.getKind() == lltok::LabelID) { 5769 NameID = Lex.getUIntVal(); 5770 Lex.Lex(); 5771 } 5772 5773 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 5774 if (!BB) 5775 return true; 5776 5777 std::string NameStr; 5778 5779 // parse the instructions in this block until we get a terminator. 5780 Instruction *Inst; 5781 do { 5782 // This instruction may have three possibilities for a name: a) none 5783 // specified, b) name specified "%foo =", c) number specified: "%4 =". 5784 LocTy NameLoc = Lex.getLoc(); 5785 int NameID = -1; 5786 NameStr = ""; 5787 5788 if (Lex.getKind() == lltok::LocalVarID) { 5789 NameID = Lex.getUIntVal(); 5790 Lex.Lex(); 5791 if (parseToken(lltok::equal, "expected '=' after instruction id")) 5792 return true; 5793 } else if (Lex.getKind() == lltok::LocalVar) { 5794 NameStr = Lex.getStrVal(); 5795 Lex.Lex(); 5796 if (parseToken(lltok::equal, "expected '=' after instruction name")) 5797 return true; 5798 } 5799 5800 switch (parseInstruction(Inst, BB, PFS)) { 5801 default: 5802 llvm_unreachable("Unknown parseInstruction result!"); 5803 case InstError: return true; 5804 case InstNormal: 5805 BB->getInstList().push_back(Inst); 5806 5807 // With a normal result, we check to see if the instruction is followed by 5808 // a comma and metadata. 5809 if (EatIfPresent(lltok::comma)) 5810 if (parseInstructionMetadata(*Inst)) 5811 return true; 5812 break; 5813 case InstExtraComma: 5814 BB->getInstList().push_back(Inst); 5815 5816 // If the instruction parser ate an extra comma at the end of it, it 5817 // *must* be followed by metadata. 5818 if (parseInstructionMetadata(*Inst)) 5819 return true; 5820 break; 5821 } 5822 5823 // Set the name on the instruction. 5824 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 5825 return true; 5826 } while (!Inst->isTerminator()); 5827 5828 return false; 5829 } 5830 5831 //===----------------------------------------------------------------------===// 5832 // Instruction Parsing. 5833 //===----------------------------------------------------------------------===// 5834 5835 /// parseInstruction - parse one of the many different instructions. 5836 /// 5837 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 5838 PerFunctionState &PFS) { 5839 lltok::Kind Token = Lex.getKind(); 5840 if (Token == lltok::Eof) 5841 return tokError("found end of file when expecting more instructions"); 5842 LocTy Loc = Lex.getLoc(); 5843 unsigned KeywordVal = Lex.getUIntVal(); 5844 Lex.Lex(); // Eat the keyword. 5845 5846 switch (Token) { 5847 default: 5848 return error(Loc, "expected instruction opcode"); 5849 // Terminator Instructions. 5850 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 5851 case lltok::kw_ret: 5852 return parseRet(Inst, BB, PFS); 5853 case lltok::kw_br: 5854 return parseBr(Inst, PFS); 5855 case lltok::kw_switch: 5856 return parseSwitch(Inst, PFS); 5857 case lltok::kw_indirectbr: 5858 return parseIndirectBr(Inst, PFS); 5859 case lltok::kw_invoke: 5860 return parseInvoke(Inst, PFS); 5861 case lltok::kw_resume: 5862 return parseResume(Inst, PFS); 5863 case lltok::kw_cleanupret: 5864 return parseCleanupRet(Inst, PFS); 5865 case lltok::kw_catchret: 5866 return parseCatchRet(Inst, PFS); 5867 case lltok::kw_catchswitch: 5868 return parseCatchSwitch(Inst, PFS); 5869 case lltok::kw_catchpad: 5870 return parseCatchPad(Inst, PFS); 5871 case lltok::kw_cleanuppad: 5872 return parseCleanupPad(Inst, PFS); 5873 case lltok::kw_callbr: 5874 return parseCallBr(Inst, PFS); 5875 // Unary Operators. 5876 case lltok::kw_fneg: { 5877 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5878 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 5879 if (Res != 0) 5880 return Res; 5881 if (FMF.any()) 5882 Inst->setFastMathFlags(FMF); 5883 return false; 5884 } 5885 // Binary Operators. 5886 case lltok::kw_add: 5887 case lltok::kw_sub: 5888 case lltok::kw_mul: 5889 case lltok::kw_shl: { 5890 bool NUW = EatIfPresent(lltok::kw_nuw); 5891 bool NSW = EatIfPresent(lltok::kw_nsw); 5892 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 5893 5894 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 5895 return true; 5896 5897 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 5898 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 5899 return false; 5900 } 5901 case lltok::kw_fadd: 5902 case lltok::kw_fsub: 5903 case lltok::kw_fmul: 5904 case lltok::kw_fdiv: 5905 case lltok::kw_frem: { 5906 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5907 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 5908 if (Res != 0) 5909 return Res; 5910 if (FMF.any()) 5911 Inst->setFastMathFlags(FMF); 5912 return 0; 5913 } 5914 5915 case lltok::kw_sdiv: 5916 case lltok::kw_udiv: 5917 case lltok::kw_lshr: 5918 case lltok::kw_ashr: { 5919 bool Exact = EatIfPresent(lltok::kw_exact); 5920 5921 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 5922 return true; 5923 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 5924 return false; 5925 } 5926 5927 case lltok::kw_urem: 5928 case lltok::kw_srem: 5929 return parseArithmetic(Inst, PFS, KeywordVal, 5930 /*IsFP*/ false); 5931 case lltok::kw_and: 5932 case lltok::kw_or: 5933 case lltok::kw_xor: 5934 return parseLogical(Inst, PFS, KeywordVal); 5935 case lltok::kw_icmp: 5936 return parseCompare(Inst, PFS, KeywordVal); 5937 case lltok::kw_fcmp: { 5938 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5939 int Res = parseCompare(Inst, PFS, KeywordVal); 5940 if (Res != 0) 5941 return Res; 5942 if (FMF.any()) 5943 Inst->setFastMathFlags(FMF); 5944 return 0; 5945 } 5946 5947 // Casts. 5948 case lltok::kw_trunc: 5949 case lltok::kw_zext: 5950 case lltok::kw_sext: 5951 case lltok::kw_fptrunc: 5952 case lltok::kw_fpext: 5953 case lltok::kw_bitcast: 5954 case lltok::kw_addrspacecast: 5955 case lltok::kw_uitofp: 5956 case lltok::kw_sitofp: 5957 case lltok::kw_fptoui: 5958 case lltok::kw_fptosi: 5959 case lltok::kw_inttoptr: 5960 case lltok::kw_ptrtoint: 5961 return parseCast(Inst, PFS, KeywordVal); 5962 // Other. 5963 case lltok::kw_select: { 5964 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5965 int Res = parseSelect(Inst, PFS); 5966 if (Res != 0) 5967 return Res; 5968 if (FMF.any()) { 5969 if (!isa<FPMathOperator>(Inst)) 5970 return error(Loc, "fast-math-flags specified for select without " 5971 "floating-point scalar or vector return type"); 5972 Inst->setFastMathFlags(FMF); 5973 } 5974 return 0; 5975 } 5976 case lltok::kw_va_arg: 5977 return parseVAArg(Inst, PFS); 5978 case lltok::kw_extractelement: 5979 return parseExtractElement(Inst, PFS); 5980 case lltok::kw_insertelement: 5981 return parseInsertElement(Inst, PFS); 5982 case lltok::kw_shufflevector: 5983 return parseShuffleVector(Inst, PFS); 5984 case lltok::kw_phi: { 5985 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 5986 int Res = parsePHI(Inst, PFS); 5987 if (Res != 0) 5988 return Res; 5989 if (FMF.any()) { 5990 if (!isa<FPMathOperator>(Inst)) 5991 return error(Loc, "fast-math-flags specified for phi without " 5992 "floating-point scalar or vector return type"); 5993 Inst->setFastMathFlags(FMF); 5994 } 5995 return 0; 5996 } 5997 case lltok::kw_landingpad: 5998 return parseLandingPad(Inst, PFS); 5999 case lltok::kw_freeze: 6000 return parseFreeze(Inst, PFS); 6001 // Call. 6002 case lltok::kw_call: 6003 return parseCall(Inst, PFS, CallInst::TCK_None); 6004 case lltok::kw_tail: 6005 return parseCall(Inst, PFS, CallInst::TCK_Tail); 6006 case lltok::kw_musttail: 6007 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 6008 case lltok::kw_notail: 6009 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 6010 // Memory. 6011 case lltok::kw_alloca: 6012 return parseAlloc(Inst, PFS); 6013 case lltok::kw_load: 6014 return parseLoad(Inst, PFS); 6015 case lltok::kw_store: 6016 return parseStore(Inst, PFS); 6017 case lltok::kw_cmpxchg: 6018 return parseCmpXchg(Inst, PFS); 6019 case lltok::kw_atomicrmw: 6020 return parseAtomicRMW(Inst, PFS); 6021 case lltok::kw_fence: 6022 return parseFence(Inst, PFS); 6023 case lltok::kw_getelementptr: 6024 return parseGetElementPtr(Inst, PFS); 6025 case lltok::kw_extractvalue: 6026 return parseExtractValue(Inst, PFS); 6027 case lltok::kw_insertvalue: 6028 return parseInsertValue(Inst, PFS); 6029 } 6030 } 6031 6032 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 6033 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 6034 if (Opc == Instruction::FCmp) { 6035 switch (Lex.getKind()) { 6036 default: 6037 return tokError("expected fcmp predicate (e.g. 'oeq')"); 6038 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 6039 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 6040 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 6041 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 6042 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 6043 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 6044 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 6045 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 6046 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 6047 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 6048 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 6049 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 6050 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 6051 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 6052 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 6053 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 6054 } 6055 } else { 6056 switch (Lex.getKind()) { 6057 default: 6058 return tokError("expected icmp predicate (e.g. 'eq')"); 6059 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 6060 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 6061 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 6062 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 6063 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 6064 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 6065 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 6066 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 6067 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 6068 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 6069 } 6070 } 6071 Lex.Lex(); 6072 return false; 6073 } 6074 6075 //===----------------------------------------------------------------------===// 6076 // Terminator Instructions. 6077 //===----------------------------------------------------------------------===// 6078 6079 /// parseRet - parse a return instruction. 6080 /// ::= 'ret' void (',' !dbg, !1)* 6081 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 6082 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 6083 PerFunctionState &PFS) { 6084 SMLoc TypeLoc = Lex.getLoc(); 6085 Type *Ty = nullptr; 6086 if (parseType(Ty, true /*void allowed*/)) 6087 return true; 6088 6089 Type *ResType = PFS.getFunction().getReturnType(); 6090 6091 if (Ty->isVoidTy()) { 6092 if (!ResType->isVoidTy()) 6093 return error(TypeLoc, "value doesn't match function result type '" + 6094 getTypeString(ResType) + "'"); 6095 6096 Inst = ReturnInst::Create(Context); 6097 return false; 6098 } 6099 6100 Value *RV; 6101 if (parseValue(Ty, RV, PFS)) 6102 return true; 6103 6104 if (ResType != RV->getType()) 6105 return error(TypeLoc, "value doesn't match function result type '" + 6106 getTypeString(ResType) + "'"); 6107 6108 Inst = ReturnInst::Create(Context, RV); 6109 return false; 6110 } 6111 6112 /// parseBr 6113 /// ::= 'br' TypeAndValue 6114 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6115 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 6116 LocTy Loc, Loc2; 6117 Value *Op0; 6118 BasicBlock *Op1, *Op2; 6119 if (parseTypeAndValue(Op0, Loc, PFS)) 6120 return true; 6121 6122 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 6123 Inst = BranchInst::Create(BB); 6124 return false; 6125 } 6126 6127 if (Op0->getType() != Type::getInt1Ty(Context)) 6128 return error(Loc, "branch condition must have 'i1' type"); 6129 6130 if (parseToken(lltok::comma, "expected ',' after branch condition") || 6131 parseTypeAndBasicBlock(Op1, Loc, PFS) || 6132 parseToken(lltok::comma, "expected ',' after true destination") || 6133 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 6134 return true; 6135 6136 Inst = BranchInst::Create(Op1, Op2, Op0); 6137 return false; 6138 } 6139 6140 /// parseSwitch 6141 /// Instruction 6142 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 6143 /// JumpTable 6144 /// ::= (TypeAndValue ',' TypeAndValue)* 6145 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6146 LocTy CondLoc, BBLoc; 6147 Value *Cond; 6148 BasicBlock *DefaultBB; 6149 if (parseTypeAndValue(Cond, CondLoc, PFS) || 6150 parseToken(lltok::comma, "expected ',' after switch condition") || 6151 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 6152 parseToken(lltok::lsquare, "expected '[' with switch table")) 6153 return true; 6154 6155 if (!Cond->getType()->isIntegerTy()) 6156 return error(CondLoc, "switch condition must have integer type"); 6157 6158 // parse the jump table pairs. 6159 SmallPtrSet<Value*, 32> SeenCases; 6160 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 6161 while (Lex.getKind() != lltok::rsquare) { 6162 Value *Constant; 6163 BasicBlock *DestBB; 6164 6165 if (parseTypeAndValue(Constant, CondLoc, PFS) || 6166 parseToken(lltok::comma, "expected ',' after case value") || 6167 parseTypeAndBasicBlock(DestBB, PFS)) 6168 return true; 6169 6170 if (!SeenCases.insert(Constant).second) 6171 return error(CondLoc, "duplicate case value in switch"); 6172 if (!isa<ConstantInt>(Constant)) 6173 return error(CondLoc, "case value is not a constant integer"); 6174 6175 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 6176 } 6177 6178 Lex.Lex(); // Eat the ']'. 6179 6180 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 6181 for (unsigned i = 0, e = Table.size(); i != e; ++i) 6182 SI->addCase(Table[i].first, Table[i].second); 6183 Inst = SI; 6184 return false; 6185 } 6186 6187 /// parseIndirectBr 6188 /// Instruction 6189 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 6190 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 6191 LocTy AddrLoc; 6192 Value *Address; 6193 if (parseTypeAndValue(Address, AddrLoc, PFS) || 6194 parseToken(lltok::comma, "expected ',' after indirectbr address") || 6195 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 6196 return true; 6197 6198 if (!Address->getType()->isPointerTy()) 6199 return error(AddrLoc, "indirectbr address must have pointer type"); 6200 6201 // parse the destination list. 6202 SmallVector<BasicBlock*, 16> DestList; 6203 6204 if (Lex.getKind() != lltok::rsquare) { 6205 BasicBlock *DestBB; 6206 if (parseTypeAndBasicBlock(DestBB, PFS)) 6207 return true; 6208 DestList.push_back(DestBB); 6209 6210 while (EatIfPresent(lltok::comma)) { 6211 if (parseTypeAndBasicBlock(DestBB, PFS)) 6212 return true; 6213 DestList.push_back(DestBB); 6214 } 6215 } 6216 6217 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6218 return true; 6219 6220 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 6221 for (unsigned i = 0, e = DestList.size(); i != e; ++i) 6222 IBI->addDestination(DestList[i]); 6223 Inst = IBI; 6224 return false; 6225 } 6226 6227 /// parseInvoke 6228 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 6229 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 6230 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 6231 LocTy CallLoc = Lex.getLoc(); 6232 AttrBuilder RetAttrs, FnAttrs; 6233 std::vector<unsigned> FwdRefAttrGrps; 6234 LocTy NoBuiltinLoc; 6235 unsigned CC; 6236 unsigned InvokeAddrSpace; 6237 Type *RetType = nullptr; 6238 LocTy RetTypeLoc; 6239 ValID CalleeID; 6240 SmallVector<ParamInfo, 16> ArgList; 6241 SmallVector<OperandBundleDef, 2> BundleList; 6242 6243 BasicBlock *NormalBB, *UnwindBB; 6244 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6245 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 6246 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6247 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 6248 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6249 NoBuiltinLoc) || 6250 parseOptionalOperandBundles(BundleList, PFS) || 6251 parseToken(lltok::kw_to, "expected 'to' in invoke") || 6252 parseTypeAndBasicBlock(NormalBB, PFS) || 6253 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 6254 parseTypeAndBasicBlock(UnwindBB, PFS)) 6255 return true; 6256 6257 // If RetType is a non-function pointer type, then this is the short syntax 6258 // for the call, which means that RetType is just the return type. Infer the 6259 // rest of the function argument types from the arguments that are present. 6260 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6261 if (!Ty) { 6262 // Pull out the types of all of the arguments... 6263 std::vector<Type*> ParamTypes; 6264 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6265 ParamTypes.push_back(ArgList[i].V->getType()); 6266 6267 if (!FunctionType::isValidReturnType(RetType)) 6268 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6269 6270 Ty = FunctionType::get(RetType, ParamTypes, false); 6271 } 6272 6273 CalleeID.FTy = Ty; 6274 6275 // Look up the callee. 6276 Value *Callee; 6277 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 6278 Callee, &PFS)) 6279 return true; 6280 6281 // Set up the Attribute for the function. 6282 SmallVector<Value *, 8> Args; 6283 SmallVector<AttributeSet, 8> ArgAttrs; 6284 6285 // Loop through FunctionType's arguments and ensure they are specified 6286 // correctly. Also, gather any parameter attributes. 6287 FunctionType::param_iterator I = Ty->param_begin(); 6288 FunctionType::param_iterator E = Ty->param_end(); 6289 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6290 Type *ExpectedTy = nullptr; 6291 if (I != E) { 6292 ExpectedTy = *I++; 6293 } else if (!Ty->isVarArg()) { 6294 return error(ArgList[i].Loc, "too many arguments specified"); 6295 } 6296 6297 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6298 return error(ArgList[i].Loc, "argument is not of expected type '" + 6299 getTypeString(ExpectedTy) + "'"); 6300 Args.push_back(ArgList[i].V); 6301 ArgAttrs.push_back(ArgList[i].Attrs); 6302 } 6303 6304 if (I != E) 6305 return error(CallLoc, "not enough parameters specified for call"); 6306 6307 if (FnAttrs.hasAlignmentAttr()) 6308 return error(CallLoc, "invoke instructions may not have an alignment"); 6309 6310 // Finish off the Attribute and check them 6311 AttributeList PAL = 6312 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6313 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6314 6315 InvokeInst *II = 6316 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 6317 II->setCallingConv(CC); 6318 II->setAttributes(PAL); 6319 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 6320 Inst = II; 6321 return false; 6322 } 6323 6324 /// parseResume 6325 /// ::= 'resume' TypeAndValue 6326 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 6327 Value *Exn; LocTy ExnLoc; 6328 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 6329 return true; 6330 6331 ResumeInst *RI = ResumeInst::Create(Exn); 6332 Inst = RI; 6333 return false; 6334 } 6335 6336 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 6337 PerFunctionState &PFS) { 6338 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 6339 return true; 6340 6341 while (Lex.getKind() != lltok::rsquare) { 6342 // If this isn't the first argument, we need a comma. 6343 if (!Args.empty() && 6344 parseToken(lltok::comma, "expected ',' in argument list")) 6345 return true; 6346 6347 // parse the argument. 6348 LocTy ArgLoc; 6349 Type *ArgTy = nullptr; 6350 if (parseType(ArgTy, ArgLoc)) 6351 return true; 6352 6353 Value *V; 6354 if (ArgTy->isMetadataTy()) { 6355 if (parseMetadataAsValue(V, PFS)) 6356 return true; 6357 } else { 6358 if (parseValue(ArgTy, V, PFS)) 6359 return true; 6360 } 6361 Args.push_back(V); 6362 } 6363 6364 Lex.Lex(); // Lex the ']'. 6365 return false; 6366 } 6367 6368 /// parseCleanupRet 6369 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 6370 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 6371 Value *CleanupPad = nullptr; 6372 6373 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 6374 return true; 6375 6376 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 6377 return true; 6378 6379 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 6380 return true; 6381 6382 BasicBlock *UnwindBB = nullptr; 6383 if (Lex.getKind() == lltok::kw_to) { 6384 Lex.Lex(); 6385 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 6386 return true; 6387 } else { 6388 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 6389 return true; 6390 } 6391 } 6392 6393 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 6394 return false; 6395 } 6396 6397 /// parseCatchRet 6398 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 6399 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 6400 Value *CatchPad = nullptr; 6401 6402 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 6403 return true; 6404 6405 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 6406 return true; 6407 6408 BasicBlock *BB; 6409 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 6410 parseTypeAndBasicBlock(BB, PFS)) 6411 return true; 6412 6413 Inst = CatchReturnInst::Create(CatchPad, BB); 6414 return false; 6415 } 6416 6417 /// parseCatchSwitch 6418 /// ::= 'catchswitch' within Parent 6419 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 6420 Value *ParentPad; 6421 6422 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 6423 return true; 6424 6425 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6426 Lex.getKind() != lltok::LocalVarID) 6427 return tokError("expected scope value for catchswitch"); 6428 6429 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6430 return true; 6431 6432 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 6433 return true; 6434 6435 SmallVector<BasicBlock *, 32> Table; 6436 do { 6437 BasicBlock *DestBB; 6438 if (parseTypeAndBasicBlock(DestBB, PFS)) 6439 return true; 6440 Table.push_back(DestBB); 6441 } while (EatIfPresent(lltok::comma)); 6442 6443 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 6444 return true; 6445 6446 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 6447 return true; 6448 6449 BasicBlock *UnwindBB = nullptr; 6450 if (EatIfPresent(lltok::kw_to)) { 6451 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 6452 return true; 6453 } else { 6454 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 6455 return true; 6456 } 6457 6458 auto *CatchSwitch = 6459 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 6460 for (BasicBlock *DestBB : Table) 6461 CatchSwitch->addHandler(DestBB); 6462 Inst = CatchSwitch; 6463 return false; 6464 } 6465 6466 /// parseCatchPad 6467 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 6468 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 6469 Value *CatchSwitch = nullptr; 6470 6471 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 6472 return true; 6473 6474 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 6475 return tokError("expected scope value for catchpad"); 6476 6477 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 6478 return true; 6479 6480 SmallVector<Value *, 8> Args; 6481 if (parseExceptionArgs(Args, PFS)) 6482 return true; 6483 6484 Inst = CatchPadInst::Create(CatchSwitch, Args); 6485 return false; 6486 } 6487 6488 /// parseCleanupPad 6489 /// ::= 'cleanuppad' within Parent ParamList 6490 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 6491 Value *ParentPad = nullptr; 6492 6493 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 6494 return true; 6495 6496 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 6497 Lex.getKind() != lltok::LocalVarID) 6498 return tokError("expected scope value for cleanuppad"); 6499 6500 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 6501 return true; 6502 6503 SmallVector<Value *, 8> Args; 6504 if (parseExceptionArgs(Args, PFS)) 6505 return true; 6506 6507 Inst = CleanupPadInst::Create(ParentPad, Args); 6508 return false; 6509 } 6510 6511 //===----------------------------------------------------------------------===// 6512 // Unary Operators. 6513 //===----------------------------------------------------------------------===// 6514 6515 /// parseUnaryOp 6516 /// ::= UnaryOp TypeAndValue ',' Value 6517 /// 6518 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6519 /// operand is allowed. 6520 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 6521 unsigned Opc, bool IsFP) { 6522 LocTy Loc; Value *LHS; 6523 if (parseTypeAndValue(LHS, Loc, PFS)) 6524 return true; 6525 6526 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6527 : LHS->getType()->isIntOrIntVectorTy(); 6528 6529 if (!Valid) 6530 return error(Loc, "invalid operand type for instruction"); 6531 6532 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 6533 return false; 6534 } 6535 6536 /// parseCallBr 6537 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 6538 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 6539 /// '[' LabelList ']' 6540 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 6541 LocTy CallLoc = Lex.getLoc(); 6542 AttrBuilder RetAttrs, FnAttrs; 6543 std::vector<unsigned> FwdRefAttrGrps; 6544 LocTy NoBuiltinLoc; 6545 unsigned CC; 6546 Type *RetType = nullptr; 6547 LocTy RetTypeLoc; 6548 ValID CalleeID; 6549 SmallVector<ParamInfo, 16> ArgList; 6550 SmallVector<OperandBundleDef, 2> BundleList; 6551 6552 BasicBlock *DefaultDest; 6553 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6554 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6555 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 6556 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 6557 NoBuiltinLoc) || 6558 parseOptionalOperandBundles(BundleList, PFS) || 6559 parseToken(lltok::kw_to, "expected 'to' in callbr") || 6560 parseTypeAndBasicBlock(DefaultDest, PFS) || 6561 parseToken(lltok::lsquare, "expected '[' in callbr")) 6562 return true; 6563 6564 // parse the destination list. 6565 SmallVector<BasicBlock *, 16> IndirectDests; 6566 6567 if (Lex.getKind() != lltok::rsquare) { 6568 BasicBlock *DestBB; 6569 if (parseTypeAndBasicBlock(DestBB, PFS)) 6570 return true; 6571 IndirectDests.push_back(DestBB); 6572 6573 while (EatIfPresent(lltok::comma)) { 6574 if (parseTypeAndBasicBlock(DestBB, PFS)) 6575 return true; 6576 IndirectDests.push_back(DestBB); 6577 } 6578 } 6579 6580 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 6581 return true; 6582 6583 // If RetType is a non-function pointer type, then this is the short syntax 6584 // for the call, which means that RetType is just the return type. Infer the 6585 // rest of the function argument types from the arguments that are present. 6586 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6587 if (!Ty) { 6588 // Pull out the types of all of the arguments... 6589 std::vector<Type *> ParamTypes; 6590 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6591 ParamTypes.push_back(ArgList[i].V->getType()); 6592 6593 if (!FunctionType::isValidReturnType(RetType)) 6594 return error(RetTypeLoc, "Invalid result type for LLVM function"); 6595 6596 Ty = FunctionType::get(RetType, ParamTypes, false); 6597 } 6598 6599 CalleeID.FTy = Ty; 6600 6601 // Look up the callee. 6602 Value *Callee; 6603 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 6604 return true; 6605 6606 // Set up the Attribute for the function. 6607 SmallVector<Value *, 8> Args; 6608 SmallVector<AttributeSet, 8> ArgAttrs; 6609 6610 // Loop through FunctionType's arguments and ensure they are specified 6611 // correctly. Also, gather any parameter attributes. 6612 FunctionType::param_iterator I = Ty->param_begin(); 6613 FunctionType::param_iterator E = Ty->param_end(); 6614 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 6615 Type *ExpectedTy = nullptr; 6616 if (I != E) { 6617 ExpectedTy = *I++; 6618 } else if (!Ty->isVarArg()) { 6619 return error(ArgList[i].Loc, "too many arguments specified"); 6620 } 6621 6622 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 6623 return error(ArgList[i].Loc, "argument is not of expected type '" + 6624 getTypeString(ExpectedTy) + "'"); 6625 Args.push_back(ArgList[i].V); 6626 ArgAttrs.push_back(ArgList[i].Attrs); 6627 } 6628 6629 if (I != E) 6630 return error(CallLoc, "not enough parameters specified for call"); 6631 6632 if (FnAttrs.hasAlignmentAttr()) 6633 return error(CallLoc, "callbr instructions may not have an alignment"); 6634 6635 // Finish off the Attribute and check them 6636 AttributeList PAL = 6637 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 6638 AttributeSet::get(Context, RetAttrs), ArgAttrs); 6639 6640 CallBrInst *CBI = 6641 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 6642 BundleList); 6643 CBI->setCallingConv(CC); 6644 CBI->setAttributes(PAL); 6645 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 6646 Inst = CBI; 6647 return false; 6648 } 6649 6650 //===----------------------------------------------------------------------===// 6651 // Binary Operators. 6652 //===----------------------------------------------------------------------===// 6653 6654 /// parseArithmetic 6655 /// ::= ArithmeticOps TypeAndValue ',' Value 6656 /// 6657 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 6658 /// operand is allowed. 6659 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 6660 unsigned Opc, bool IsFP) { 6661 LocTy Loc; Value *LHS, *RHS; 6662 if (parseTypeAndValue(LHS, Loc, PFS) || 6663 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 6664 parseValue(LHS->getType(), RHS, PFS)) 6665 return true; 6666 6667 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 6668 : LHS->getType()->isIntOrIntVectorTy(); 6669 6670 if (!Valid) 6671 return error(Loc, "invalid operand type for instruction"); 6672 6673 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6674 return false; 6675 } 6676 6677 /// parseLogical 6678 /// ::= ArithmeticOps TypeAndValue ',' Value { 6679 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 6680 unsigned Opc) { 6681 LocTy Loc; Value *LHS, *RHS; 6682 if (parseTypeAndValue(LHS, Loc, PFS) || 6683 parseToken(lltok::comma, "expected ',' in logical operation") || 6684 parseValue(LHS->getType(), RHS, PFS)) 6685 return true; 6686 6687 if (!LHS->getType()->isIntOrIntVectorTy()) 6688 return error(Loc, 6689 "instruction requires integer or integer vector operands"); 6690 6691 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 6692 return false; 6693 } 6694 6695 /// parseCompare 6696 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 6697 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 6698 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 6699 unsigned Opc) { 6700 // parse the integer/fp comparison predicate. 6701 LocTy Loc; 6702 unsigned Pred; 6703 Value *LHS, *RHS; 6704 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 6705 parseToken(lltok::comma, "expected ',' after compare value") || 6706 parseValue(LHS->getType(), RHS, PFS)) 6707 return true; 6708 6709 if (Opc == Instruction::FCmp) { 6710 if (!LHS->getType()->isFPOrFPVectorTy()) 6711 return error(Loc, "fcmp requires floating point operands"); 6712 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6713 } else { 6714 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 6715 if (!LHS->getType()->isIntOrIntVectorTy() && 6716 !LHS->getType()->isPtrOrPtrVectorTy()) 6717 return error(Loc, "icmp requires integer operands"); 6718 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 6719 } 6720 return false; 6721 } 6722 6723 //===----------------------------------------------------------------------===// 6724 // Other Instructions. 6725 //===----------------------------------------------------------------------===// 6726 6727 /// parseCast 6728 /// ::= CastOpc TypeAndValue 'to' Type 6729 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 6730 unsigned Opc) { 6731 LocTy Loc; 6732 Value *Op; 6733 Type *DestTy = nullptr; 6734 if (parseTypeAndValue(Op, Loc, PFS) || 6735 parseToken(lltok::kw_to, "expected 'to' after cast value") || 6736 parseType(DestTy)) 6737 return true; 6738 6739 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 6740 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 6741 return error(Loc, "invalid cast opcode for cast from '" + 6742 getTypeString(Op->getType()) + "' to '" + 6743 getTypeString(DestTy) + "'"); 6744 } 6745 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 6746 return false; 6747 } 6748 6749 /// parseSelect 6750 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6751 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 6752 LocTy Loc; 6753 Value *Op0, *Op1, *Op2; 6754 if (parseTypeAndValue(Op0, Loc, PFS) || 6755 parseToken(lltok::comma, "expected ',' after select condition") || 6756 parseTypeAndValue(Op1, PFS) || 6757 parseToken(lltok::comma, "expected ',' after select value") || 6758 parseTypeAndValue(Op2, PFS)) 6759 return true; 6760 6761 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 6762 return error(Loc, Reason); 6763 6764 Inst = SelectInst::Create(Op0, Op1, Op2); 6765 return false; 6766 } 6767 6768 /// parseVAArg 6769 /// ::= 'va_arg' TypeAndValue ',' Type 6770 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 6771 Value *Op; 6772 Type *EltTy = nullptr; 6773 LocTy TypeLoc; 6774 if (parseTypeAndValue(Op, PFS) || 6775 parseToken(lltok::comma, "expected ',' after vaarg operand") || 6776 parseType(EltTy, TypeLoc)) 6777 return true; 6778 6779 if (!EltTy->isFirstClassType()) 6780 return error(TypeLoc, "va_arg requires operand with first class type"); 6781 6782 Inst = new VAArgInst(Op, EltTy); 6783 return false; 6784 } 6785 6786 /// parseExtractElement 6787 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 6788 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 6789 LocTy Loc; 6790 Value *Op0, *Op1; 6791 if (parseTypeAndValue(Op0, Loc, PFS) || 6792 parseToken(lltok::comma, "expected ',' after extract value") || 6793 parseTypeAndValue(Op1, PFS)) 6794 return true; 6795 6796 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 6797 return error(Loc, "invalid extractelement operands"); 6798 6799 Inst = ExtractElementInst::Create(Op0, Op1); 6800 return false; 6801 } 6802 6803 /// parseInsertElement 6804 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6805 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 6806 LocTy Loc; 6807 Value *Op0, *Op1, *Op2; 6808 if (parseTypeAndValue(Op0, Loc, PFS) || 6809 parseToken(lltok::comma, "expected ',' after insertelement value") || 6810 parseTypeAndValue(Op1, PFS) || 6811 parseToken(lltok::comma, "expected ',' after insertelement value") || 6812 parseTypeAndValue(Op2, PFS)) 6813 return true; 6814 6815 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 6816 return error(Loc, "invalid insertelement operands"); 6817 6818 Inst = InsertElementInst::Create(Op0, Op1, Op2); 6819 return false; 6820 } 6821 6822 /// parseShuffleVector 6823 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 6824 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 6825 LocTy Loc; 6826 Value *Op0, *Op1, *Op2; 6827 if (parseTypeAndValue(Op0, Loc, PFS) || 6828 parseToken(lltok::comma, "expected ',' after shuffle mask") || 6829 parseTypeAndValue(Op1, PFS) || 6830 parseToken(lltok::comma, "expected ',' after shuffle value") || 6831 parseTypeAndValue(Op2, PFS)) 6832 return true; 6833 6834 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 6835 return error(Loc, "invalid shufflevector operands"); 6836 6837 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 6838 return false; 6839 } 6840 6841 /// parsePHI 6842 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 6843 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 6844 Type *Ty = nullptr; LocTy TypeLoc; 6845 Value *Op0, *Op1; 6846 6847 if (parseType(Ty, TypeLoc) || 6848 parseToken(lltok::lsquare, "expected '[' in phi value list") || 6849 parseValue(Ty, Op0, PFS) || 6850 parseToken(lltok::comma, "expected ',' after insertelement value") || 6851 parseValue(Type::getLabelTy(Context), Op1, PFS) || 6852 parseToken(lltok::rsquare, "expected ']' in phi value list")) 6853 return true; 6854 6855 bool AteExtraComma = false; 6856 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 6857 6858 while (true) { 6859 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 6860 6861 if (!EatIfPresent(lltok::comma)) 6862 break; 6863 6864 if (Lex.getKind() == lltok::MetadataVar) { 6865 AteExtraComma = true; 6866 break; 6867 } 6868 6869 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 6870 parseValue(Ty, Op0, PFS) || 6871 parseToken(lltok::comma, "expected ',' after insertelement value") || 6872 parseValue(Type::getLabelTy(Context), Op1, PFS) || 6873 parseToken(lltok::rsquare, "expected ']' in phi value list")) 6874 return true; 6875 } 6876 6877 if (!Ty->isFirstClassType()) 6878 return error(TypeLoc, "phi node must have first class type"); 6879 6880 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 6881 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 6882 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 6883 Inst = PN; 6884 return AteExtraComma ? InstExtraComma : InstNormal; 6885 } 6886 6887 /// parseLandingPad 6888 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 6889 /// Clause 6890 /// ::= 'catch' TypeAndValue 6891 /// ::= 'filter' 6892 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 6893 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 6894 Type *Ty = nullptr; LocTy TyLoc; 6895 6896 if (parseType(Ty, TyLoc)) 6897 return true; 6898 6899 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 6900 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 6901 6902 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 6903 LandingPadInst::ClauseType CT; 6904 if (EatIfPresent(lltok::kw_catch)) 6905 CT = LandingPadInst::Catch; 6906 else if (EatIfPresent(lltok::kw_filter)) 6907 CT = LandingPadInst::Filter; 6908 else 6909 return tokError("expected 'catch' or 'filter' clause type"); 6910 6911 Value *V; 6912 LocTy VLoc; 6913 if (parseTypeAndValue(V, VLoc, PFS)) 6914 return true; 6915 6916 // A 'catch' type expects a non-array constant. A filter clause expects an 6917 // array constant. 6918 if (CT == LandingPadInst::Catch) { 6919 if (isa<ArrayType>(V->getType())) 6920 error(VLoc, "'catch' clause has an invalid type"); 6921 } else { 6922 if (!isa<ArrayType>(V->getType())) 6923 error(VLoc, "'filter' clause has an invalid type"); 6924 } 6925 6926 Constant *CV = dyn_cast<Constant>(V); 6927 if (!CV) 6928 return error(VLoc, "clause argument must be a constant"); 6929 LP->addClause(CV); 6930 } 6931 6932 Inst = LP.release(); 6933 return false; 6934 } 6935 6936 /// parseFreeze 6937 /// ::= 'freeze' Type Value 6938 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 6939 LocTy Loc; 6940 Value *Op; 6941 if (parseTypeAndValue(Op, Loc, PFS)) 6942 return true; 6943 6944 Inst = new FreezeInst(Op); 6945 return false; 6946 } 6947 6948 /// parseCall 6949 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 6950 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6951 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 6952 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6953 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 6954 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6955 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 6956 /// OptionalAttrs Type Value ParameterList OptionalAttrs 6957 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 6958 CallInst::TailCallKind TCK) { 6959 AttrBuilder RetAttrs, FnAttrs; 6960 std::vector<unsigned> FwdRefAttrGrps; 6961 LocTy BuiltinLoc; 6962 unsigned CallAddrSpace; 6963 unsigned CC; 6964 Type *RetType = nullptr; 6965 LocTy RetTypeLoc; 6966 ValID CalleeID; 6967 SmallVector<ParamInfo, 16> ArgList; 6968 SmallVector<OperandBundleDef, 2> BundleList; 6969 LocTy CallLoc = Lex.getLoc(); 6970 6971 if (TCK != CallInst::TCK_None && 6972 parseToken(lltok::kw_call, 6973 "expected 'tail call', 'musttail call', or 'notail call'")) 6974 return true; 6975 6976 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6977 6978 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6979 parseOptionalProgramAddrSpace(CallAddrSpace) || 6980 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 6981 parseValID(CalleeID, &PFS) || 6982 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 6983 PFS.getFunction().isVarArg()) || 6984 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 6985 parseOptionalOperandBundles(BundleList, PFS)) 6986 return true; 6987 6988 // If RetType is a non-function pointer type, then this is the short syntax 6989 // for the call, which means that RetType is just the return type. Infer the 6990 // rest of the function argument types from the arguments that are present. 6991 FunctionType *Ty = dyn_cast<FunctionType>(RetType); 6992 if (!Ty) { 6993 // Pull out the types of all of the arguments... 6994 std::vector<Type*> ParamTypes; 6995 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) 6996 ParamTypes.push_back(ArgList[i].V->getType()); 6997 6998 if (!FunctionType::isValidReturnType(RetType)) 6999 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7000 7001 Ty = FunctionType::get(RetType, ParamTypes, false); 7002 } 7003 7004 CalleeID.FTy = Ty; 7005 7006 // Look up the callee. 7007 Value *Callee; 7008 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 7009 &PFS)) 7010 return true; 7011 7012 // Set up the Attribute for the function. 7013 SmallVector<AttributeSet, 8> Attrs; 7014 7015 SmallVector<Value*, 8> Args; 7016 7017 // Loop through FunctionType's arguments and ensure they are specified 7018 // correctly. Also, gather any parameter attributes. 7019 FunctionType::param_iterator I = Ty->param_begin(); 7020 FunctionType::param_iterator E = Ty->param_end(); 7021 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) { 7022 Type *ExpectedTy = nullptr; 7023 if (I != E) { 7024 ExpectedTy = *I++; 7025 } else if (!Ty->isVarArg()) { 7026 return error(ArgList[i].Loc, "too many arguments specified"); 7027 } 7028 7029 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType()) 7030 return error(ArgList[i].Loc, "argument is not of expected type '" + 7031 getTypeString(ExpectedTy) + "'"); 7032 Args.push_back(ArgList[i].V); 7033 Attrs.push_back(ArgList[i].Attrs); 7034 } 7035 7036 if (I != E) 7037 return error(CallLoc, "not enough parameters specified for call"); 7038 7039 if (FnAttrs.hasAlignmentAttr()) 7040 return error(CallLoc, "call instructions may not have an alignment"); 7041 7042 // Finish off the Attribute and check them 7043 AttributeList PAL = 7044 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7045 AttributeSet::get(Context, RetAttrs), Attrs); 7046 7047 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 7048 CI->setTailCallKind(TCK); 7049 CI->setCallingConv(CC); 7050 if (FMF.any()) { 7051 if (!isa<FPMathOperator>(CI)) { 7052 CI->deleteValue(); 7053 return error(CallLoc, "fast-math-flags specified for call without " 7054 "floating-point scalar or vector return type"); 7055 } 7056 CI->setFastMathFlags(FMF); 7057 } 7058 CI->setAttributes(PAL); 7059 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 7060 Inst = CI; 7061 return false; 7062 } 7063 7064 //===----------------------------------------------------------------------===// 7065 // Memory Instructions. 7066 //===----------------------------------------------------------------------===// 7067 7068 /// parseAlloc 7069 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 7070 /// (',' 'align' i32)? (',', 'addrspace(n))? 7071 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 7072 Value *Size = nullptr; 7073 LocTy SizeLoc, TyLoc, ASLoc; 7074 MaybeAlign Alignment; 7075 unsigned AddrSpace = 0; 7076 Type *Ty = nullptr; 7077 7078 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 7079 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 7080 7081 if (parseType(Ty, TyLoc)) 7082 return true; 7083 7084 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 7085 return error(TyLoc, "invalid type for alloca"); 7086 7087 bool AteExtraComma = false; 7088 if (EatIfPresent(lltok::comma)) { 7089 if (Lex.getKind() == lltok::kw_align) { 7090 if (parseOptionalAlignment(Alignment)) 7091 return true; 7092 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7093 return true; 7094 } else if (Lex.getKind() == lltok::kw_addrspace) { 7095 ASLoc = Lex.getLoc(); 7096 if (parseOptionalAddrSpace(AddrSpace)) 7097 return true; 7098 } else if (Lex.getKind() == lltok::MetadataVar) { 7099 AteExtraComma = true; 7100 } else { 7101 if (parseTypeAndValue(Size, SizeLoc, PFS)) 7102 return true; 7103 if (EatIfPresent(lltok::comma)) { 7104 if (Lex.getKind() == lltok::kw_align) { 7105 if (parseOptionalAlignment(Alignment)) 7106 return true; 7107 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 7108 return true; 7109 } else if (Lex.getKind() == lltok::kw_addrspace) { 7110 ASLoc = Lex.getLoc(); 7111 if (parseOptionalAddrSpace(AddrSpace)) 7112 return true; 7113 } else if (Lex.getKind() == lltok::MetadataVar) { 7114 AteExtraComma = true; 7115 } 7116 } 7117 } 7118 } 7119 7120 if (Size && !Size->getType()->isIntegerTy()) 7121 return error(SizeLoc, "element count must have integer type"); 7122 7123 SmallPtrSet<Type *, 4> Visited; 7124 if (!Alignment && !Ty->isSized(&Visited)) 7125 return error(TyLoc, "Cannot allocate unsized type"); 7126 if (!Alignment) 7127 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 7128 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 7129 AI->setUsedWithInAlloca(IsInAlloca); 7130 AI->setSwiftError(IsSwiftError); 7131 Inst = AI; 7132 return AteExtraComma ? InstExtraComma : InstNormal; 7133 } 7134 7135 /// parseLoad 7136 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 7137 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 7138 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7139 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 7140 Value *Val; LocTy Loc; 7141 MaybeAlign Alignment; 7142 bool AteExtraComma = false; 7143 bool isAtomic = false; 7144 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7145 SyncScope::ID SSID = SyncScope::System; 7146 7147 if (Lex.getKind() == lltok::kw_atomic) { 7148 isAtomic = true; 7149 Lex.Lex(); 7150 } 7151 7152 bool isVolatile = false; 7153 if (Lex.getKind() == lltok::kw_volatile) { 7154 isVolatile = true; 7155 Lex.Lex(); 7156 } 7157 7158 Type *Ty; 7159 LocTy ExplicitTypeLoc = Lex.getLoc(); 7160 if (parseType(Ty) || 7161 parseToken(lltok::comma, "expected comma after load's type") || 7162 parseTypeAndValue(Val, Loc, PFS) || 7163 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7164 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7165 return true; 7166 7167 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 7168 return error(Loc, "load operand must be a pointer to a first class type"); 7169 if (isAtomic && !Alignment) 7170 return error(Loc, "atomic load must have explicit non-zero alignment"); 7171 if (Ordering == AtomicOrdering::Release || 7172 Ordering == AtomicOrdering::AcquireRelease) 7173 return error(Loc, "atomic load cannot use Release ordering"); 7174 7175 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) { 7176 return error( 7177 ExplicitTypeLoc, 7178 typeComparisonErrorMessage( 7179 "explicit pointee type doesn't match operand's pointee type", Ty, 7180 cast<PointerType>(Val->getType())->getElementType())); 7181 } 7182 SmallPtrSet<Type *, 4> Visited; 7183 if (!Alignment && !Ty->isSized(&Visited)) 7184 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 7185 if (!Alignment) 7186 Alignment = M->getDataLayout().getABITypeAlign(Ty); 7187 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 7188 return AteExtraComma ? InstExtraComma : InstNormal; 7189 } 7190 7191 /// parseStore 7192 7193 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 7194 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 7195 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 7196 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 7197 Value *Val, *Ptr; LocTy Loc, PtrLoc; 7198 MaybeAlign Alignment; 7199 bool AteExtraComma = false; 7200 bool isAtomic = false; 7201 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7202 SyncScope::ID SSID = SyncScope::System; 7203 7204 if (Lex.getKind() == lltok::kw_atomic) { 7205 isAtomic = true; 7206 Lex.Lex(); 7207 } 7208 7209 bool isVolatile = false; 7210 if (Lex.getKind() == lltok::kw_volatile) { 7211 isVolatile = true; 7212 Lex.Lex(); 7213 } 7214 7215 if (parseTypeAndValue(Val, Loc, PFS) || 7216 parseToken(lltok::comma, "expected ',' after store operand") || 7217 parseTypeAndValue(Ptr, PtrLoc, PFS) || 7218 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 7219 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7220 return true; 7221 7222 if (!Ptr->getType()->isPointerTy()) 7223 return error(PtrLoc, "store operand must be a pointer"); 7224 if (!Val->getType()->isFirstClassType()) 7225 return error(Loc, "store operand must be a first class value"); 7226 if (!cast<PointerType>(Ptr->getType()) 7227 ->isOpaqueOrPointeeTypeMatches(Val->getType())) 7228 return error(Loc, "stored value and pointer type do not match"); 7229 if (isAtomic && !Alignment) 7230 return error(Loc, "atomic store must have explicit non-zero alignment"); 7231 if (Ordering == AtomicOrdering::Acquire || 7232 Ordering == AtomicOrdering::AcquireRelease) 7233 return error(Loc, "atomic store cannot use Acquire ordering"); 7234 SmallPtrSet<Type *, 4> Visited; 7235 if (!Alignment && !Val->getType()->isSized(&Visited)) 7236 return error(Loc, "storing unsized types is not allowed"); 7237 if (!Alignment) 7238 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 7239 7240 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 7241 return AteExtraComma ? InstExtraComma : InstNormal; 7242 } 7243 7244 /// parseCmpXchg 7245 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 7246 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ',' 7247 /// 'Align'? 7248 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 7249 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 7250 bool AteExtraComma = false; 7251 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 7252 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 7253 SyncScope::ID SSID = SyncScope::System; 7254 bool isVolatile = false; 7255 bool isWeak = false; 7256 MaybeAlign Alignment; 7257 7258 if (EatIfPresent(lltok::kw_weak)) 7259 isWeak = true; 7260 7261 if (EatIfPresent(lltok::kw_volatile)) 7262 isVolatile = true; 7263 7264 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7265 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 7266 parseTypeAndValue(Cmp, CmpLoc, PFS) || 7267 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 7268 parseTypeAndValue(New, NewLoc, PFS) || 7269 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 7270 parseOrdering(FailureOrdering) || 7271 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7272 return true; 7273 7274 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 7275 return tokError("invalid cmpxchg success ordering"); 7276 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 7277 return tokError("invalid cmpxchg failure ordering"); 7278 if (!Ptr->getType()->isPointerTy()) 7279 return error(PtrLoc, "cmpxchg operand must be a pointer"); 7280 if (!cast<PointerType>(Ptr->getType()) 7281 ->isOpaqueOrPointeeTypeMatches(Cmp->getType())) 7282 return error(CmpLoc, "compare value and pointer type do not match"); 7283 if (!cast<PointerType>(Ptr->getType()) 7284 ->isOpaqueOrPointeeTypeMatches(New->getType())) 7285 return error(NewLoc, "new value and pointer type do not match"); 7286 if (Cmp->getType() != New->getType()) 7287 return error(NewLoc, "compare value and new value type do not match"); 7288 if (!New->getType()->isFirstClassType()) 7289 return error(NewLoc, "cmpxchg operand must be a first class value"); 7290 7291 const Align DefaultAlignment( 7292 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7293 Cmp->getType())); 7294 7295 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst( 7296 Ptr, Cmp, New, Alignment.getValueOr(DefaultAlignment), SuccessOrdering, 7297 FailureOrdering, SSID); 7298 CXI->setVolatile(isVolatile); 7299 CXI->setWeak(isWeak); 7300 7301 Inst = CXI; 7302 return AteExtraComma ? InstExtraComma : InstNormal; 7303 } 7304 7305 /// parseAtomicRMW 7306 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 7307 /// 'singlethread'? AtomicOrdering 7308 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 7309 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 7310 bool AteExtraComma = false; 7311 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7312 SyncScope::ID SSID = SyncScope::System; 7313 bool isVolatile = false; 7314 bool IsFP = false; 7315 AtomicRMWInst::BinOp Operation; 7316 MaybeAlign Alignment; 7317 7318 if (EatIfPresent(lltok::kw_volatile)) 7319 isVolatile = true; 7320 7321 switch (Lex.getKind()) { 7322 default: 7323 return tokError("expected binary operation in atomicrmw"); 7324 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 7325 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 7326 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 7327 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 7328 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 7329 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 7330 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 7331 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 7332 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 7333 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 7334 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 7335 case lltok::kw_fadd: 7336 Operation = AtomicRMWInst::FAdd; 7337 IsFP = true; 7338 break; 7339 case lltok::kw_fsub: 7340 Operation = AtomicRMWInst::FSub; 7341 IsFP = true; 7342 break; 7343 } 7344 Lex.Lex(); // Eat the operation. 7345 7346 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 7347 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 7348 parseTypeAndValue(Val, ValLoc, PFS) || 7349 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) || 7350 parseOptionalCommaAlign(Alignment, AteExtraComma)) 7351 return true; 7352 7353 if (Ordering == AtomicOrdering::Unordered) 7354 return tokError("atomicrmw cannot be unordered"); 7355 if (!Ptr->getType()->isPointerTy()) 7356 return error(PtrLoc, "atomicrmw operand must be a pointer"); 7357 if (!cast<PointerType>(Ptr->getType()) 7358 ->isOpaqueOrPointeeTypeMatches(Val->getType())) 7359 return error(ValLoc, "atomicrmw value and pointer type do not match"); 7360 7361 if (Operation == AtomicRMWInst::Xchg) { 7362 if (!Val->getType()->isIntegerTy() && 7363 !Val->getType()->isFloatingPointTy()) { 7364 return error(ValLoc, 7365 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 7366 " operand must be an integer or floating point type"); 7367 } 7368 } else if (IsFP) { 7369 if (!Val->getType()->isFloatingPointTy()) { 7370 return error(ValLoc, "atomicrmw " + 7371 AtomicRMWInst::getOperationName(Operation) + 7372 " operand must be a floating point type"); 7373 } 7374 } else { 7375 if (!Val->getType()->isIntegerTy()) { 7376 return error(ValLoc, "atomicrmw " + 7377 AtomicRMWInst::getOperationName(Operation) + 7378 " operand must be an integer"); 7379 } 7380 } 7381 7382 unsigned Size = Val->getType()->getPrimitiveSizeInBits(); 7383 if (Size < 8 || (Size & (Size - 1))) 7384 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 7385 " integer"); 7386 const Align DefaultAlignment( 7387 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize( 7388 Val->getType())); 7389 AtomicRMWInst *RMWI = 7390 new AtomicRMWInst(Operation, Ptr, Val, 7391 Alignment.getValueOr(DefaultAlignment), Ordering, SSID); 7392 RMWI->setVolatile(isVolatile); 7393 Inst = RMWI; 7394 return AteExtraComma ? InstExtraComma : InstNormal; 7395 } 7396 7397 /// parseFence 7398 /// ::= 'fence' 'singlethread'? AtomicOrdering 7399 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 7400 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 7401 SyncScope::ID SSID = SyncScope::System; 7402 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 7403 return true; 7404 7405 if (Ordering == AtomicOrdering::Unordered) 7406 return tokError("fence cannot be unordered"); 7407 if (Ordering == AtomicOrdering::Monotonic) 7408 return tokError("fence cannot be monotonic"); 7409 7410 Inst = new FenceInst(Context, Ordering, SSID); 7411 return InstNormal; 7412 } 7413 7414 /// parseGetElementPtr 7415 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 7416 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 7417 Value *Ptr = nullptr; 7418 Value *Val = nullptr; 7419 LocTy Loc, EltLoc; 7420 7421 bool InBounds = EatIfPresent(lltok::kw_inbounds); 7422 7423 Type *Ty = nullptr; 7424 LocTy ExplicitTypeLoc = Lex.getLoc(); 7425 if (parseType(Ty) || 7426 parseToken(lltok::comma, "expected comma after getelementptr's type") || 7427 parseTypeAndValue(Ptr, Loc, PFS)) 7428 return true; 7429 7430 Type *BaseType = Ptr->getType(); 7431 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 7432 if (!BasePointerType) 7433 return error(Loc, "base of getelementptr must be a pointer"); 7434 7435 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) { 7436 return error( 7437 ExplicitTypeLoc, 7438 typeComparisonErrorMessage( 7439 "explicit pointee type doesn't match operand's pointee type", Ty, 7440 BasePointerType->getElementType())); 7441 } 7442 7443 SmallVector<Value*, 16> Indices; 7444 bool AteExtraComma = false; 7445 // GEP returns a vector of pointers if at least one of parameters is a vector. 7446 // All vector parameters should have the same vector width. 7447 ElementCount GEPWidth = BaseType->isVectorTy() 7448 ? cast<VectorType>(BaseType)->getElementCount() 7449 : ElementCount::getFixed(0); 7450 7451 while (EatIfPresent(lltok::comma)) { 7452 if (Lex.getKind() == lltok::MetadataVar) { 7453 AteExtraComma = true; 7454 break; 7455 } 7456 if (parseTypeAndValue(Val, EltLoc, PFS)) 7457 return true; 7458 if (!Val->getType()->isIntOrIntVectorTy()) 7459 return error(EltLoc, "getelementptr index must be an integer"); 7460 7461 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 7462 ElementCount ValNumEl = ValVTy->getElementCount(); 7463 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 7464 return error( 7465 EltLoc, 7466 "getelementptr vector index has a wrong number of elements"); 7467 GEPWidth = ValNumEl; 7468 } 7469 Indices.push_back(Val); 7470 } 7471 7472 SmallPtrSet<Type*, 4> Visited; 7473 if (!Indices.empty() && !Ty->isSized(&Visited)) 7474 return error(Loc, "base element of getelementptr must be sized"); 7475 7476 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 7477 return error(Loc, "invalid getelementptr indices"); 7478 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices); 7479 if (InBounds) 7480 cast<GetElementPtrInst>(Inst)->setIsInBounds(true); 7481 return AteExtraComma ? InstExtraComma : InstNormal; 7482 } 7483 7484 /// parseExtractValue 7485 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 7486 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 7487 Value *Val; LocTy Loc; 7488 SmallVector<unsigned, 4> Indices; 7489 bool AteExtraComma; 7490 if (parseTypeAndValue(Val, Loc, PFS) || 7491 parseIndexList(Indices, AteExtraComma)) 7492 return true; 7493 7494 if (!Val->getType()->isAggregateType()) 7495 return error(Loc, "extractvalue operand must be aggregate type"); 7496 7497 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 7498 return error(Loc, "invalid indices for extractvalue"); 7499 Inst = ExtractValueInst::Create(Val, Indices); 7500 return AteExtraComma ? InstExtraComma : InstNormal; 7501 } 7502 7503 /// parseInsertValue 7504 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 7505 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 7506 Value *Val0, *Val1; LocTy Loc0, Loc1; 7507 SmallVector<unsigned, 4> Indices; 7508 bool AteExtraComma; 7509 if (parseTypeAndValue(Val0, Loc0, PFS) || 7510 parseToken(lltok::comma, "expected comma after insertvalue operand") || 7511 parseTypeAndValue(Val1, Loc1, PFS) || 7512 parseIndexList(Indices, AteExtraComma)) 7513 return true; 7514 7515 if (!Val0->getType()->isAggregateType()) 7516 return error(Loc0, "insertvalue operand must be aggregate type"); 7517 7518 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 7519 if (!IndexedType) 7520 return error(Loc0, "invalid indices for insertvalue"); 7521 if (IndexedType != Val1->getType()) 7522 return error(Loc1, "insertvalue operand and field disagree in type: '" + 7523 getTypeString(Val1->getType()) + "' instead of '" + 7524 getTypeString(IndexedType) + "'"); 7525 Inst = InsertValueInst::Create(Val0, Val1, Indices); 7526 return AteExtraComma ? InstExtraComma : InstNormal; 7527 } 7528 7529 //===----------------------------------------------------------------------===// 7530 // Embedded metadata. 7531 //===----------------------------------------------------------------------===// 7532 7533 /// parseMDNodeVector 7534 /// ::= { Element (',' Element)* } 7535 /// Element 7536 /// ::= 'null' | TypeAndValue 7537 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 7538 if (parseToken(lltok::lbrace, "expected '{' here")) 7539 return true; 7540 7541 // Check for an empty list. 7542 if (EatIfPresent(lltok::rbrace)) 7543 return false; 7544 7545 do { 7546 // Null is a special case since it is typeless. 7547 if (EatIfPresent(lltok::kw_null)) { 7548 Elts.push_back(nullptr); 7549 continue; 7550 } 7551 7552 Metadata *MD; 7553 if (parseMetadata(MD, nullptr)) 7554 return true; 7555 Elts.push_back(MD); 7556 } while (EatIfPresent(lltok::comma)); 7557 7558 return parseToken(lltok::rbrace, "expected end of metadata node"); 7559 } 7560 7561 //===----------------------------------------------------------------------===// 7562 // Use-list order directives. 7563 //===----------------------------------------------------------------------===// 7564 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 7565 SMLoc Loc) { 7566 if (V->use_empty()) 7567 return error(Loc, "value has no uses"); 7568 7569 unsigned NumUses = 0; 7570 SmallDenseMap<const Use *, unsigned, 16> Order; 7571 for (const Use &U : V->uses()) { 7572 if (++NumUses > Indexes.size()) 7573 break; 7574 Order[&U] = Indexes[NumUses - 1]; 7575 } 7576 if (NumUses < 2) 7577 return error(Loc, "value only has one use"); 7578 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 7579 return error(Loc, 7580 "wrong number of indexes, expected " + Twine(V->getNumUses())); 7581 7582 V->sortUseList([&](const Use &L, const Use &R) { 7583 return Order.lookup(&L) < Order.lookup(&R); 7584 }); 7585 return false; 7586 } 7587 7588 /// parseUseListOrderIndexes 7589 /// ::= '{' uint32 (',' uint32)+ '}' 7590 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 7591 SMLoc Loc = Lex.getLoc(); 7592 if (parseToken(lltok::lbrace, "expected '{' here")) 7593 return true; 7594 if (Lex.getKind() == lltok::rbrace) 7595 return Lex.Error("expected non-empty list of uselistorder indexes"); 7596 7597 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 7598 // indexes should be distinct numbers in the range [0, size-1], and should 7599 // not be in order. 7600 unsigned Offset = 0; 7601 unsigned Max = 0; 7602 bool IsOrdered = true; 7603 assert(Indexes.empty() && "Expected empty order vector"); 7604 do { 7605 unsigned Index; 7606 if (parseUInt32(Index)) 7607 return true; 7608 7609 // Update consistency checks. 7610 Offset += Index - Indexes.size(); 7611 Max = std::max(Max, Index); 7612 IsOrdered &= Index == Indexes.size(); 7613 7614 Indexes.push_back(Index); 7615 } while (EatIfPresent(lltok::comma)); 7616 7617 if (parseToken(lltok::rbrace, "expected '}' here")) 7618 return true; 7619 7620 if (Indexes.size() < 2) 7621 return error(Loc, "expected >= 2 uselistorder indexes"); 7622 if (Offset != 0 || Max >= Indexes.size()) 7623 return error(Loc, 7624 "expected distinct uselistorder indexes in range [0, size)"); 7625 if (IsOrdered) 7626 return error(Loc, "expected uselistorder indexes to change the order"); 7627 7628 return false; 7629 } 7630 7631 /// parseUseListOrder 7632 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 7633 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 7634 SMLoc Loc = Lex.getLoc(); 7635 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 7636 return true; 7637 7638 Value *V; 7639 SmallVector<unsigned, 16> Indexes; 7640 if (parseTypeAndValue(V, PFS) || 7641 parseToken(lltok::comma, "expected comma in uselistorder directive") || 7642 parseUseListOrderIndexes(Indexes)) 7643 return true; 7644 7645 return sortUseListOrder(V, Indexes, Loc); 7646 } 7647 7648 /// parseUseListOrderBB 7649 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 7650 bool LLParser::parseUseListOrderBB() { 7651 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 7652 SMLoc Loc = Lex.getLoc(); 7653 Lex.Lex(); 7654 7655 ValID Fn, Label; 7656 SmallVector<unsigned, 16> Indexes; 7657 if (parseValID(Fn, /*PFS=*/nullptr) || 7658 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7659 parseValID(Label, /*PFS=*/nullptr) || 7660 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 7661 parseUseListOrderIndexes(Indexes)) 7662 return true; 7663 7664 // Check the function. 7665 GlobalValue *GV; 7666 if (Fn.Kind == ValID::t_GlobalName) 7667 GV = M->getNamedValue(Fn.StrVal); 7668 else if (Fn.Kind == ValID::t_GlobalID) 7669 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr; 7670 else 7671 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7672 if (!GV) 7673 return error(Fn.Loc, 7674 "invalid function forward reference in uselistorder_bb"); 7675 auto *F = dyn_cast<Function>(GV); 7676 if (!F) 7677 return error(Fn.Loc, "expected function name in uselistorder_bb"); 7678 if (F->isDeclaration()) 7679 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 7680 7681 // Check the basic block. 7682 if (Label.Kind == ValID::t_LocalID) 7683 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 7684 if (Label.Kind != ValID::t_LocalName) 7685 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 7686 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 7687 if (!V) 7688 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 7689 if (!isa<BasicBlock>(V)) 7690 return error(Label.Loc, "expected basic block in uselistorder_bb"); 7691 7692 return sortUseListOrder(V, Indexes, Loc); 7693 } 7694 7695 /// ModuleEntry 7696 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 7697 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 7698 bool LLParser::parseModuleEntry(unsigned ID) { 7699 assert(Lex.getKind() == lltok::kw_module); 7700 Lex.Lex(); 7701 7702 std::string Path; 7703 if (parseToken(lltok::colon, "expected ':' here") || 7704 parseToken(lltok::lparen, "expected '(' here") || 7705 parseToken(lltok::kw_path, "expected 'path' here") || 7706 parseToken(lltok::colon, "expected ':' here") || 7707 parseStringConstant(Path) || 7708 parseToken(lltok::comma, "expected ',' here") || 7709 parseToken(lltok::kw_hash, "expected 'hash' here") || 7710 parseToken(lltok::colon, "expected ':' here") || 7711 parseToken(lltok::lparen, "expected '(' here")) 7712 return true; 7713 7714 ModuleHash Hash; 7715 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 7716 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 7717 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 7718 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 7719 parseUInt32(Hash[4])) 7720 return true; 7721 7722 if (parseToken(lltok::rparen, "expected ')' here") || 7723 parseToken(lltok::rparen, "expected ')' here")) 7724 return true; 7725 7726 auto ModuleEntry = Index->addModule(Path, ID, Hash); 7727 ModuleIdMap[ID] = ModuleEntry->first(); 7728 7729 return false; 7730 } 7731 7732 /// TypeIdEntry 7733 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 7734 bool LLParser::parseTypeIdEntry(unsigned ID) { 7735 assert(Lex.getKind() == lltok::kw_typeid); 7736 Lex.Lex(); 7737 7738 std::string Name; 7739 if (parseToken(lltok::colon, "expected ':' here") || 7740 parseToken(lltok::lparen, "expected '(' here") || 7741 parseToken(lltok::kw_name, "expected 'name' here") || 7742 parseToken(lltok::colon, "expected ':' here") || 7743 parseStringConstant(Name)) 7744 return true; 7745 7746 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 7747 if (parseToken(lltok::comma, "expected ',' here") || 7748 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 7749 return true; 7750 7751 // Check if this ID was forward referenced, and if so, update the 7752 // corresponding GUIDs. 7753 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7754 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7755 for (auto TIDRef : FwdRefTIDs->second) { 7756 assert(!*TIDRef.first && 7757 "Forward referenced type id GUID expected to be 0"); 7758 *TIDRef.first = GlobalValue::getGUID(Name); 7759 } 7760 ForwardRefTypeIds.erase(FwdRefTIDs); 7761 } 7762 7763 return false; 7764 } 7765 7766 /// TypeIdSummary 7767 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 7768 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 7769 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 7770 parseToken(lltok::colon, "expected ':' here") || 7771 parseToken(lltok::lparen, "expected '(' here") || 7772 parseTypeTestResolution(TIS.TTRes)) 7773 return true; 7774 7775 if (EatIfPresent(lltok::comma)) { 7776 // Expect optional wpdResolutions field 7777 if (parseOptionalWpdResolutions(TIS.WPDRes)) 7778 return true; 7779 } 7780 7781 if (parseToken(lltok::rparen, "expected ')' here")) 7782 return true; 7783 7784 return false; 7785 } 7786 7787 static ValueInfo EmptyVI = 7788 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 7789 7790 /// TypeIdCompatibleVtableEntry 7791 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 7792 /// TypeIdCompatibleVtableInfo 7793 /// ')' 7794 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 7795 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 7796 Lex.Lex(); 7797 7798 std::string Name; 7799 if (parseToken(lltok::colon, "expected ':' here") || 7800 parseToken(lltok::lparen, "expected '(' here") || 7801 parseToken(lltok::kw_name, "expected 'name' here") || 7802 parseToken(lltok::colon, "expected ':' here") || 7803 parseStringConstant(Name)) 7804 return true; 7805 7806 TypeIdCompatibleVtableInfo &TI = 7807 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 7808 if (parseToken(lltok::comma, "expected ',' here") || 7809 parseToken(lltok::kw_summary, "expected 'summary' here") || 7810 parseToken(lltok::colon, "expected ':' here") || 7811 parseToken(lltok::lparen, "expected '(' here")) 7812 return true; 7813 7814 IdToIndexMapType IdToIndexMap; 7815 // parse each call edge 7816 do { 7817 uint64_t Offset; 7818 if (parseToken(lltok::lparen, "expected '(' here") || 7819 parseToken(lltok::kw_offset, "expected 'offset' here") || 7820 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 7821 parseToken(lltok::comma, "expected ',' here")) 7822 return true; 7823 7824 LocTy Loc = Lex.getLoc(); 7825 unsigned GVId; 7826 ValueInfo VI; 7827 if (parseGVReference(VI, GVId)) 7828 return true; 7829 7830 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 7831 // forward reference. We will save the location of the ValueInfo needing an 7832 // update, but can only do so once the std::vector is finalized. 7833 if (VI == EmptyVI) 7834 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 7835 TI.push_back({Offset, VI}); 7836 7837 if (parseToken(lltok::rparen, "expected ')' in call")) 7838 return true; 7839 } while (EatIfPresent(lltok::comma)); 7840 7841 // Now that the TI vector is finalized, it is safe to save the locations 7842 // of any forward GV references that need updating later. 7843 for (auto I : IdToIndexMap) { 7844 auto &Infos = ForwardRefValueInfos[I.first]; 7845 for (auto P : I.second) { 7846 assert(TI[P.first].VTableVI == EmptyVI && 7847 "Forward referenced ValueInfo expected to be empty"); 7848 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 7849 } 7850 } 7851 7852 if (parseToken(lltok::rparen, "expected ')' here") || 7853 parseToken(lltok::rparen, "expected ')' here")) 7854 return true; 7855 7856 // Check if this ID was forward referenced, and if so, update the 7857 // corresponding GUIDs. 7858 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 7859 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 7860 for (auto TIDRef : FwdRefTIDs->second) { 7861 assert(!*TIDRef.first && 7862 "Forward referenced type id GUID expected to be 0"); 7863 *TIDRef.first = GlobalValue::getGUID(Name); 7864 } 7865 ForwardRefTypeIds.erase(FwdRefTIDs); 7866 } 7867 7868 return false; 7869 } 7870 7871 /// TypeTestResolution 7872 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 7873 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 7874 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 7875 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 7876 /// [',' 'inlinesBits' ':' UInt64]? ')' 7877 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 7878 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 7879 parseToken(lltok::colon, "expected ':' here") || 7880 parseToken(lltok::lparen, "expected '(' here") || 7881 parseToken(lltok::kw_kind, "expected 'kind' here") || 7882 parseToken(lltok::colon, "expected ':' here")) 7883 return true; 7884 7885 switch (Lex.getKind()) { 7886 case lltok::kw_unknown: 7887 TTRes.TheKind = TypeTestResolution::Unknown; 7888 break; 7889 case lltok::kw_unsat: 7890 TTRes.TheKind = TypeTestResolution::Unsat; 7891 break; 7892 case lltok::kw_byteArray: 7893 TTRes.TheKind = TypeTestResolution::ByteArray; 7894 break; 7895 case lltok::kw_inline: 7896 TTRes.TheKind = TypeTestResolution::Inline; 7897 break; 7898 case lltok::kw_single: 7899 TTRes.TheKind = TypeTestResolution::Single; 7900 break; 7901 case lltok::kw_allOnes: 7902 TTRes.TheKind = TypeTestResolution::AllOnes; 7903 break; 7904 default: 7905 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 7906 } 7907 Lex.Lex(); 7908 7909 if (parseToken(lltok::comma, "expected ',' here") || 7910 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 7911 parseToken(lltok::colon, "expected ':' here") || 7912 parseUInt32(TTRes.SizeM1BitWidth)) 7913 return true; 7914 7915 // parse optional fields 7916 while (EatIfPresent(lltok::comma)) { 7917 switch (Lex.getKind()) { 7918 case lltok::kw_alignLog2: 7919 Lex.Lex(); 7920 if (parseToken(lltok::colon, "expected ':'") || 7921 parseUInt64(TTRes.AlignLog2)) 7922 return true; 7923 break; 7924 case lltok::kw_sizeM1: 7925 Lex.Lex(); 7926 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 7927 return true; 7928 break; 7929 case lltok::kw_bitMask: { 7930 unsigned Val; 7931 Lex.Lex(); 7932 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 7933 return true; 7934 assert(Val <= 0xff); 7935 TTRes.BitMask = (uint8_t)Val; 7936 break; 7937 } 7938 case lltok::kw_inlineBits: 7939 Lex.Lex(); 7940 if (parseToken(lltok::colon, "expected ':'") || 7941 parseUInt64(TTRes.InlineBits)) 7942 return true; 7943 break; 7944 default: 7945 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 7946 } 7947 } 7948 7949 if (parseToken(lltok::rparen, "expected ')' here")) 7950 return true; 7951 7952 return false; 7953 } 7954 7955 /// OptionalWpdResolutions 7956 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 7957 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 7958 bool LLParser::parseOptionalWpdResolutions( 7959 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 7960 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 7961 parseToken(lltok::colon, "expected ':' here") || 7962 parseToken(lltok::lparen, "expected '(' here")) 7963 return true; 7964 7965 do { 7966 uint64_t Offset; 7967 WholeProgramDevirtResolution WPDRes; 7968 if (parseToken(lltok::lparen, "expected '(' here") || 7969 parseToken(lltok::kw_offset, "expected 'offset' here") || 7970 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 7971 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 7972 parseToken(lltok::rparen, "expected ')' here")) 7973 return true; 7974 WPDResMap[Offset] = WPDRes; 7975 } while (EatIfPresent(lltok::comma)); 7976 7977 if (parseToken(lltok::rparen, "expected ')' here")) 7978 return true; 7979 7980 return false; 7981 } 7982 7983 /// WpdRes 7984 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 7985 /// [',' OptionalResByArg]? ')' 7986 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 7987 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 7988 /// [',' OptionalResByArg]? ')' 7989 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 7990 /// [',' OptionalResByArg]? ')' 7991 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 7992 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 7993 parseToken(lltok::colon, "expected ':' here") || 7994 parseToken(lltok::lparen, "expected '(' here") || 7995 parseToken(lltok::kw_kind, "expected 'kind' here") || 7996 parseToken(lltok::colon, "expected ':' here")) 7997 return true; 7998 7999 switch (Lex.getKind()) { 8000 case lltok::kw_indir: 8001 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 8002 break; 8003 case lltok::kw_singleImpl: 8004 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 8005 break; 8006 case lltok::kw_branchFunnel: 8007 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 8008 break; 8009 default: 8010 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 8011 } 8012 Lex.Lex(); 8013 8014 // parse optional fields 8015 while (EatIfPresent(lltok::comma)) { 8016 switch (Lex.getKind()) { 8017 case lltok::kw_singleImplName: 8018 Lex.Lex(); 8019 if (parseToken(lltok::colon, "expected ':' here") || 8020 parseStringConstant(WPDRes.SingleImplName)) 8021 return true; 8022 break; 8023 case lltok::kw_resByArg: 8024 if (parseOptionalResByArg(WPDRes.ResByArg)) 8025 return true; 8026 break; 8027 default: 8028 return error(Lex.getLoc(), 8029 "expected optional WholeProgramDevirtResolution field"); 8030 } 8031 } 8032 8033 if (parseToken(lltok::rparen, "expected ')' here")) 8034 return true; 8035 8036 return false; 8037 } 8038 8039 /// OptionalResByArg 8040 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 8041 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 8042 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 8043 /// 'virtualConstProp' ) 8044 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 8045 /// [',' 'bit' ':' UInt32]? ')' 8046 bool LLParser::parseOptionalResByArg( 8047 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 8048 &ResByArg) { 8049 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 8050 parseToken(lltok::colon, "expected ':' here") || 8051 parseToken(lltok::lparen, "expected '(' here")) 8052 return true; 8053 8054 do { 8055 std::vector<uint64_t> Args; 8056 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 8057 parseToken(lltok::kw_byArg, "expected 'byArg here") || 8058 parseToken(lltok::colon, "expected ':' here") || 8059 parseToken(lltok::lparen, "expected '(' here") || 8060 parseToken(lltok::kw_kind, "expected 'kind' here") || 8061 parseToken(lltok::colon, "expected ':' here")) 8062 return true; 8063 8064 WholeProgramDevirtResolution::ByArg ByArg; 8065 switch (Lex.getKind()) { 8066 case lltok::kw_indir: 8067 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 8068 break; 8069 case lltok::kw_uniformRetVal: 8070 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 8071 break; 8072 case lltok::kw_uniqueRetVal: 8073 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 8074 break; 8075 case lltok::kw_virtualConstProp: 8076 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 8077 break; 8078 default: 8079 return error(Lex.getLoc(), 8080 "unexpected WholeProgramDevirtResolution::ByArg kind"); 8081 } 8082 Lex.Lex(); 8083 8084 // parse optional fields 8085 while (EatIfPresent(lltok::comma)) { 8086 switch (Lex.getKind()) { 8087 case lltok::kw_info: 8088 Lex.Lex(); 8089 if (parseToken(lltok::colon, "expected ':' here") || 8090 parseUInt64(ByArg.Info)) 8091 return true; 8092 break; 8093 case lltok::kw_byte: 8094 Lex.Lex(); 8095 if (parseToken(lltok::colon, "expected ':' here") || 8096 parseUInt32(ByArg.Byte)) 8097 return true; 8098 break; 8099 case lltok::kw_bit: 8100 Lex.Lex(); 8101 if (parseToken(lltok::colon, "expected ':' here") || 8102 parseUInt32(ByArg.Bit)) 8103 return true; 8104 break; 8105 default: 8106 return error(Lex.getLoc(), 8107 "expected optional whole program devirt field"); 8108 } 8109 } 8110 8111 if (parseToken(lltok::rparen, "expected ')' here")) 8112 return true; 8113 8114 ResByArg[Args] = ByArg; 8115 } while (EatIfPresent(lltok::comma)); 8116 8117 if (parseToken(lltok::rparen, "expected ')' here")) 8118 return true; 8119 8120 return false; 8121 } 8122 8123 /// OptionalResByArg 8124 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 8125 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 8126 if (parseToken(lltok::kw_args, "expected 'args' here") || 8127 parseToken(lltok::colon, "expected ':' here") || 8128 parseToken(lltok::lparen, "expected '(' here")) 8129 return true; 8130 8131 do { 8132 uint64_t Val; 8133 if (parseUInt64(Val)) 8134 return true; 8135 Args.push_back(Val); 8136 } while (EatIfPresent(lltok::comma)); 8137 8138 if (parseToken(lltok::rparen, "expected ')' here")) 8139 return true; 8140 8141 return false; 8142 } 8143 8144 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 8145 8146 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 8147 bool ReadOnly = Fwd->isReadOnly(); 8148 bool WriteOnly = Fwd->isWriteOnly(); 8149 assert(!(ReadOnly && WriteOnly)); 8150 *Fwd = Resolved; 8151 if (ReadOnly) 8152 Fwd->setReadOnly(); 8153 if (WriteOnly) 8154 Fwd->setWriteOnly(); 8155 } 8156 8157 /// Stores the given Name/GUID and associated summary into the Index. 8158 /// Also updates any forward references to the associated entry ID. 8159 void LLParser::addGlobalValueToIndex( 8160 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 8161 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) { 8162 // First create the ValueInfo utilizing the Name or GUID. 8163 ValueInfo VI; 8164 if (GUID != 0) { 8165 assert(Name.empty()); 8166 VI = Index->getOrInsertValueInfo(GUID); 8167 } else { 8168 assert(!Name.empty()); 8169 if (M) { 8170 auto *GV = M->getNamedValue(Name); 8171 assert(GV); 8172 VI = Index->getOrInsertValueInfo(GV); 8173 } else { 8174 assert( 8175 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 8176 "Need a source_filename to compute GUID for local"); 8177 GUID = GlobalValue::getGUID( 8178 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 8179 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 8180 } 8181 } 8182 8183 // Resolve forward references from calls/refs 8184 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 8185 if (FwdRefVIs != ForwardRefValueInfos.end()) { 8186 for (auto VIRef : FwdRefVIs->second) { 8187 assert(VIRef.first->getRef() == FwdVIRef && 8188 "Forward referenced ValueInfo expected to be empty"); 8189 resolveFwdRef(VIRef.first, VI); 8190 } 8191 ForwardRefValueInfos.erase(FwdRefVIs); 8192 } 8193 8194 // Resolve forward references from aliases 8195 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 8196 if (FwdRefAliasees != ForwardRefAliasees.end()) { 8197 for (auto AliaseeRef : FwdRefAliasees->second) { 8198 assert(!AliaseeRef.first->hasAliasee() && 8199 "Forward referencing alias already has aliasee"); 8200 assert(Summary && "Aliasee must be a definition"); 8201 AliaseeRef.first->setAliasee(VI, Summary.get()); 8202 } 8203 ForwardRefAliasees.erase(FwdRefAliasees); 8204 } 8205 8206 // Add the summary if one was provided. 8207 if (Summary) 8208 Index->addGlobalValueSummary(VI, std::move(Summary)); 8209 8210 // Save the associated ValueInfo for use in later references by ID. 8211 if (ID == NumberedValueInfos.size()) 8212 NumberedValueInfos.push_back(VI); 8213 else { 8214 // Handle non-continuous numbers (to make test simplification easier). 8215 if (ID > NumberedValueInfos.size()) 8216 NumberedValueInfos.resize(ID + 1); 8217 NumberedValueInfos[ID] = VI; 8218 } 8219 } 8220 8221 /// parseSummaryIndexFlags 8222 /// ::= 'flags' ':' UInt64 8223 bool LLParser::parseSummaryIndexFlags() { 8224 assert(Lex.getKind() == lltok::kw_flags); 8225 Lex.Lex(); 8226 8227 if (parseToken(lltok::colon, "expected ':' here")) 8228 return true; 8229 uint64_t Flags; 8230 if (parseUInt64(Flags)) 8231 return true; 8232 if (Index) 8233 Index->setFlags(Flags); 8234 return false; 8235 } 8236 8237 /// parseBlockCount 8238 /// ::= 'blockcount' ':' UInt64 8239 bool LLParser::parseBlockCount() { 8240 assert(Lex.getKind() == lltok::kw_blockcount); 8241 Lex.Lex(); 8242 8243 if (parseToken(lltok::colon, "expected ':' here")) 8244 return true; 8245 uint64_t BlockCount; 8246 if (parseUInt64(BlockCount)) 8247 return true; 8248 if (Index) 8249 Index->setBlockCount(BlockCount); 8250 return false; 8251 } 8252 8253 /// parseGVEntry 8254 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 8255 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 8256 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 8257 bool LLParser::parseGVEntry(unsigned ID) { 8258 assert(Lex.getKind() == lltok::kw_gv); 8259 Lex.Lex(); 8260 8261 if (parseToken(lltok::colon, "expected ':' here") || 8262 parseToken(lltok::lparen, "expected '(' here")) 8263 return true; 8264 8265 std::string Name; 8266 GlobalValue::GUID GUID = 0; 8267 switch (Lex.getKind()) { 8268 case lltok::kw_name: 8269 Lex.Lex(); 8270 if (parseToken(lltok::colon, "expected ':' here") || 8271 parseStringConstant(Name)) 8272 return true; 8273 // Can't create GUID/ValueInfo until we have the linkage. 8274 break; 8275 case lltok::kw_guid: 8276 Lex.Lex(); 8277 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 8278 return true; 8279 break; 8280 default: 8281 return error(Lex.getLoc(), "expected name or guid tag"); 8282 } 8283 8284 if (!EatIfPresent(lltok::comma)) { 8285 // No summaries. Wrap up. 8286 if (parseToken(lltok::rparen, "expected ')' here")) 8287 return true; 8288 // This was created for a call to an external or indirect target. 8289 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 8290 // created for indirect calls with VP. A Name with no GUID came from 8291 // an external definition. We pass ExternalLinkage since that is only 8292 // used when the GUID must be computed from Name, and in that case 8293 // the symbol must have external linkage. 8294 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 8295 nullptr); 8296 return false; 8297 } 8298 8299 // Have a list of summaries 8300 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 8301 parseToken(lltok::colon, "expected ':' here") || 8302 parseToken(lltok::lparen, "expected '(' here")) 8303 return true; 8304 do { 8305 switch (Lex.getKind()) { 8306 case lltok::kw_function: 8307 if (parseFunctionSummary(Name, GUID, ID)) 8308 return true; 8309 break; 8310 case lltok::kw_variable: 8311 if (parseVariableSummary(Name, GUID, ID)) 8312 return true; 8313 break; 8314 case lltok::kw_alias: 8315 if (parseAliasSummary(Name, GUID, ID)) 8316 return true; 8317 break; 8318 default: 8319 return error(Lex.getLoc(), "expected summary type"); 8320 } 8321 } while (EatIfPresent(lltok::comma)); 8322 8323 if (parseToken(lltok::rparen, "expected ')' here") || 8324 parseToken(lltok::rparen, "expected ')' here")) 8325 return true; 8326 8327 return false; 8328 } 8329 8330 /// FunctionSummary 8331 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8332 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 8333 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 8334 /// [',' OptionalRefs]? ')' 8335 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 8336 unsigned ID) { 8337 assert(Lex.getKind() == lltok::kw_function); 8338 Lex.Lex(); 8339 8340 StringRef ModulePath; 8341 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8342 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8343 /*NotEligibleToImport=*/false, 8344 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8345 unsigned InstCount; 8346 std::vector<FunctionSummary::EdgeTy> Calls; 8347 FunctionSummary::TypeIdInfo TypeIdInfo; 8348 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 8349 std::vector<ValueInfo> Refs; 8350 // Default is all-zeros (conservative values). 8351 FunctionSummary::FFlags FFlags = {}; 8352 if (parseToken(lltok::colon, "expected ':' here") || 8353 parseToken(lltok::lparen, "expected '(' here") || 8354 parseModuleReference(ModulePath) || 8355 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8356 parseToken(lltok::comma, "expected ',' here") || 8357 parseToken(lltok::kw_insts, "expected 'insts' here") || 8358 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 8359 return true; 8360 8361 // parse optional fields 8362 while (EatIfPresent(lltok::comma)) { 8363 switch (Lex.getKind()) { 8364 case lltok::kw_funcFlags: 8365 if (parseOptionalFFlags(FFlags)) 8366 return true; 8367 break; 8368 case lltok::kw_calls: 8369 if (parseOptionalCalls(Calls)) 8370 return true; 8371 break; 8372 case lltok::kw_typeIdInfo: 8373 if (parseOptionalTypeIdInfo(TypeIdInfo)) 8374 return true; 8375 break; 8376 case lltok::kw_refs: 8377 if (parseOptionalRefs(Refs)) 8378 return true; 8379 break; 8380 case lltok::kw_params: 8381 if (parseOptionalParamAccesses(ParamAccesses)) 8382 return true; 8383 break; 8384 default: 8385 return error(Lex.getLoc(), "expected optional function summary field"); 8386 } 8387 } 8388 8389 if (parseToken(lltok::rparen, "expected ')' here")) 8390 return true; 8391 8392 auto FS = std::make_unique<FunctionSummary>( 8393 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs), 8394 std::move(Calls), std::move(TypeIdInfo.TypeTests), 8395 std::move(TypeIdInfo.TypeTestAssumeVCalls), 8396 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 8397 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 8398 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 8399 std::move(ParamAccesses)); 8400 8401 FS->setModulePath(ModulePath); 8402 8403 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8404 ID, std::move(FS)); 8405 8406 return false; 8407 } 8408 8409 /// VariableSummary 8410 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 8411 /// [',' OptionalRefs]? ')' 8412 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 8413 unsigned ID) { 8414 assert(Lex.getKind() == lltok::kw_variable); 8415 Lex.Lex(); 8416 8417 StringRef ModulePath; 8418 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8419 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8420 /*NotEligibleToImport=*/false, 8421 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8422 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 8423 /* WriteOnly */ false, 8424 /* Constant */ false, 8425 GlobalObject::VCallVisibilityPublic); 8426 std::vector<ValueInfo> Refs; 8427 VTableFuncList VTableFuncs; 8428 if (parseToken(lltok::colon, "expected ':' here") || 8429 parseToken(lltok::lparen, "expected '(' here") || 8430 parseModuleReference(ModulePath) || 8431 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8432 parseToken(lltok::comma, "expected ',' here") || 8433 parseGVarFlags(GVarFlags)) 8434 return true; 8435 8436 // parse optional fields 8437 while (EatIfPresent(lltok::comma)) { 8438 switch (Lex.getKind()) { 8439 case lltok::kw_vTableFuncs: 8440 if (parseOptionalVTableFuncs(VTableFuncs)) 8441 return true; 8442 break; 8443 case lltok::kw_refs: 8444 if (parseOptionalRefs(Refs)) 8445 return true; 8446 break; 8447 default: 8448 return error(Lex.getLoc(), "expected optional variable summary field"); 8449 } 8450 } 8451 8452 if (parseToken(lltok::rparen, "expected ')' here")) 8453 return true; 8454 8455 auto GS = 8456 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 8457 8458 GS->setModulePath(ModulePath); 8459 GS->setVTableFuncs(std::move(VTableFuncs)); 8460 8461 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8462 ID, std::move(GS)); 8463 8464 return false; 8465 } 8466 8467 /// AliasSummary 8468 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 8469 /// 'aliasee' ':' GVReference ')' 8470 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 8471 unsigned ID) { 8472 assert(Lex.getKind() == lltok::kw_alias); 8473 LocTy Loc = Lex.getLoc(); 8474 Lex.Lex(); 8475 8476 StringRef ModulePath; 8477 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 8478 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 8479 /*NotEligibleToImport=*/false, 8480 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false); 8481 if (parseToken(lltok::colon, "expected ':' here") || 8482 parseToken(lltok::lparen, "expected '(' here") || 8483 parseModuleReference(ModulePath) || 8484 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 8485 parseToken(lltok::comma, "expected ',' here") || 8486 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 8487 parseToken(lltok::colon, "expected ':' here")) 8488 return true; 8489 8490 ValueInfo AliaseeVI; 8491 unsigned GVId; 8492 if (parseGVReference(AliaseeVI, GVId)) 8493 return true; 8494 8495 if (parseToken(lltok::rparen, "expected ')' here")) 8496 return true; 8497 8498 auto AS = std::make_unique<AliasSummary>(GVFlags); 8499 8500 AS->setModulePath(ModulePath); 8501 8502 // Record forward reference if the aliasee is not parsed yet. 8503 if (AliaseeVI.getRef() == FwdVIRef) { 8504 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 8505 } else { 8506 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 8507 assert(Summary && "Aliasee must be a definition"); 8508 AS->setAliasee(AliaseeVI, Summary); 8509 } 8510 8511 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage, 8512 ID, std::move(AS)); 8513 8514 return false; 8515 } 8516 8517 /// Flag 8518 /// ::= [0|1] 8519 bool LLParser::parseFlag(unsigned &Val) { 8520 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 8521 return tokError("expected integer"); 8522 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 8523 Lex.Lex(); 8524 return false; 8525 } 8526 8527 /// OptionalFFlags 8528 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 8529 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 8530 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 8531 /// [',' 'noInline' ':' Flag]? ')' 8532 /// [',' 'alwaysInline' ':' Flag]? ')' 8533 /// [',' 'noUnwind' ':' Flag]? ')' 8534 /// [',' 'mayThrow' ':' Flag]? ')' 8535 /// [',' 'hasUnknownCall' ':' Flag]? ')' 8536 8537 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 8538 assert(Lex.getKind() == lltok::kw_funcFlags); 8539 Lex.Lex(); 8540 8541 if (parseToken(lltok::colon, "expected ':' in funcFlags") || 8542 parseToken(lltok::lparen, "expected '(' in funcFlags")) 8543 return true; 8544 8545 do { 8546 unsigned Val = 0; 8547 switch (Lex.getKind()) { 8548 case lltok::kw_readNone: 8549 Lex.Lex(); 8550 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8551 return true; 8552 FFlags.ReadNone = Val; 8553 break; 8554 case lltok::kw_readOnly: 8555 Lex.Lex(); 8556 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8557 return true; 8558 FFlags.ReadOnly = Val; 8559 break; 8560 case lltok::kw_noRecurse: 8561 Lex.Lex(); 8562 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8563 return true; 8564 FFlags.NoRecurse = Val; 8565 break; 8566 case lltok::kw_returnDoesNotAlias: 8567 Lex.Lex(); 8568 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8569 return true; 8570 FFlags.ReturnDoesNotAlias = Val; 8571 break; 8572 case lltok::kw_noInline: 8573 Lex.Lex(); 8574 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8575 return true; 8576 FFlags.NoInline = Val; 8577 break; 8578 case lltok::kw_alwaysInline: 8579 Lex.Lex(); 8580 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8581 return true; 8582 FFlags.AlwaysInline = Val; 8583 break; 8584 case lltok::kw_noUnwind: 8585 Lex.Lex(); 8586 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8587 return true; 8588 FFlags.NoUnwind = Val; 8589 break; 8590 case lltok::kw_mayThrow: 8591 Lex.Lex(); 8592 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8593 return true; 8594 FFlags.MayThrow = Val; 8595 break; 8596 case lltok::kw_hasUnknownCall: 8597 Lex.Lex(); 8598 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 8599 return true; 8600 FFlags.HasUnknownCall = Val; 8601 break; 8602 default: 8603 return error(Lex.getLoc(), "expected function flag type"); 8604 } 8605 } while (EatIfPresent(lltok::comma)); 8606 8607 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 8608 return true; 8609 8610 return false; 8611 } 8612 8613 /// OptionalCalls 8614 /// := 'calls' ':' '(' Call [',' Call]* ')' 8615 /// Call ::= '(' 'callee' ':' GVReference 8616 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')' 8617 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) { 8618 assert(Lex.getKind() == lltok::kw_calls); 8619 Lex.Lex(); 8620 8621 if (parseToken(lltok::colon, "expected ':' in calls") || 8622 parseToken(lltok::lparen, "expected '(' in calls")) 8623 return true; 8624 8625 IdToIndexMapType IdToIndexMap; 8626 // parse each call edge 8627 do { 8628 ValueInfo VI; 8629 if (parseToken(lltok::lparen, "expected '(' in call") || 8630 parseToken(lltok::kw_callee, "expected 'callee' in call") || 8631 parseToken(lltok::colon, "expected ':'")) 8632 return true; 8633 8634 LocTy Loc = Lex.getLoc(); 8635 unsigned GVId; 8636 if (parseGVReference(VI, GVId)) 8637 return true; 8638 8639 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 8640 unsigned RelBF = 0; 8641 if (EatIfPresent(lltok::comma)) { 8642 // Expect either hotness or relbf 8643 if (EatIfPresent(lltok::kw_hotness)) { 8644 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 8645 return true; 8646 } else { 8647 if (parseToken(lltok::kw_relbf, "expected relbf") || 8648 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 8649 return true; 8650 } 8651 } 8652 // Keep track of the Call array index needing a forward reference. 8653 // We will save the location of the ValueInfo needing an update, but 8654 // can only do so once the std::vector is finalized. 8655 if (VI.getRef() == FwdVIRef) 8656 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 8657 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)}); 8658 8659 if (parseToken(lltok::rparen, "expected ')' in call")) 8660 return true; 8661 } while (EatIfPresent(lltok::comma)); 8662 8663 // Now that the Calls vector is finalized, it is safe to save the locations 8664 // of any forward GV references that need updating later. 8665 for (auto I : IdToIndexMap) { 8666 auto &Infos = ForwardRefValueInfos[I.first]; 8667 for (auto P : I.second) { 8668 assert(Calls[P.first].first.getRef() == FwdVIRef && 8669 "Forward referenced ValueInfo expected to be empty"); 8670 Infos.emplace_back(&Calls[P.first].first, P.second); 8671 } 8672 } 8673 8674 if (parseToken(lltok::rparen, "expected ')' in calls")) 8675 return true; 8676 8677 return false; 8678 } 8679 8680 /// Hotness 8681 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 8682 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 8683 switch (Lex.getKind()) { 8684 case lltok::kw_unknown: 8685 Hotness = CalleeInfo::HotnessType::Unknown; 8686 break; 8687 case lltok::kw_cold: 8688 Hotness = CalleeInfo::HotnessType::Cold; 8689 break; 8690 case lltok::kw_none: 8691 Hotness = CalleeInfo::HotnessType::None; 8692 break; 8693 case lltok::kw_hot: 8694 Hotness = CalleeInfo::HotnessType::Hot; 8695 break; 8696 case lltok::kw_critical: 8697 Hotness = CalleeInfo::HotnessType::Critical; 8698 break; 8699 default: 8700 return error(Lex.getLoc(), "invalid call edge hotness"); 8701 } 8702 Lex.Lex(); 8703 return false; 8704 } 8705 8706 /// OptionalVTableFuncs 8707 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 8708 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 8709 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 8710 assert(Lex.getKind() == lltok::kw_vTableFuncs); 8711 Lex.Lex(); 8712 8713 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") || 8714 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 8715 return true; 8716 8717 IdToIndexMapType IdToIndexMap; 8718 // parse each virtual function pair 8719 do { 8720 ValueInfo VI; 8721 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 8722 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 8723 parseToken(lltok::colon, "expected ':'")) 8724 return true; 8725 8726 LocTy Loc = Lex.getLoc(); 8727 unsigned GVId; 8728 if (parseGVReference(VI, GVId)) 8729 return true; 8730 8731 uint64_t Offset; 8732 if (parseToken(lltok::comma, "expected comma") || 8733 parseToken(lltok::kw_offset, "expected offset") || 8734 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 8735 return true; 8736 8737 // Keep track of the VTableFuncs array index needing a forward reference. 8738 // We will save the location of the ValueInfo needing an update, but 8739 // can only do so once the std::vector is finalized. 8740 if (VI == EmptyVI) 8741 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 8742 VTableFuncs.push_back({VI, Offset}); 8743 8744 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 8745 return true; 8746 } while (EatIfPresent(lltok::comma)); 8747 8748 // Now that the VTableFuncs vector is finalized, it is safe to save the 8749 // locations of any forward GV references that need updating later. 8750 for (auto I : IdToIndexMap) { 8751 auto &Infos = ForwardRefValueInfos[I.first]; 8752 for (auto P : I.second) { 8753 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 8754 "Forward referenced ValueInfo expected to be empty"); 8755 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 8756 } 8757 } 8758 8759 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 8760 return true; 8761 8762 return false; 8763 } 8764 8765 /// ParamNo := 'param' ':' UInt64 8766 bool LLParser::parseParamNo(uint64_t &ParamNo) { 8767 if (parseToken(lltok::kw_param, "expected 'param' here") || 8768 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 8769 return true; 8770 return false; 8771 } 8772 8773 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 8774 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 8775 APSInt Lower; 8776 APSInt Upper; 8777 auto ParseAPSInt = [&](APSInt &Val) { 8778 if (Lex.getKind() != lltok::APSInt) 8779 return tokError("expected integer"); 8780 Val = Lex.getAPSIntVal(); 8781 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 8782 Val.setIsSigned(true); 8783 Lex.Lex(); 8784 return false; 8785 }; 8786 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 8787 parseToken(lltok::colon, "expected ':' here") || 8788 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 8789 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 8790 parseToken(lltok::rsquare, "expected ']' here")) 8791 return true; 8792 8793 ++Upper; 8794 Range = 8795 (Lower == Upper && !Lower.isMaxValue()) 8796 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 8797 : ConstantRange(Lower, Upper); 8798 8799 return false; 8800 } 8801 8802 /// ParamAccessCall 8803 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 8804 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 8805 IdLocListType &IdLocList) { 8806 if (parseToken(lltok::lparen, "expected '(' here") || 8807 parseToken(lltok::kw_callee, "expected 'callee' here") || 8808 parseToken(lltok::colon, "expected ':' here")) 8809 return true; 8810 8811 unsigned GVId; 8812 ValueInfo VI; 8813 LocTy Loc = Lex.getLoc(); 8814 if (parseGVReference(VI, GVId)) 8815 return true; 8816 8817 Call.Callee = VI; 8818 IdLocList.emplace_back(GVId, Loc); 8819 8820 if (parseToken(lltok::comma, "expected ',' here") || 8821 parseParamNo(Call.ParamNo) || 8822 parseToken(lltok::comma, "expected ',' here") || 8823 parseParamAccessOffset(Call.Offsets)) 8824 return true; 8825 8826 if (parseToken(lltok::rparen, "expected ')' here")) 8827 return true; 8828 8829 return false; 8830 } 8831 8832 /// ParamAccess 8833 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 8834 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 8835 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 8836 IdLocListType &IdLocList) { 8837 if (parseToken(lltok::lparen, "expected '(' here") || 8838 parseParamNo(Param.ParamNo) || 8839 parseToken(lltok::comma, "expected ',' here") || 8840 parseParamAccessOffset(Param.Use)) 8841 return true; 8842 8843 if (EatIfPresent(lltok::comma)) { 8844 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 8845 parseToken(lltok::colon, "expected ':' here") || 8846 parseToken(lltok::lparen, "expected '(' here")) 8847 return true; 8848 do { 8849 FunctionSummary::ParamAccess::Call Call; 8850 if (parseParamAccessCall(Call, IdLocList)) 8851 return true; 8852 Param.Calls.push_back(Call); 8853 } while (EatIfPresent(lltok::comma)); 8854 8855 if (parseToken(lltok::rparen, "expected ')' here")) 8856 return true; 8857 } 8858 8859 if (parseToken(lltok::rparen, "expected ')' here")) 8860 return true; 8861 8862 return false; 8863 } 8864 8865 /// OptionalParamAccesses 8866 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 8867 bool LLParser::parseOptionalParamAccesses( 8868 std::vector<FunctionSummary::ParamAccess> &Params) { 8869 assert(Lex.getKind() == lltok::kw_params); 8870 Lex.Lex(); 8871 8872 if (parseToken(lltok::colon, "expected ':' here") || 8873 parseToken(lltok::lparen, "expected '(' here")) 8874 return true; 8875 8876 IdLocListType VContexts; 8877 size_t CallsNum = 0; 8878 do { 8879 FunctionSummary::ParamAccess ParamAccess; 8880 if (parseParamAccess(ParamAccess, VContexts)) 8881 return true; 8882 CallsNum += ParamAccess.Calls.size(); 8883 assert(VContexts.size() == CallsNum); 8884 (void)CallsNum; 8885 Params.emplace_back(std::move(ParamAccess)); 8886 } while (EatIfPresent(lltok::comma)); 8887 8888 if (parseToken(lltok::rparen, "expected ')' here")) 8889 return true; 8890 8891 // Now that the Params is finalized, it is safe to save the locations 8892 // of any forward GV references that need updating later. 8893 IdLocListType::const_iterator ItContext = VContexts.begin(); 8894 for (auto &PA : Params) { 8895 for (auto &C : PA.Calls) { 8896 if (C.Callee.getRef() == FwdVIRef) 8897 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 8898 ItContext->second); 8899 ++ItContext; 8900 } 8901 } 8902 assert(ItContext == VContexts.end()); 8903 8904 return false; 8905 } 8906 8907 /// OptionalRefs 8908 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 8909 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) { 8910 assert(Lex.getKind() == lltok::kw_refs); 8911 Lex.Lex(); 8912 8913 if (parseToken(lltok::colon, "expected ':' in refs") || 8914 parseToken(lltok::lparen, "expected '(' in refs")) 8915 return true; 8916 8917 struct ValueContext { 8918 ValueInfo VI; 8919 unsigned GVId; 8920 LocTy Loc; 8921 }; 8922 std::vector<ValueContext> VContexts; 8923 // parse each ref edge 8924 do { 8925 ValueContext VC; 8926 VC.Loc = Lex.getLoc(); 8927 if (parseGVReference(VC.VI, VC.GVId)) 8928 return true; 8929 VContexts.push_back(VC); 8930 } while (EatIfPresent(lltok::comma)); 8931 8932 // Sort value contexts so that ones with writeonly 8933 // and readonly ValueInfo are at the end of VContexts vector. 8934 // See FunctionSummary::specialRefCounts() 8935 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 8936 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 8937 }); 8938 8939 IdToIndexMapType IdToIndexMap; 8940 for (auto &VC : VContexts) { 8941 // Keep track of the Refs array index needing a forward reference. 8942 // We will save the location of the ValueInfo needing an update, but 8943 // can only do so once the std::vector is finalized. 8944 if (VC.VI.getRef() == FwdVIRef) 8945 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 8946 Refs.push_back(VC.VI); 8947 } 8948 8949 // Now that the Refs vector is finalized, it is safe to save the locations 8950 // of any forward GV references that need updating later. 8951 for (auto I : IdToIndexMap) { 8952 auto &Infos = ForwardRefValueInfos[I.first]; 8953 for (auto P : I.second) { 8954 assert(Refs[P.first].getRef() == FwdVIRef && 8955 "Forward referenced ValueInfo expected to be empty"); 8956 Infos.emplace_back(&Refs[P.first], P.second); 8957 } 8958 } 8959 8960 if (parseToken(lltok::rparen, "expected ')' in refs")) 8961 return true; 8962 8963 return false; 8964 } 8965 8966 /// OptionalTypeIdInfo 8967 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 8968 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 8969 /// [',' TypeCheckedLoadConstVCalls]? ')' 8970 bool LLParser::parseOptionalTypeIdInfo( 8971 FunctionSummary::TypeIdInfo &TypeIdInfo) { 8972 assert(Lex.getKind() == lltok::kw_typeIdInfo); 8973 Lex.Lex(); 8974 8975 if (parseToken(lltok::colon, "expected ':' here") || 8976 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 8977 return true; 8978 8979 do { 8980 switch (Lex.getKind()) { 8981 case lltok::kw_typeTests: 8982 if (parseTypeTests(TypeIdInfo.TypeTests)) 8983 return true; 8984 break; 8985 case lltok::kw_typeTestAssumeVCalls: 8986 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 8987 TypeIdInfo.TypeTestAssumeVCalls)) 8988 return true; 8989 break; 8990 case lltok::kw_typeCheckedLoadVCalls: 8991 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 8992 TypeIdInfo.TypeCheckedLoadVCalls)) 8993 return true; 8994 break; 8995 case lltok::kw_typeTestAssumeConstVCalls: 8996 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 8997 TypeIdInfo.TypeTestAssumeConstVCalls)) 8998 return true; 8999 break; 9000 case lltok::kw_typeCheckedLoadConstVCalls: 9001 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 9002 TypeIdInfo.TypeCheckedLoadConstVCalls)) 9003 return true; 9004 break; 9005 default: 9006 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 9007 } 9008 } while (EatIfPresent(lltok::comma)); 9009 9010 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9011 return true; 9012 9013 return false; 9014 } 9015 9016 /// TypeTests 9017 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 9018 /// [',' (SummaryID | UInt64)]* ')' 9019 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 9020 assert(Lex.getKind() == lltok::kw_typeTests); 9021 Lex.Lex(); 9022 9023 if (parseToken(lltok::colon, "expected ':' here") || 9024 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 9025 return true; 9026 9027 IdToIndexMapType IdToIndexMap; 9028 do { 9029 GlobalValue::GUID GUID = 0; 9030 if (Lex.getKind() == lltok::SummaryID) { 9031 unsigned ID = Lex.getUIntVal(); 9032 LocTy Loc = Lex.getLoc(); 9033 // Keep track of the TypeTests array index needing a forward reference. 9034 // We will save the location of the GUID needing an update, but 9035 // can only do so once the std::vector is finalized. 9036 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 9037 Lex.Lex(); 9038 } else if (parseUInt64(GUID)) 9039 return true; 9040 TypeTests.push_back(GUID); 9041 } while (EatIfPresent(lltok::comma)); 9042 9043 // Now that the TypeTests vector is finalized, it is safe to save the 9044 // locations of any forward GV references that need updating later. 9045 for (auto I : IdToIndexMap) { 9046 auto &Ids = ForwardRefTypeIds[I.first]; 9047 for (auto P : I.second) { 9048 assert(TypeTests[P.first] == 0 && 9049 "Forward referenced type id GUID expected to be 0"); 9050 Ids.emplace_back(&TypeTests[P.first], P.second); 9051 } 9052 } 9053 9054 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 9055 return true; 9056 9057 return false; 9058 } 9059 9060 /// VFuncIdList 9061 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 9062 bool LLParser::parseVFuncIdList( 9063 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 9064 assert(Lex.getKind() == Kind); 9065 Lex.Lex(); 9066 9067 if (parseToken(lltok::colon, "expected ':' here") || 9068 parseToken(lltok::lparen, "expected '(' here")) 9069 return true; 9070 9071 IdToIndexMapType IdToIndexMap; 9072 do { 9073 FunctionSummary::VFuncId VFuncId; 9074 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 9075 return true; 9076 VFuncIdList.push_back(VFuncId); 9077 } while (EatIfPresent(lltok::comma)); 9078 9079 if (parseToken(lltok::rparen, "expected ')' here")) 9080 return true; 9081 9082 // Now that the VFuncIdList vector is finalized, it is safe to save the 9083 // locations of any forward GV references that need updating later. 9084 for (auto I : IdToIndexMap) { 9085 auto &Ids = ForwardRefTypeIds[I.first]; 9086 for (auto P : I.second) { 9087 assert(VFuncIdList[P.first].GUID == 0 && 9088 "Forward referenced type id GUID expected to be 0"); 9089 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 9090 } 9091 } 9092 9093 return false; 9094 } 9095 9096 /// ConstVCallList 9097 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 9098 bool LLParser::parseConstVCallList( 9099 lltok::Kind Kind, 9100 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 9101 assert(Lex.getKind() == Kind); 9102 Lex.Lex(); 9103 9104 if (parseToken(lltok::colon, "expected ':' here") || 9105 parseToken(lltok::lparen, "expected '(' here")) 9106 return true; 9107 9108 IdToIndexMapType IdToIndexMap; 9109 do { 9110 FunctionSummary::ConstVCall ConstVCall; 9111 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 9112 return true; 9113 ConstVCallList.push_back(ConstVCall); 9114 } while (EatIfPresent(lltok::comma)); 9115 9116 if (parseToken(lltok::rparen, "expected ')' here")) 9117 return true; 9118 9119 // Now that the ConstVCallList vector is finalized, it is safe to save the 9120 // locations of any forward GV references that need updating later. 9121 for (auto I : IdToIndexMap) { 9122 auto &Ids = ForwardRefTypeIds[I.first]; 9123 for (auto P : I.second) { 9124 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 9125 "Forward referenced type id GUID expected to be 0"); 9126 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 9127 } 9128 } 9129 9130 return false; 9131 } 9132 9133 /// ConstVCall 9134 /// ::= '(' VFuncId ',' Args ')' 9135 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 9136 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9137 if (parseToken(lltok::lparen, "expected '(' here") || 9138 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 9139 return true; 9140 9141 if (EatIfPresent(lltok::comma)) 9142 if (parseArgs(ConstVCall.Args)) 9143 return true; 9144 9145 if (parseToken(lltok::rparen, "expected ')' here")) 9146 return true; 9147 9148 return false; 9149 } 9150 9151 /// VFuncId 9152 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 9153 /// 'offset' ':' UInt64 ')' 9154 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 9155 IdToIndexMapType &IdToIndexMap, unsigned Index) { 9156 assert(Lex.getKind() == lltok::kw_vFuncId); 9157 Lex.Lex(); 9158 9159 if (parseToken(lltok::colon, "expected ':' here") || 9160 parseToken(lltok::lparen, "expected '(' here")) 9161 return true; 9162 9163 if (Lex.getKind() == lltok::SummaryID) { 9164 VFuncId.GUID = 0; 9165 unsigned ID = Lex.getUIntVal(); 9166 LocTy Loc = Lex.getLoc(); 9167 // Keep track of the array index needing a forward reference. 9168 // We will save the location of the GUID needing an update, but 9169 // can only do so once the caller's std::vector is finalized. 9170 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 9171 Lex.Lex(); 9172 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 9173 parseToken(lltok::colon, "expected ':' here") || 9174 parseUInt64(VFuncId.GUID)) 9175 return true; 9176 9177 if (parseToken(lltok::comma, "expected ',' here") || 9178 parseToken(lltok::kw_offset, "expected 'offset' here") || 9179 parseToken(lltok::colon, "expected ':' here") || 9180 parseUInt64(VFuncId.Offset) || 9181 parseToken(lltok::rparen, "expected ')' here")) 9182 return true; 9183 9184 return false; 9185 } 9186 9187 /// GVFlags 9188 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 9189 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ',' 9190 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ',' 9191 /// 'canAutoHide' ':' Flag ',' ')' 9192 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 9193 assert(Lex.getKind() == lltok::kw_flags); 9194 Lex.Lex(); 9195 9196 if (parseToken(lltok::colon, "expected ':' here") || 9197 parseToken(lltok::lparen, "expected '(' here")) 9198 return true; 9199 9200 do { 9201 unsigned Flag = 0; 9202 switch (Lex.getKind()) { 9203 case lltok::kw_linkage: 9204 Lex.Lex(); 9205 if (parseToken(lltok::colon, "expected ':'")) 9206 return true; 9207 bool HasLinkage; 9208 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 9209 assert(HasLinkage && "Linkage not optional in summary entry"); 9210 Lex.Lex(); 9211 break; 9212 case lltok::kw_visibility: 9213 Lex.Lex(); 9214 if (parseToken(lltok::colon, "expected ':'")) 9215 return true; 9216 parseOptionalVisibility(Flag); 9217 GVFlags.Visibility = Flag; 9218 break; 9219 case lltok::kw_notEligibleToImport: 9220 Lex.Lex(); 9221 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9222 return true; 9223 GVFlags.NotEligibleToImport = Flag; 9224 break; 9225 case lltok::kw_live: 9226 Lex.Lex(); 9227 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9228 return true; 9229 GVFlags.Live = Flag; 9230 break; 9231 case lltok::kw_dsoLocal: 9232 Lex.Lex(); 9233 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9234 return true; 9235 GVFlags.DSOLocal = Flag; 9236 break; 9237 case lltok::kw_canAutoHide: 9238 Lex.Lex(); 9239 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 9240 return true; 9241 GVFlags.CanAutoHide = Flag; 9242 break; 9243 default: 9244 return error(Lex.getLoc(), "expected gv flag type"); 9245 } 9246 } while (EatIfPresent(lltok::comma)); 9247 9248 if (parseToken(lltok::rparen, "expected ')' here")) 9249 return true; 9250 9251 return false; 9252 } 9253 9254 /// GVarFlags 9255 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 9256 /// ',' 'writeonly' ':' Flag 9257 /// ',' 'constant' ':' Flag ')' 9258 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 9259 assert(Lex.getKind() == lltok::kw_varFlags); 9260 Lex.Lex(); 9261 9262 if (parseToken(lltok::colon, "expected ':' here") || 9263 parseToken(lltok::lparen, "expected '(' here")) 9264 return true; 9265 9266 auto ParseRest = [this](unsigned int &Val) { 9267 Lex.Lex(); 9268 if (parseToken(lltok::colon, "expected ':'")) 9269 return true; 9270 return parseFlag(Val); 9271 }; 9272 9273 do { 9274 unsigned Flag = 0; 9275 switch (Lex.getKind()) { 9276 case lltok::kw_readonly: 9277 if (ParseRest(Flag)) 9278 return true; 9279 GVarFlags.MaybeReadOnly = Flag; 9280 break; 9281 case lltok::kw_writeonly: 9282 if (ParseRest(Flag)) 9283 return true; 9284 GVarFlags.MaybeWriteOnly = Flag; 9285 break; 9286 case lltok::kw_constant: 9287 if (ParseRest(Flag)) 9288 return true; 9289 GVarFlags.Constant = Flag; 9290 break; 9291 case lltok::kw_vcall_visibility: 9292 if (ParseRest(Flag)) 9293 return true; 9294 GVarFlags.VCallVisibility = Flag; 9295 break; 9296 default: 9297 return error(Lex.getLoc(), "expected gvar flag type"); 9298 } 9299 } while (EatIfPresent(lltok::comma)); 9300 return parseToken(lltok::rparen, "expected ')' here"); 9301 } 9302 9303 /// ModuleReference 9304 /// ::= 'module' ':' UInt 9305 bool LLParser::parseModuleReference(StringRef &ModulePath) { 9306 // parse module id. 9307 if (parseToken(lltok::kw_module, "expected 'module' here") || 9308 parseToken(lltok::colon, "expected ':' here") || 9309 parseToken(lltok::SummaryID, "expected module ID")) 9310 return true; 9311 9312 unsigned ModuleID = Lex.getUIntVal(); 9313 auto I = ModuleIdMap.find(ModuleID); 9314 // We should have already parsed all module IDs 9315 assert(I != ModuleIdMap.end()); 9316 ModulePath = I->second; 9317 return false; 9318 } 9319 9320 /// GVReference 9321 /// ::= SummaryID 9322 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 9323 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 9324 if (!ReadOnly) 9325 WriteOnly = EatIfPresent(lltok::kw_writeonly); 9326 if (parseToken(lltok::SummaryID, "expected GV ID")) 9327 return true; 9328 9329 GVId = Lex.getUIntVal(); 9330 // Check if we already have a VI for this GV 9331 if (GVId < NumberedValueInfos.size()) { 9332 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 9333 VI = NumberedValueInfos[GVId]; 9334 } else 9335 // We will create a forward reference to the stored location. 9336 VI = ValueInfo(false, FwdVIRef); 9337 9338 if (ReadOnly) 9339 VI.setReadOnly(); 9340 if (WriteOnly) 9341 VI.setWriteOnly(); 9342 return false; 9343 } 9344