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