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