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