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 = Intrinsic::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::getOrInsertDeclaration(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, {}), 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 && !Lower.isZero()) 3113 return tokError("the range represent the empty set but limits aren't 0!"); 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)) 3206 return true; 3207 if (Ty->isMetadataTy()) { 3208 if (parseMetadataAsValue(Input, PFS)) 3209 return true; 3210 } else if (parseValue(Ty, Input, PFS)) { 3211 return true; 3212 } 3213 Inputs.push_back(Input); 3214 } 3215 3216 BundleList.emplace_back(std::move(Tag), std::move(Inputs)); 3217 3218 Lex.Lex(); // Lex the ')'. 3219 } 3220 3221 if (BundleList.empty()) 3222 return error(BeginLoc, "operand bundle set must not be empty"); 3223 3224 Lex.Lex(); // Lex the ']'. 3225 return false; 3226 } 3227 3228 bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix, 3229 unsigned NextID, unsigned ID) { 3230 if (ID < NextID) 3231 return error(Loc, Kind + " expected to be numbered '" + Prefix + 3232 Twine(NextID) + "' or greater"); 3233 3234 return false; 3235 } 3236 3237 /// parseArgumentList - parse the argument list for a function type or function 3238 /// prototype. 3239 /// ::= '(' ArgTypeListI ')' 3240 /// ArgTypeListI 3241 /// ::= /*empty*/ 3242 /// ::= '...' 3243 /// ::= ArgTypeList ',' '...' 3244 /// ::= ArgType (',' ArgType)* 3245 /// 3246 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, 3247 SmallVectorImpl<unsigned> &UnnamedArgNums, 3248 bool &IsVarArg) { 3249 unsigned CurValID = 0; 3250 IsVarArg = false; 3251 assert(Lex.getKind() == lltok::lparen); 3252 Lex.Lex(); // eat the (. 3253 3254 if (Lex.getKind() != lltok::rparen) { 3255 do { 3256 // Handle ... at end of arg list. 3257 if (EatIfPresent(lltok::dotdotdot)) { 3258 IsVarArg = true; 3259 break; 3260 } 3261 3262 // Otherwise must be an argument type. 3263 LocTy TypeLoc = Lex.getLoc(); 3264 Type *ArgTy = nullptr; 3265 AttrBuilder Attrs(M->getContext()); 3266 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs)) 3267 return true; 3268 3269 if (ArgTy->isVoidTy()) 3270 return error(TypeLoc, "argument can not have void type"); 3271 3272 std::string Name; 3273 if (Lex.getKind() == lltok::LocalVar) { 3274 Name = Lex.getStrVal(); 3275 Lex.Lex(); 3276 } else { 3277 unsigned ArgID; 3278 if (Lex.getKind() == lltok::LocalVarID) { 3279 ArgID = Lex.getUIntVal(); 3280 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID)) 3281 return true; 3282 Lex.Lex(); 3283 } else { 3284 ArgID = CurValID; 3285 } 3286 UnnamedArgNums.push_back(ArgID); 3287 CurValID = ArgID + 1; 3288 } 3289 3290 if (!ArgTy->isFirstClassType()) 3291 return error(TypeLoc, "invalid type for function argument"); 3292 3293 ArgList.emplace_back(TypeLoc, ArgTy, 3294 AttributeSet::get(ArgTy->getContext(), Attrs), 3295 std::move(Name)); 3296 } while (EatIfPresent(lltok::comma)); 3297 } 3298 3299 return parseToken(lltok::rparen, "expected ')' at end of argument list"); 3300 } 3301 3302 /// parseFunctionType 3303 /// ::= Type ArgumentList OptionalAttrs 3304 bool LLParser::parseFunctionType(Type *&Result) { 3305 assert(Lex.getKind() == lltok::lparen); 3306 3307 if (!FunctionType::isValidReturnType(Result)) 3308 return tokError("invalid function return type"); 3309 3310 SmallVector<ArgInfo, 8> ArgList; 3311 bool IsVarArg; 3312 SmallVector<unsigned> UnnamedArgNums; 3313 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg)) 3314 return true; 3315 3316 // Reject names on the arguments lists. 3317 for (const ArgInfo &Arg : ArgList) { 3318 if (!Arg.Name.empty()) 3319 return error(Arg.Loc, "argument name invalid in function type"); 3320 if (Arg.Attrs.hasAttributes()) 3321 return error(Arg.Loc, "argument attributes invalid in function type"); 3322 } 3323 3324 SmallVector<Type*, 16> ArgListTy; 3325 for (const ArgInfo &Arg : ArgList) 3326 ArgListTy.push_back(Arg.Ty); 3327 3328 Result = FunctionType::get(Result, ArgListTy, IsVarArg); 3329 return false; 3330 } 3331 3332 /// parseAnonStructType - parse an anonymous struct type, which is inlined into 3333 /// other structs. 3334 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) { 3335 SmallVector<Type*, 8> Elts; 3336 if (parseStructBody(Elts)) 3337 return true; 3338 3339 Result = StructType::get(Context, Elts, Packed); 3340 return false; 3341 } 3342 3343 /// parseStructDefinition - parse a struct in a 'type' definition. 3344 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name, 3345 std::pair<Type *, LocTy> &Entry, 3346 Type *&ResultTy) { 3347 // If the type was already defined, diagnose the redefinition. 3348 if (Entry.first && !Entry.second.isValid()) 3349 return error(TypeLoc, "redefinition of type"); 3350 3351 // If we have opaque, just return without filling in the definition for the 3352 // struct. This counts as a definition as far as the .ll file goes. 3353 if (EatIfPresent(lltok::kw_opaque)) { 3354 // This type is being defined, so clear the location to indicate this. 3355 Entry.second = SMLoc(); 3356 3357 // If this type number has never been uttered, create it. 3358 if (!Entry.first) 3359 Entry.first = StructType::create(Context, Name); 3360 ResultTy = Entry.first; 3361 return false; 3362 } 3363 3364 // If the type starts with '<', then it is either a packed struct or a vector. 3365 bool isPacked = EatIfPresent(lltok::less); 3366 3367 // If we don't have a struct, then we have a random type alias, which we 3368 // accept for compatibility with old files. These types are not allowed to be 3369 // forward referenced and not allowed to be recursive. 3370 if (Lex.getKind() != lltok::lbrace) { 3371 if (Entry.first) 3372 return error(TypeLoc, "forward references to non-struct type"); 3373 3374 ResultTy = nullptr; 3375 if (isPacked) 3376 return parseArrayVectorType(ResultTy, true); 3377 return parseType(ResultTy); 3378 } 3379 3380 // This type is being defined, so clear the location to indicate this. 3381 Entry.second = SMLoc(); 3382 3383 // If this type number has never been uttered, create it. 3384 if (!Entry.first) 3385 Entry.first = StructType::create(Context, Name); 3386 3387 StructType *STy = cast<StructType>(Entry.first); 3388 3389 SmallVector<Type*, 8> Body; 3390 if (parseStructBody(Body) || 3391 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct"))) 3392 return true; 3393 3394 if (auto E = STy->setBodyOrError(Body, isPacked)) 3395 return tokError(toString(std::move(E))); 3396 3397 ResultTy = STy; 3398 return false; 3399 } 3400 3401 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere. 3402 /// StructType 3403 /// ::= '{' '}' 3404 /// ::= '{' Type (',' Type)* '}' 3405 /// ::= '<' '{' '}' '>' 3406 /// ::= '<' '{' Type (',' Type)* '}' '>' 3407 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) { 3408 assert(Lex.getKind() == lltok::lbrace); 3409 Lex.Lex(); // Consume the '{' 3410 3411 // Handle the empty struct. 3412 if (EatIfPresent(lltok::rbrace)) 3413 return false; 3414 3415 LocTy EltTyLoc = Lex.getLoc(); 3416 Type *Ty = nullptr; 3417 if (parseType(Ty)) 3418 return true; 3419 Body.push_back(Ty); 3420 3421 if (!StructType::isValidElementType(Ty)) 3422 return error(EltTyLoc, "invalid element type for struct"); 3423 3424 while (EatIfPresent(lltok::comma)) { 3425 EltTyLoc = Lex.getLoc(); 3426 if (parseType(Ty)) 3427 return true; 3428 3429 if (!StructType::isValidElementType(Ty)) 3430 return error(EltTyLoc, "invalid element type for struct"); 3431 3432 Body.push_back(Ty); 3433 } 3434 3435 return parseToken(lltok::rbrace, "expected '}' at end of struct"); 3436 } 3437 3438 /// parseArrayVectorType - parse an array or vector type, assuming the first 3439 /// token has already been consumed. 3440 /// Type 3441 /// ::= '[' APSINTVAL 'x' Types ']' 3442 /// ::= '<' APSINTVAL 'x' Types '>' 3443 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>' 3444 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) { 3445 bool Scalable = false; 3446 3447 if (IsVector && Lex.getKind() == lltok::kw_vscale) { 3448 Lex.Lex(); // consume the 'vscale' 3449 if (parseToken(lltok::kw_x, "expected 'x' after vscale")) 3450 return true; 3451 3452 Scalable = true; 3453 } 3454 3455 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() || 3456 Lex.getAPSIntVal().getBitWidth() > 64) 3457 return tokError("expected number in address space"); 3458 3459 LocTy SizeLoc = Lex.getLoc(); 3460 uint64_t Size = Lex.getAPSIntVal().getZExtValue(); 3461 Lex.Lex(); 3462 3463 if (parseToken(lltok::kw_x, "expected 'x' after element count")) 3464 return true; 3465 3466 LocTy TypeLoc = Lex.getLoc(); 3467 Type *EltTy = nullptr; 3468 if (parseType(EltTy)) 3469 return true; 3470 3471 if (parseToken(IsVector ? lltok::greater : lltok::rsquare, 3472 "expected end of sequential type")) 3473 return true; 3474 3475 if (IsVector) { 3476 if (Size == 0) 3477 return error(SizeLoc, "zero element vector is illegal"); 3478 if ((unsigned)Size != Size) 3479 return error(SizeLoc, "size too large for vector"); 3480 if (!VectorType::isValidElementType(EltTy)) 3481 return error(TypeLoc, "invalid vector element type"); 3482 Result = VectorType::get(EltTy, unsigned(Size), Scalable); 3483 } else { 3484 if (!ArrayType::isValidElementType(EltTy)) 3485 return error(TypeLoc, "invalid array element type"); 3486 Result = ArrayType::get(EltTy, Size); 3487 } 3488 return false; 3489 } 3490 3491 /// parseTargetExtType - handle target extension type syntax 3492 /// TargetExtType 3493 /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')' 3494 /// 3495 /// TargetExtTypeParams 3496 /// ::= /*empty*/ 3497 /// ::= ',' Type TargetExtTypeParams 3498 /// 3499 /// TargetExtIntParams 3500 /// ::= /*empty*/ 3501 /// ::= ',' uint32 TargetExtIntParams 3502 bool LLParser::parseTargetExtType(Type *&Result) { 3503 Lex.Lex(); // Eat the 'target' keyword. 3504 3505 // Get the mandatory type name. 3506 std::string TypeName; 3507 if (parseToken(lltok::lparen, "expected '(' in target extension type") || 3508 parseStringConstant(TypeName)) 3509 return true; 3510 3511 // Parse all of the integer and type parameters at the same time; the use of 3512 // SeenInt will allow us to catch cases where type parameters follow integer 3513 // parameters. 3514 SmallVector<Type *> TypeParams; 3515 SmallVector<unsigned> IntParams; 3516 bool SeenInt = false; 3517 while (Lex.getKind() == lltok::comma) { 3518 Lex.Lex(); // Eat the comma. 3519 3520 if (Lex.getKind() == lltok::APSInt) { 3521 SeenInt = true; 3522 unsigned IntVal; 3523 if (parseUInt32(IntVal)) 3524 return true; 3525 IntParams.push_back(IntVal); 3526 } else if (SeenInt) { 3527 // The only other kind of parameter we support is type parameters, which 3528 // must precede the integer parameters. This is therefore an error. 3529 return tokError("expected uint32 param"); 3530 } else { 3531 Type *TypeParam; 3532 if (parseType(TypeParam, /*AllowVoid=*/true)) 3533 return true; 3534 TypeParams.push_back(TypeParam); 3535 } 3536 } 3537 3538 if (parseToken(lltok::rparen, "expected ')' in target extension type")) 3539 return true; 3540 3541 auto TTy = 3542 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams); 3543 if (auto E = TTy.takeError()) 3544 return tokError(toString(std::move(E))); 3545 3546 Result = *TTy; 3547 return false; 3548 } 3549 3550 //===----------------------------------------------------------------------===// 3551 // Function Semantic Analysis. 3552 //===----------------------------------------------------------------------===// 3553 3554 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f, 3555 int functionNumber, 3556 ArrayRef<unsigned> UnnamedArgNums) 3557 : P(p), F(f), FunctionNumber(functionNumber) { 3558 3559 // Insert unnamed arguments into the NumberedVals list. 3560 auto It = UnnamedArgNums.begin(); 3561 for (Argument &A : F.args()) { 3562 if (!A.hasName()) { 3563 unsigned ArgNum = *It++; 3564 NumberedVals.add(ArgNum, &A); 3565 } 3566 } 3567 } 3568 3569 LLParser::PerFunctionState::~PerFunctionState() { 3570 // If there were any forward referenced non-basicblock values, delete them. 3571 3572 for (const auto &P : ForwardRefVals) { 3573 if (isa<BasicBlock>(P.second.first)) 3574 continue; 3575 P.second.first->replaceAllUsesWith( 3576 PoisonValue::get(P.second.first->getType())); 3577 P.second.first->deleteValue(); 3578 } 3579 3580 for (const auto &P : ForwardRefValIDs) { 3581 if (isa<BasicBlock>(P.second.first)) 3582 continue; 3583 P.second.first->replaceAllUsesWith( 3584 PoisonValue::get(P.second.first->getType())); 3585 P.second.first->deleteValue(); 3586 } 3587 } 3588 3589 bool LLParser::PerFunctionState::finishFunction() { 3590 if (!ForwardRefVals.empty()) 3591 return P.error(ForwardRefVals.begin()->second.second, 3592 "use of undefined value '%" + ForwardRefVals.begin()->first + 3593 "'"); 3594 if (!ForwardRefValIDs.empty()) 3595 return P.error(ForwardRefValIDs.begin()->second.second, 3596 "use of undefined value '%" + 3597 Twine(ForwardRefValIDs.begin()->first) + "'"); 3598 return false; 3599 } 3600 3601 /// getVal - Get a value with the specified name or ID, creating a 3602 /// forward reference record if needed. This can return null if the value 3603 /// exists but does not have the right type. 3604 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty, 3605 LocTy Loc) { 3606 // Look this name up in the normal function symbol table. 3607 Value *Val = F.getValueSymbolTable()->lookup(Name); 3608 3609 // If this is a forward reference for the value, see if we already created a 3610 // forward ref record. 3611 if (!Val) { 3612 auto I = ForwardRefVals.find(Name); 3613 if (I != ForwardRefVals.end()) 3614 Val = I->second.first; 3615 } 3616 3617 // If we have the value in the symbol table or fwd-ref table, return it. 3618 if (Val) 3619 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val); 3620 3621 // Don't make placeholders with invalid type. 3622 if (!Ty->isFirstClassType()) { 3623 P.error(Loc, "invalid use of a non-first-class type"); 3624 return nullptr; 3625 } 3626 3627 // Otherwise, create a new forward reference for this value and remember it. 3628 Value *FwdVal; 3629 if (Ty->isLabelTy()) { 3630 FwdVal = BasicBlock::Create(F.getContext(), Name, &F); 3631 } else { 3632 FwdVal = new Argument(Ty, Name); 3633 } 3634 if (FwdVal->getName() != Name) { 3635 P.error(Loc, "name is too long which can result in name collisions, " 3636 "consider making the name shorter or " 3637 "increasing -non-global-value-max-name-size"); 3638 return nullptr; 3639 } 3640 3641 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc); 3642 return FwdVal; 3643 } 3644 3645 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) { 3646 // Look this name up in the normal function symbol table. 3647 Value *Val = NumberedVals.get(ID); 3648 3649 // If this is a forward reference for the value, see if we already created a 3650 // forward ref record. 3651 if (!Val) { 3652 auto I = ForwardRefValIDs.find(ID); 3653 if (I != ForwardRefValIDs.end()) 3654 Val = I->second.first; 3655 } 3656 3657 // If we have the value in the symbol table or fwd-ref table, return it. 3658 if (Val) 3659 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val); 3660 3661 if (!Ty->isFirstClassType()) { 3662 P.error(Loc, "invalid use of a non-first-class type"); 3663 return nullptr; 3664 } 3665 3666 // Otherwise, create a new forward reference for this value and remember it. 3667 Value *FwdVal; 3668 if (Ty->isLabelTy()) { 3669 FwdVal = BasicBlock::Create(F.getContext(), "", &F); 3670 } else { 3671 FwdVal = new Argument(Ty); 3672 } 3673 3674 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc); 3675 return FwdVal; 3676 } 3677 3678 /// setInstName - After an instruction is parsed and inserted into its 3679 /// basic block, this installs its name. 3680 bool LLParser::PerFunctionState::setInstName(int NameID, 3681 const std::string &NameStr, 3682 LocTy NameLoc, Instruction *Inst) { 3683 // If this instruction has void type, it cannot have a name or ID specified. 3684 if (Inst->getType()->isVoidTy()) { 3685 if (NameID != -1 || !NameStr.empty()) 3686 return P.error(NameLoc, "instructions returning void cannot have a name"); 3687 return false; 3688 } 3689 3690 // If this was a numbered instruction, verify that the instruction is the 3691 // expected value and resolve any forward references. 3692 if (NameStr.empty()) { 3693 // If neither a name nor an ID was specified, just use the next ID. 3694 if (NameID == -1) 3695 NameID = NumberedVals.getNext(); 3696 3697 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(), 3698 NameID)) 3699 return true; 3700 3701 auto FI = ForwardRefValIDs.find(NameID); 3702 if (FI != ForwardRefValIDs.end()) { 3703 Value *Sentinel = FI->second.first; 3704 if (Sentinel->getType() != Inst->getType()) 3705 return P.error(NameLoc, "instruction forward referenced with type '" + 3706 getTypeString(FI->second.first->getType()) + 3707 "'"); 3708 3709 Sentinel->replaceAllUsesWith(Inst); 3710 Sentinel->deleteValue(); 3711 ForwardRefValIDs.erase(FI); 3712 } 3713 3714 NumberedVals.add(NameID, Inst); 3715 return false; 3716 } 3717 3718 // Otherwise, the instruction had a name. Resolve forward refs and set it. 3719 auto FI = ForwardRefVals.find(NameStr); 3720 if (FI != ForwardRefVals.end()) { 3721 Value *Sentinel = FI->second.first; 3722 if (Sentinel->getType() != Inst->getType()) 3723 return P.error(NameLoc, "instruction forward referenced with type '" + 3724 getTypeString(FI->second.first->getType()) + 3725 "'"); 3726 3727 Sentinel->replaceAllUsesWith(Inst); 3728 Sentinel->deleteValue(); 3729 ForwardRefVals.erase(FI); 3730 } 3731 3732 // Set the name on the instruction. 3733 Inst->setName(NameStr); 3734 3735 if (Inst->getName() != NameStr) 3736 return P.error(NameLoc, "multiple definition of local value named '" + 3737 NameStr + "'"); 3738 return false; 3739 } 3740 3741 /// getBB - Get a basic block with the specified name or ID, creating a 3742 /// forward reference record if needed. 3743 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name, 3744 LocTy Loc) { 3745 return dyn_cast_or_null<BasicBlock>( 3746 getVal(Name, Type::getLabelTy(F.getContext()), Loc)); 3747 } 3748 3749 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) { 3750 return dyn_cast_or_null<BasicBlock>( 3751 getVal(ID, Type::getLabelTy(F.getContext()), Loc)); 3752 } 3753 3754 /// defineBB - Define the specified basic block, which is either named or 3755 /// unnamed. If there is an error, this returns null otherwise it returns 3756 /// the block being defined. 3757 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name, 3758 int NameID, LocTy Loc) { 3759 BasicBlock *BB; 3760 if (Name.empty()) { 3761 if (NameID != -1) { 3762 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID)) 3763 return nullptr; 3764 } else { 3765 NameID = NumberedVals.getNext(); 3766 } 3767 BB = getBB(NameID, Loc); 3768 if (!BB) { 3769 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'"); 3770 return nullptr; 3771 } 3772 } else { 3773 BB = getBB(Name, Loc); 3774 if (!BB) { 3775 P.error(Loc, "unable to create block named '" + Name + "'"); 3776 return nullptr; 3777 } 3778 } 3779 3780 // Move the block to the end of the function. Forward ref'd blocks are 3781 // inserted wherever they happen to be referenced. 3782 F.splice(F.end(), &F, BB->getIterator()); 3783 3784 // Remove the block from forward ref sets. 3785 if (Name.empty()) { 3786 ForwardRefValIDs.erase(NameID); 3787 NumberedVals.add(NameID, BB); 3788 } else { 3789 // BB forward references are already in the function symbol table. 3790 ForwardRefVals.erase(Name); 3791 } 3792 3793 return BB; 3794 } 3795 3796 //===----------------------------------------------------------------------===// 3797 // Constants. 3798 //===----------------------------------------------------------------------===// 3799 3800 /// parseValID - parse an abstract value that doesn't necessarily have a 3801 /// type implied. For example, if we parse "4" we don't know what integer type 3802 /// it has. The value will later be combined with its type and checked for 3803 /// basic correctness. PFS is used to convert function-local operands of 3804 /// metadata (since metadata operands are not just parsed here but also 3805 /// converted to values). PFS can be null when we are not parsing metadata 3806 /// values inside a function. 3807 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) { 3808 ID.Loc = Lex.getLoc(); 3809 switch (Lex.getKind()) { 3810 default: 3811 return tokError("expected value token"); 3812 case lltok::GlobalID: // @42 3813 ID.UIntVal = Lex.getUIntVal(); 3814 ID.Kind = ValID::t_GlobalID; 3815 break; 3816 case lltok::GlobalVar: // @foo 3817 ID.StrVal = Lex.getStrVal(); 3818 ID.Kind = ValID::t_GlobalName; 3819 break; 3820 case lltok::LocalVarID: // %42 3821 ID.UIntVal = Lex.getUIntVal(); 3822 ID.Kind = ValID::t_LocalID; 3823 break; 3824 case lltok::LocalVar: // %foo 3825 ID.StrVal = Lex.getStrVal(); 3826 ID.Kind = ValID::t_LocalName; 3827 break; 3828 case lltok::APSInt: 3829 ID.APSIntVal = Lex.getAPSIntVal(); 3830 ID.Kind = ValID::t_APSInt; 3831 break; 3832 case lltok::APFloat: 3833 ID.APFloatVal = Lex.getAPFloatVal(); 3834 ID.Kind = ValID::t_APFloat; 3835 break; 3836 case lltok::kw_true: 3837 ID.ConstantVal = ConstantInt::getTrue(Context); 3838 ID.Kind = ValID::t_Constant; 3839 break; 3840 case lltok::kw_false: 3841 ID.ConstantVal = ConstantInt::getFalse(Context); 3842 ID.Kind = ValID::t_Constant; 3843 break; 3844 case lltok::kw_null: ID.Kind = ValID::t_Null; break; 3845 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break; 3846 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break; 3847 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break; 3848 case lltok::kw_none: ID.Kind = ValID::t_None; break; 3849 3850 case lltok::lbrace: { 3851 // ValID ::= '{' ConstVector '}' 3852 Lex.Lex(); 3853 SmallVector<Constant*, 16> Elts; 3854 if (parseGlobalValueVector(Elts) || 3855 parseToken(lltok::rbrace, "expected end of struct constant")) 3856 return true; 3857 3858 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3859 ID.UIntVal = Elts.size(); 3860 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3861 Elts.size() * sizeof(Elts[0])); 3862 ID.Kind = ValID::t_ConstantStruct; 3863 return false; 3864 } 3865 case lltok::less: { 3866 // ValID ::= '<' ConstVector '>' --> Vector. 3867 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct. 3868 Lex.Lex(); 3869 bool isPackedStruct = EatIfPresent(lltok::lbrace); 3870 3871 SmallVector<Constant*, 16> Elts; 3872 LocTy FirstEltLoc = Lex.getLoc(); 3873 if (parseGlobalValueVector(Elts) || 3874 (isPackedStruct && 3875 parseToken(lltok::rbrace, "expected end of packed struct")) || 3876 parseToken(lltok::greater, "expected end of constant")) 3877 return true; 3878 3879 if (isPackedStruct) { 3880 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size()); 3881 memcpy(ID.ConstantStructElts.get(), Elts.data(), 3882 Elts.size() * sizeof(Elts[0])); 3883 ID.UIntVal = Elts.size(); 3884 ID.Kind = ValID::t_PackedConstantStruct; 3885 return false; 3886 } 3887 3888 if (Elts.empty()) 3889 return error(ID.Loc, "constant vector must not be empty"); 3890 3891 if (!Elts[0]->getType()->isIntegerTy() && 3892 !Elts[0]->getType()->isFloatingPointTy() && 3893 !Elts[0]->getType()->isPointerTy()) 3894 return error( 3895 FirstEltLoc, 3896 "vector elements must have integer, pointer or floating point type"); 3897 3898 // Verify that all the vector elements have the same type. 3899 for (unsigned i = 1, e = Elts.size(); i != e; ++i) 3900 if (Elts[i]->getType() != Elts[0]->getType()) 3901 return error(FirstEltLoc, "vector element #" + Twine(i) + 3902 " is not of type '" + 3903 getTypeString(Elts[0]->getType())); 3904 3905 ID.ConstantVal = ConstantVector::get(Elts); 3906 ID.Kind = ValID::t_Constant; 3907 return false; 3908 } 3909 case lltok::lsquare: { // Array Constant 3910 Lex.Lex(); 3911 SmallVector<Constant*, 16> Elts; 3912 LocTy FirstEltLoc = Lex.getLoc(); 3913 if (parseGlobalValueVector(Elts) || 3914 parseToken(lltok::rsquare, "expected end of array constant")) 3915 return true; 3916 3917 // Handle empty element. 3918 if (Elts.empty()) { 3919 // Use undef instead of an array because it's inconvenient to determine 3920 // the element type at this point, there being no elements to examine. 3921 ID.Kind = ValID::t_EmptyArray; 3922 return false; 3923 } 3924 3925 if (!Elts[0]->getType()->isFirstClassType()) 3926 return error(FirstEltLoc, "invalid array element type: " + 3927 getTypeString(Elts[0]->getType())); 3928 3929 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size()); 3930 3931 // Verify all elements are correct type! 3932 for (unsigned i = 0, e = Elts.size(); i != e; ++i) { 3933 if (Elts[i]->getType() != Elts[0]->getType()) 3934 return error(FirstEltLoc, "array element #" + Twine(i) + 3935 " is not of type '" + 3936 getTypeString(Elts[0]->getType())); 3937 } 3938 3939 ID.ConstantVal = ConstantArray::get(ATy, Elts); 3940 ID.Kind = ValID::t_Constant; 3941 return false; 3942 } 3943 case lltok::kw_c: // c "foo" 3944 Lex.Lex(); 3945 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(), 3946 false); 3947 if (parseToken(lltok::StringConstant, "expected string")) 3948 return true; 3949 ID.Kind = ValID::t_Constant; 3950 return false; 3951 3952 case lltok::kw_asm: { 3953 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ',' 3954 // STRINGCONSTANT 3955 bool HasSideEffect, AlignStack, AsmDialect, CanThrow; 3956 Lex.Lex(); 3957 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) || 3958 parseOptionalToken(lltok::kw_alignstack, AlignStack) || 3959 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) || 3960 parseOptionalToken(lltok::kw_unwind, CanThrow) || 3961 parseStringConstant(ID.StrVal) || 3962 parseToken(lltok::comma, "expected comma in inline asm expression") || 3963 parseToken(lltok::StringConstant, "expected constraint string")) 3964 return true; 3965 ID.StrVal2 = Lex.getStrVal(); 3966 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) | 3967 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3); 3968 ID.Kind = ValID::t_InlineAsm; 3969 return false; 3970 } 3971 3972 case lltok::kw_blockaddress: { 3973 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')' 3974 Lex.Lex(); 3975 3976 ValID Fn, Label; 3977 3978 if (parseToken(lltok::lparen, "expected '(' in block address expression") || 3979 parseValID(Fn, PFS) || 3980 parseToken(lltok::comma, 3981 "expected comma in block address expression") || 3982 parseValID(Label, PFS) || 3983 parseToken(lltok::rparen, "expected ')' in block address expression")) 3984 return true; 3985 3986 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 3987 return error(Fn.Loc, "expected function name in blockaddress"); 3988 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName) 3989 return error(Label.Loc, "expected basic block name in blockaddress"); 3990 3991 // Try to find the function (but skip it if it's forward-referenced). 3992 GlobalValue *GV = nullptr; 3993 if (Fn.Kind == ValID::t_GlobalID) { 3994 GV = NumberedVals.get(Fn.UIntVal); 3995 } else if (!ForwardRefVals.count(Fn.StrVal)) { 3996 GV = M->getNamedValue(Fn.StrVal); 3997 } 3998 Function *F = nullptr; 3999 if (GV) { 4000 // Confirm that it's actually a function with a definition. 4001 if (!isa<Function>(GV)) 4002 return error(Fn.Loc, "expected function name in blockaddress"); 4003 F = cast<Function>(GV); 4004 if (F->isDeclaration()) 4005 return error(Fn.Loc, "cannot take blockaddress inside a declaration"); 4006 } 4007 4008 if (!F) { 4009 // Make a global variable as a placeholder for this reference. 4010 GlobalValue *&FwdRef = 4011 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)]; 4012 if (!FwdRef) { 4013 unsigned FwdDeclAS; 4014 if (ExpectedTy) { 4015 // If we know the type that the blockaddress is being assigned to, 4016 // we can use the address space of that type. 4017 if (!ExpectedTy->isPointerTy()) 4018 return error(ID.Loc, 4019 "type of blockaddress must be a pointer and not '" + 4020 getTypeString(ExpectedTy) + "'"); 4021 FwdDeclAS = ExpectedTy->getPointerAddressSpace(); 4022 } else if (PFS) { 4023 // Otherwise, we default the address space of the current function. 4024 FwdDeclAS = PFS->getFunction().getAddressSpace(); 4025 } else { 4026 llvm_unreachable("Unknown address space for blockaddress"); 4027 } 4028 FwdRef = new GlobalVariable( 4029 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage, 4030 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS); 4031 } 4032 4033 ID.ConstantVal = FwdRef; 4034 ID.Kind = ValID::t_Constant; 4035 return false; 4036 } 4037 4038 // We found the function; now find the basic block. Don't use PFS, since we 4039 // might be inside a constant expression. 4040 BasicBlock *BB; 4041 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) { 4042 if (Label.Kind == ValID::t_LocalID) 4043 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc); 4044 else 4045 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc); 4046 if (!BB) 4047 return error(Label.Loc, "referenced value is not a basic block"); 4048 } else { 4049 if (Label.Kind == ValID::t_LocalID) 4050 return error(Label.Loc, "cannot take address of numeric label after " 4051 "the function is defined"); 4052 BB = dyn_cast_or_null<BasicBlock>( 4053 F->getValueSymbolTable()->lookup(Label.StrVal)); 4054 if (!BB) 4055 return error(Label.Loc, "referenced value is not a basic block"); 4056 } 4057 4058 ID.ConstantVal = BlockAddress::get(F, BB); 4059 ID.Kind = ValID::t_Constant; 4060 return false; 4061 } 4062 4063 case lltok::kw_dso_local_equivalent: { 4064 // ValID ::= 'dso_local_equivalent' @foo 4065 Lex.Lex(); 4066 4067 ValID Fn; 4068 4069 if (parseValID(Fn, PFS)) 4070 return true; 4071 4072 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName) 4073 return error(Fn.Loc, 4074 "expected global value name in dso_local_equivalent"); 4075 4076 // Try to find the function (but skip it if it's forward-referenced). 4077 GlobalValue *GV = nullptr; 4078 if (Fn.Kind == ValID::t_GlobalID) { 4079 GV = NumberedVals.get(Fn.UIntVal); 4080 } else if (!ForwardRefVals.count(Fn.StrVal)) { 4081 GV = M->getNamedValue(Fn.StrVal); 4082 } 4083 4084 if (!GV) { 4085 // Make a placeholder global variable as a placeholder for this reference. 4086 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID) 4087 ? ForwardRefDSOLocalEquivalentIDs 4088 : ForwardRefDSOLocalEquivalentNames; 4089 GlobalValue *&FwdRef = FwdRefMap[Fn]; 4090 if (!FwdRef) { 4091 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false, 4092 GlobalValue::InternalLinkage, nullptr, "", 4093 nullptr, GlobalValue::NotThreadLocal); 4094 } 4095 4096 ID.ConstantVal = FwdRef; 4097 ID.Kind = ValID::t_Constant; 4098 return false; 4099 } 4100 4101 if (!GV->getValueType()->isFunctionTy()) 4102 return error(Fn.Loc, "expected a function, alias to function, or ifunc " 4103 "in dso_local_equivalent"); 4104 4105 ID.ConstantVal = DSOLocalEquivalent::get(GV); 4106 ID.Kind = ValID::t_Constant; 4107 return false; 4108 } 4109 4110 case lltok::kw_no_cfi: { 4111 // ValID ::= 'no_cfi' @foo 4112 Lex.Lex(); 4113 4114 if (parseValID(ID, PFS)) 4115 return true; 4116 4117 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName) 4118 return error(ID.Loc, "expected global value name in no_cfi"); 4119 4120 ID.NoCFI = true; 4121 return false; 4122 } 4123 case lltok::kw_ptrauth: { 4124 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key> 4125 // (',' i64 <disc> (',' ptr addrdisc)? )? ')' 4126 Lex.Lex(); 4127 4128 Constant *Ptr, *Key; 4129 Constant *Disc = nullptr, *AddrDisc = nullptr; 4130 4131 if (parseToken(lltok::lparen, 4132 "expected '(' in constant ptrauth expression") || 4133 parseGlobalTypeAndValue(Ptr) || 4134 parseToken(lltok::comma, 4135 "expected comma in constant ptrauth expression") || 4136 parseGlobalTypeAndValue(Key)) 4137 return true; 4138 // If present, parse the optional disc/addrdisc. 4139 if (EatIfPresent(lltok::comma)) 4140 if (parseGlobalTypeAndValue(Disc) || 4141 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))) 4142 return true; 4143 if (parseToken(lltok::rparen, 4144 "expected ')' in constant ptrauth expression")) 4145 return true; 4146 4147 if (!Ptr->getType()->isPointerTy()) 4148 return error(ID.Loc, "constant ptrauth base pointer must be a pointer"); 4149 4150 auto *KeyC = dyn_cast<ConstantInt>(Key); 4151 if (!KeyC || KeyC->getBitWidth() != 32) 4152 return error(ID.Loc, "constant ptrauth key must be i32 constant"); 4153 4154 ConstantInt *DiscC = nullptr; 4155 if (Disc) { 4156 DiscC = dyn_cast<ConstantInt>(Disc); 4157 if (!DiscC || DiscC->getBitWidth() != 64) 4158 return error( 4159 ID.Loc, 4160 "constant ptrauth integer discriminator must be i64 constant"); 4161 } else { 4162 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0); 4163 } 4164 4165 if (AddrDisc) { 4166 if (!AddrDisc->getType()->isPointerTy()) 4167 return error( 4168 ID.Loc, "constant ptrauth address discriminator must be a pointer"); 4169 } else { 4170 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0)); 4171 } 4172 4173 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc); 4174 ID.Kind = ValID::t_Constant; 4175 return false; 4176 } 4177 4178 case lltok::kw_trunc: 4179 case lltok::kw_bitcast: 4180 case lltok::kw_addrspacecast: 4181 case lltok::kw_inttoptr: 4182 case lltok::kw_ptrtoint: { 4183 unsigned Opc = Lex.getUIntVal(); 4184 Type *DestTy = nullptr; 4185 Constant *SrcVal; 4186 Lex.Lex(); 4187 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") || 4188 parseGlobalTypeAndValue(SrcVal) || 4189 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") || 4190 parseType(DestTy) || 4191 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast")) 4192 return true; 4193 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy)) 4194 return error(ID.Loc, "invalid cast opcode for cast from '" + 4195 getTypeString(SrcVal->getType()) + "' to '" + 4196 getTypeString(DestTy) + "'"); 4197 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, 4198 SrcVal, DestTy); 4199 ID.Kind = ValID::t_Constant; 4200 return false; 4201 } 4202 case lltok::kw_extractvalue: 4203 return error(ID.Loc, "extractvalue constexprs are no longer supported"); 4204 case lltok::kw_insertvalue: 4205 return error(ID.Loc, "insertvalue constexprs are no longer supported"); 4206 case lltok::kw_udiv: 4207 return error(ID.Loc, "udiv constexprs are no longer supported"); 4208 case lltok::kw_sdiv: 4209 return error(ID.Loc, "sdiv constexprs are no longer supported"); 4210 case lltok::kw_urem: 4211 return error(ID.Loc, "urem constexprs are no longer supported"); 4212 case lltok::kw_srem: 4213 return error(ID.Loc, "srem constexprs are no longer supported"); 4214 case lltok::kw_fadd: 4215 return error(ID.Loc, "fadd constexprs are no longer supported"); 4216 case lltok::kw_fsub: 4217 return error(ID.Loc, "fsub constexprs are no longer supported"); 4218 case lltok::kw_fmul: 4219 return error(ID.Loc, "fmul constexprs are no longer supported"); 4220 case lltok::kw_fdiv: 4221 return error(ID.Loc, "fdiv constexprs are no longer supported"); 4222 case lltok::kw_frem: 4223 return error(ID.Loc, "frem constexprs are no longer supported"); 4224 case lltok::kw_and: 4225 return error(ID.Loc, "and constexprs are no longer supported"); 4226 case lltok::kw_or: 4227 return error(ID.Loc, "or constexprs are no longer supported"); 4228 case lltok::kw_lshr: 4229 return error(ID.Loc, "lshr constexprs are no longer supported"); 4230 case lltok::kw_ashr: 4231 return error(ID.Loc, "ashr constexprs are no longer supported"); 4232 case lltok::kw_shl: 4233 return error(ID.Loc, "shl constexprs are no longer supported"); 4234 case lltok::kw_fneg: 4235 return error(ID.Loc, "fneg constexprs are no longer supported"); 4236 case lltok::kw_select: 4237 return error(ID.Loc, "select constexprs are no longer supported"); 4238 case lltok::kw_zext: 4239 return error(ID.Loc, "zext constexprs are no longer supported"); 4240 case lltok::kw_sext: 4241 return error(ID.Loc, "sext constexprs are no longer supported"); 4242 case lltok::kw_fptrunc: 4243 return error(ID.Loc, "fptrunc constexprs are no longer supported"); 4244 case lltok::kw_fpext: 4245 return error(ID.Loc, "fpext constexprs are no longer supported"); 4246 case lltok::kw_uitofp: 4247 return error(ID.Loc, "uitofp constexprs are no longer supported"); 4248 case lltok::kw_sitofp: 4249 return error(ID.Loc, "sitofp constexprs are no longer supported"); 4250 case lltok::kw_fptoui: 4251 return error(ID.Loc, "fptoui constexprs are no longer supported"); 4252 case lltok::kw_fptosi: 4253 return error(ID.Loc, "fptosi constexprs are no longer supported"); 4254 case lltok::kw_icmp: 4255 return error(ID.Loc, "icmp constexprs are no longer supported"); 4256 case lltok::kw_fcmp: 4257 return error(ID.Loc, "fcmp constexprs are no longer supported"); 4258 4259 // Binary Operators. 4260 case lltok::kw_add: 4261 case lltok::kw_sub: 4262 case lltok::kw_mul: 4263 case lltok::kw_xor: { 4264 bool NUW = false; 4265 bool NSW = false; 4266 unsigned Opc = Lex.getUIntVal(); 4267 Constant *Val0, *Val1; 4268 Lex.Lex(); 4269 if (Opc == Instruction::Add || Opc == Instruction::Sub || 4270 Opc == Instruction::Mul) { 4271 if (EatIfPresent(lltok::kw_nuw)) 4272 NUW = true; 4273 if (EatIfPresent(lltok::kw_nsw)) { 4274 NSW = true; 4275 if (EatIfPresent(lltok::kw_nuw)) 4276 NUW = true; 4277 } 4278 } 4279 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") || 4280 parseGlobalTypeAndValue(Val0) || 4281 parseToken(lltok::comma, "expected comma in binary constantexpr") || 4282 parseGlobalTypeAndValue(Val1) || 4283 parseToken(lltok::rparen, "expected ')' in binary constantexpr")) 4284 return true; 4285 if (Val0->getType() != Val1->getType()) 4286 return error(ID.Loc, "operands of constexpr must have same type"); 4287 // Check that the type is valid for the operator. 4288 if (!Val0->getType()->isIntOrIntVectorTy()) 4289 return error(ID.Loc, 4290 "constexpr requires integer or integer vector operands"); 4291 unsigned Flags = 0; 4292 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 4293 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap; 4294 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags); 4295 ID.Kind = ValID::t_Constant; 4296 return false; 4297 } 4298 4299 case lltok::kw_splat: { 4300 Lex.Lex(); 4301 if (parseToken(lltok::lparen, "expected '(' after vector splat")) 4302 return true; 4303 Constant *C; 4304 if (parseGlobalTypeAndValue(C)) 4305 return true; 4306 if (parseToken(lltok::rparen, "expected ')' at end of vector splat")) 4307 return true; 4308 4309 ID.ConstantVal = C; 4310 ID.Kind = ValID::t_ConstantSplat; 4311 return false; 4312 } 4313 4314 case lltok::kw_getelementptr: 4315 case lltok::kw_shufflevector: 4316 case lltok::kw_insertelement: 4317 case lltok::kw_extractelement: { 4318 unsigned Opc = Lex.getUIntVal(); 4319 SmallVector<Constant*, 16> Elts; 4320 GEPNoWrapFlags NW; 4321 bool HasInRange = false; 4322 APSInt InRangeStart; 4323 APSInt InRangeEnd; 4324 Type *Ty; 4325 Lex.Lex(); 4326 4327 if (Opc == Instruction::GetElementPtr) { 4328 while (true) { 4329 if (EatIfPresent(lltok::kw_inbounds)) 4330 NW |= GEPNoWrapFlags::inBounds(); 4331 else if (EatIfPresent(lltok::kw_nusw)) 4332 NW |= GEPNoWrapFlags::noUnsignedSignedWrap(); 4333 else if (EatIfPresent(lltok::kw_nuw)) 4334 NW |= GEPNoWrapFlags::noUnsignedWrap(); 4335 else 4336 break; 4337 } 4338 4339 if (EatIfPresent(lltok::kw_inrange)) { 4340 if (parseToken(lltok::lparen, "expected '('")) 4341 return true; 4342 if (Lex.getKind() != lltok::APSInt) 4343 return tokError("expected integer"); 4344 InRangeStart = Lex.getAPSIntVal(); 4345 Lex.Lex(); 4346 if (parseToken(lltok::comma, "expected ','")) 4347 return true; 4348 if (Lex.getKind() != lltok::APSInt) 4349 return tokError("expected integer"); 4350 InRangeEnd = Lex.getAPSIntVal(); 4351 Lex.Lex(); 4352 if (parseToken(lltok::rparen, "expected ')'")) 4353 return true; 4354 HasInRange = true; 4355 } 4356 } 4357 4358 if (parseToken(lltok::lparen, "expected '(' in constantexpr")) 4359 return true; 4360 4361 if (Opc == Instruction::GetElementPtr) { 4362 if (parseType(Ty) || 4363 parseToken(lltok::comma, "expected comma after getelementptr's type")) 4364 return true; 4365 } 4366 4367 if (parseGlobalValueVector(Elts) || 4368 parseToken(lltok::rparen, "expected ')' in constantexpr")) 4369 return true; 4370 4371 if (Opc == Instruction::GetElementPtr) { 4372 if (Elts.size() == 0 || 4373 !Elts[0]->getType()->isPtrOrPtrVectorTy()) 4374 return error(ID.Loc, "base of getelementptr must be a pointer"); 4375 4376 Type *BaseType = Elts[0]->getType(); 4377 std::optional<ConstantRange> InRange; 4378 if (HasInRange) { 4379 unsigned IndexWidth = 4380 M->getDataLayout().getIndexTypeSizeInBits(BaseType); 4381 InRangeStart = InRangeStart.extOrTrunc(IndexWidth); 4382 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth); 4383 if (InRangeStart.sge(InRangeEnd)) 4384 return error(ID.Loc, "expected end to be larger than start"); 4385 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd); 4386 } 4387 4388 unsigned GEPWidth = 4389 BaseType->isVectorTy() 4390 ? cast<FixedVectorType>(BaseType)->getNumElements() 4391 : 0; 4392 4393 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 4394 for (Constant *Val : Indices) { 4395 Type *ValTy = Val->getType(); 4396 if (!ValTy->isIntOrIntVectorTy()) 4397 return error(ID.Loc, "getelementptr index must be an integer"); 4398 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) { 4399 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements(); 4400 if (GEPWidth && (ValNumEl != GEPWidth)) 4401 return error( 4402 ID.Loc, 4403 "getelementptr vector index has a wrong number of elements"); 4404 // GEPWidth may have been unknown because the base is a scalar, 4405 // but it is known now. 4406 GEPWidth = ValNumEl; 4407 } 4408 } 4409 4410 SmallPtrSet<Type*, 4> Visited; 4411 if (!Indices.empty() && !Ty->isSized(&Visited)) 4412 return error(ID.Loc, "base element of getelementptr must be sized"); 4413 4414 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 4415 return error(ID.Loc, "invalid getelementptr indices"); 4416 4417 ID.ConstantVal = 4418 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange); 4419 } else if (Opc == Instruction::ShuffleVector) { 4420 if (Elts.size() != 3) 4421 return error(ID.Loc, "expected three operands to shufflevector"); 4422 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 4423 return error(ID.Loc, "invalid operands to shufflevector"); 4424 SmallVector<int, 16> Mask; 4425 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask); 4426 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask); 4427 } else if (Opc == Instruction::ExtractElement) { 4428 if (Elts.size() != 2) 4429 return error(ID.Loc, "expected two operands to extractelement"); 4430 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1])) 4431 return error(ID.Loc, "invalid extractelement operands"); 4432 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]); 4433 } else { 4434 assert(Opc == Instruction::InsertElement && "Unknown opcode"); 4435 if (Elts.size() != 3) 4436 return error(ID.Loc, "expected three operands to insertelement"); 4437 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2])) 4438 return error(ID.Loc, "invalid insertelement operands"); 4439 ID.ConstantVal = 4440 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]); 4441 } 4442 4443 ID.Kind = ValID::t_Constant; 4444 return false; 4445 } 4446 } 4447 4448 Lex.Lex(); 4449 return false; 4450 } 4451 4452 /// parseGlobalValue - parse a global value with the specified type. 4453 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) { 4454 C = nullptr; 4455 ValID ID; 4456 Value *V = nullptr; 4457 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) || 4458 convertValIDToValue(Ty, ID, V, nullptr); 4459 if (V && !(C = dyn_cast<Constant>(V))) 4460 return error(ID.Loc, "global values must be constants"); 4461 return Parsed; 4462 } 4463 4464 bool LLParser::parseGlobalTypeAndValue(Constant *&V) { 4465 Type *Ty = nullptr; 4466 return parseType(Ty) || parseGlobalValue(Ty, V); 4467 } 4468 4469 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) { 4470 C = nullptr; 4471 4472 LocTy KwLoc = Lex.getLoc(); 4473 if (!EatIfPresent(lltok::kw_comdat)) 4474 return false; 4475 4476 if (EatIfPresent(lltok::lparen)) { 4477 if (Lex.getKind() != lltok::ComdatVar) 4478 return tokError("expected comdat variable"); 4479 C = getComdat(Lex.getStrVal(), Lex.getLoc()); 4480 Lex.Lex(); 4481 if (parseToken(lltok::rparen, "expected ')' after comdat var")) 4482 return true; 4483 } else { 4484 if (GlobalName.empty()) 4485 return tokError("comdat cannot be unnamed"); 4486 C = getComdat(std::string(GlobalName), KwLoc); 4487 } 4488 4489 return false; 4490 } 4491 4492 /// parseGlobalValueVector 4493 /// ::= /*empty*/ 4494 /// ::= TypeAndValue (',' TypeAndValue)* 4495 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) { 4496 // Empty list. 4497 if (Lex.getKind() == lltok::rbrace || 4498 Lex.getKind() == lltok::rsquare || 4499 Lex.getKind() == lltok::greater || 4500 Lex.getKind() == lltok::rparen) 4501 return false; 4502 4503 do { 4504 // Let the caller deal with inrange. 4505 if (Lex.getKind() == lltok::kw_inrange) 4506 return false; 4507 4508 Constant *C; 4509 if (parseGlobalTypeAndValue(C)) 4510 return true; 4511 Elts.push_back(C); 4512 } while (EatIfPresent(lltok::comma)); 4513 4514 return false; 4515 } 4516 4517 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) { 4518 SmallVector<Metadata *, 16> Elts; 4519 if (parseMDNodeVector(Elts)) 4520 return true; 4521 4522 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts); 4523 return false; 4524 } 4525 4526 /// MDNode: 4527 /// ::= !{ ... } 4528 /// ::= !7 4529 /// ::= !DILocation(...) 4530 bool LLParser::parseMDNode(MDNode *&N) { 4531 if (Lex.getKind() == lltok::MetadataVar) 4532 return parseSpecializedMDNode(N); 4533 4534 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N); 4535 } 4536 4537 bool LLParser::parseMDNodeTail(MDNode *&N) { 4538 // !{ ... } 4539 if (Lex.getKind() == lltok::lbrace) 4540 return parseMDTuple(N); 4541 4542 // !42 4543 return parseMDNodeID(N); 4544 } 4545 4546 namespace { 4547 4548 /// Structure to represent an optional metadata field. 4549 template <class FieldTy> struct MDFieldImpl { 4550 typedef MDFieldImpl ImplTy; 4551 FieldTy Val; 4552 bool Seen; 4553 4554 void assign(FieldTy Val) { 4555 Seen = true; 4556 this->Val = std::move(Val); 4557 } 4558 4559 explicit MDFieldImpl(FieldTy Default) 4560 : Val(std::move(Default)), Seen(false) {} 4561 }; 4562 4563 /// Structure to represent an optional metadata field that 4564 /// can be of either type (A or B) and encapsulates the 4565 /// MD<typeofA>Field and MD<typeofB>Field structs, so not 4566 /// to reimplement the specifics for representing each Field. 4567 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl { 4568 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy; 4569 FieldTypeA A; 4570 FieldTypeB B; 4571 bool Seen; 4572 4573 enum { 4574 IsInvalid = 0, 4575 IsTypeA = 1, 4576 IsTypeB = 2 4577 } WhatIs; 4578 4579 void assign(FieldTypeA A) { 4580 Seen = true; 4581 this->A = std::move(A); 4582 WhatIs = IsTypeA; 4583 } 4584 4585 void assign(FieldTypeB B) { 4586 Seen = true; 4587 this->B = std::move(B); 4588 WhatIs = IsTypeB; 4589 } 4590 4591 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB) 4592 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false), 4593 WhatIs(IsInvalid) {} 4594 }; 4595 4596 struct MDUnsignedField : public MDFieldImpl<uint64_t> { 4597 uint64_t Max; 4598 4599 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX) 4600 : ImplTy(Default), Max(Max) {} 4601 }; 4602 4603 struct LineField : public MDUnsignedField { 4604 LineField() : MDUnsignedField(0, UINT32_MAX) {} 4605 }; 4606 4607 struct ColumnField : public MDUnsignedField { 4608 ColumnField() : MDUnsignedField(0, UINT16_MAX) {} 4609 }; 4610 4611 struct DwarfTagField : public MDUnsignedField { 4612 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {} 4613 DwarfTagField(dwarf::Tag DefaultTag) 4614 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {} 4615 }; 4616 4617 struct DwarfMacinfoTypeField : public MDUnsignedField { 4618 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {} 4619 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType) 4620 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {} 4621 }; 4622 4623 struct DwarfAttEncodingField : public MDUnsignedField { 4624 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {} 4625 }; 4626 4627 struct DwarfVirtualityField : public MDUnsignedField { 4628 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {} 4629 }; 4630 4631 struct DwarfLangField : public MDUnsignedField { 4632 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {} 4633 }; 4634 4635 struct DwarfCCField : public MDUnsignedField { 4636 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {} 4637 }; 4638 4639 struct EmissionKindField : public MDUnsignedField { 4640 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {} 4641 }; 4642 4643 struct NameTableKindField : public MDUnsignedField { 4644 NameTableKindField() 4645 : MDUnsignedField( 4646 0, (unsigned) 4647 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {} 4648 }; 4649 4650 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> { 4651 DIFlagField() : MDFieldImpl(DINode::FlagZero) {} 4652 }; 4653 4654 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> { 4655 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {} 4656 }; 4657 4658 struct MDAPSIntField : public MDFieldImpl<APSInt> { 4659 MDAPSIntField() : ImplTy(APSInt()) {} 4660 }; 4661 4662 struct MDSignedField : public MDFieldImpl<int64_t> { 4663 int64_t Min = INT64_MIN; 4664 int64_t Max = INT64_MAX; 4665 4666 MDSignedField(int64_t Default = 0) 4667 : ImplTy(Default) {} 4668 MDSignedField(int64_t Default, int64_t Min, int64_t Max) 4669 : ImplTy(Default), Min(Min), Max(Max) {} 4670 }; 4671 4672 struct MDBoolField : public MDFieldImpl<bool> { 4673 MDBoolField(bool Default = false) : ImplTy(Default) {} 4674 }; 4675 4676 struct MDField : public MDFieldImpl<Metadata *> { 4677 bool AllowNull; 4678 4679 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {} 4680 }; 4681 4682 struct MDStringField : public MDFieldImpl<MDString *> { 4683 bool AllowEmpty; 4684 MDStringField(bool AllowEmpty = true) 4685 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {} 4686 }; 4687 4688 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> { 4689 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {} 4690 }; 4691 4692 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> { 4693 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {} 4694 }; 4695 4696 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> { 4697 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true) 4698 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {} 4699 4700 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max, 4701 bool AllowNull = true) 4702 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {} 4703 4704 bool isMDSignedField() const { return WhatIs == IsTypeA; } 4705 bool isMDField() const { return WhatIs == IsTypeB; } 4706 int64_t getMDSignedValue() const { 4707 assert(isMDSignedField() && "Wrong field type"); 4708 return A.Val; 4709 } 4710 Metadata *getMDFieldValue() const { 4711 assert(isMDField() && "Wrong field type"); 4712 return B.Val; 4713 } 4714 }; 4715 4716 } // end anonymous namespace 4717 4718 namespace llvm { 4719 4720 template <> 4721 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) { 4722 if (Lex.getKind() != lltok::APSInt) 4723 return tokError("expected integer"); 4724 4725 Result.assign(Lex.getAPSIntVal()); 4726 Lex.Lex(); 4727 return false; 4728 } 4729 4730 template <> 4731 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4732 MDUnsignedField &Result) { 4733 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 4734 return tokError("expected unsigned integer"); 4735 4736 auto &U = Lex.getAPSIntVal(); 4737 if (U.ugt(Result.Max)) 4738 return tokError("value for '" + Name + "' too large, limit is " + 4739 Twine(Result.Max)); 4740 Result.assign(U.getZExtValue()); 4741 assert(Result.Val <= Result.Max && "Expected value in range"); 4742 Lex.Lex(); 4743 return false; 4744 } 4745 4746 template <> 4747 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) { 4748 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4749 } 4750 template <> 4751 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) { 4752 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4753 } 4754 4755 template <> 4756 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) { 4757 if (Lex.getKind() == lltok::APSInt) 4758 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4759 4760 if (Lex.getKind() != lltok::DwarfTag) 4761 return tokError("expected DWARF tag"); 4762 4763 unsigned Tag = dwarf::getTag(Lex.getStrVal()); 4764 if (Tag == dwarf::DW_TAG_invalid) 4765 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'"); 4766 assert(Tag <= Result.Max && "Expected valid DWARF tag"); 4767 4768 Result.assign(Tag); 4769 Lex.Lex(); 4770 return false; 4771 } 4772 4773 template <> 4774 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4775 DwarfMacinfoTypeField &Result) { 4776 if (Lex.getKind() == lltok::APSInt) 4777 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4778 4779 if (Lex.getKind() != lltok::DwarfMacinfo) 4780 return tokError("expected DWARF macinfo type"); 4781 4782 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal()); 4783 if (Macinfo == dwarf::DW_MACINFO_invalid) 4784 return tokError("invalid DWARF macinfo type" + Twine(" '") + 4785 Lex.getStrVal() + "'"); 4786 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type"); 4787 4788 Result.assign(Macinfo); 4789 Lex.Lex(); 4790 return false; 4791 } 4792 4793 template <> 4794 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4795 DwarfVirtualityField &Result) { 4796 if (Lex.getKind() == lltok::APSInt) 4797 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4798 4799 if (Lex.getKind() != lltok::DwarfVirtuality) 4800 return tokError("expected DWARF virtuality code"); 4801 4802 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal()); 4803 if (Virtuality == dwarf::DW_VIRTUALITY_invalid) 4804 return tokError("invalid DWARF virtuality code" + Twine(" '") + 4805 Lex.getStrVal() + "'"); 4806 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code"); 4807 Result.assign(Virtuality); 4808 Lex.Lex(); 4809 return false; 4810 } 4811 4812 template <> 4813 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) { 4814 if (Lex.getKind() == lltok::APSInt) 4815 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4816 4817 if (Lex.getKind() != lltok::DwarfLang) 4818 return tokError("expected DWARF language"); 4819 4820 unsigned Lang = dwarf::getLanguage(Lex.getStrVal()); 4821 if (!Lang) 4822 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() + 4823 "'"); 4824 assert(Lang <= Result.Max && "Expected valid DWARF language"); 4825 Result.assign(Lang); 4826 Lex.Lex(); 4827 return false; 4828 } 4829 4830 template <> 4831 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) { 4832 if (Lex.getKind() == lltok::APSInt) 4833 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4834 4835 if (Lex.getKind() != lltok::DwarfCC) 4836 return tokError("expected DWARF calling convention"); 4837 4838 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal()); 4839 if (!CC) 4840 return tokError("invalid DWARF calling convention" + Twine(" '") + 4841 Lex.getStrVal() + "'"); 4842 assert(CC <= Result.Max && "Expected valid DWARF calling convention"); 4843 Result.assign(CC); 4844 Lex.Lex(); 4845 return false; 4846 } 4847 4848 template <> 4849 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4850 EmissionKindField &Result) { 4851 if (Lex.getKind() == lltok::APSInt) 4852 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4853 4854 if (Lex.getKind() != lltok::EmissionKind) 4855 return tokError("expected emission kind"); 4856 4857 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal()); 4858 if (!Kind) 4859 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() + 4860 "'"); 4861 assert(*Kind <= Result.Max && "Expected valid emission kind"); 4862 Result.assign(*Kind); 4863 Lex.Lex(); 4864 return false; 4865 } 4866 4867 template <> 4868 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4869 NameTableKindField &Result) { 4870 if (Lex.getKind() == lltok::APSInt) 4871 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4872 4873 if (Lex.getKind() != lltok::NameTableKind) 4874 return tokError("expected nameTable kind"); 4875 4876 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal()); 4877 if (!Kind) 4878 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() + 4879 "'"); 4880 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind"); 4881 Result.assign((unsigned)*Kind); 4882 Lex.Lex(); 4883 return false; 4884 } 4885 4886 template <> 4887 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 4888 DwarfAttEncodingField &Result) { 4889 if (Lex.getKind() == lltok::APSInt) 4890 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result)); 4891 4892 if (Lex.getKind() != lltok::DwarfAttEncoding) 4893 return tokError("expected DWARF type attribute encoding"); 4894 4895 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal()); 4896 if (!Encoding) 4897 return tokError("invalid DWARF type attribute encoding" + Twine(" '") + 4898 Lex.getStrVal() + "'"); 4899 assert(Encoding <= Result.Max && "Expected valid DWARF language"); 4900 Result.assign(Encoding); 4901 Lex.Lex(); 4902 return false; 4903 } 4904 4905 /// DIFlagField 4906 /// ::= uint32 4907 /// ::= DIFlagVector 4908 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic 4909 template <> 4910 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) { 4911 4912 // parser for a single flag. 4913 auto parseFlag = [&](DINode::DIFlags &Val) { 4914 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4915 uint32_t TempVal = static_cast<uint32_t>(Val); 4916 bool Res = parseUInt32(TempVal); 4917 Val = static_cast<DINode::DIFlags>(TempVal); 4918 return Res; 4919 } 4920 4921 if (Lex.getKind() != lltok::DIFlag) 4922 return tokError("expected debug info flag"); 4923 4924 Val = DINode::getFlag(Lex.getStrVal()); 4925 if (!Val) 4926 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() + 4927 "'"); 4928 Lex.Lex(); 4929 return false; 4930 }; 4931 4932 // parse the flags and combine them together. 4933 DINode::DIFlags Combined = DINode::FlagZero; 4934 do { 4935 DINode::DIFlags Val; 4936 if (parseFlag(Val)) 4937 return true; 4938 Combined |= Val; 4939 } while (EatIfPresent(lltok::bar)); 4940 4941 Result.assign(Combined); 4942 return false; 4943 } 4944 4945 /// DISPFlagField 4946 /// ::= uint32 4947 /// ::= DISPFlagVector 4948 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32 4949 template <> 4950 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) { 4951 4952 // parser for a single flag. 4953 auto parseFlag = [&](DISubprogram::DISPFlags &Val) { 4954 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) { 4955 uint32_t TempVal = static_cast<uint32_t>(Val); 4956 bool Res = parseUInt32(TempVal); 4957 Val = static_cast<DISubprogram::DISPFlags>(TempVal); 4958 return Res; 4959 } 4960 4961 if (Lex.getKind() != lltok::DISPFlag) 4962 return tokError("expected debug info flag"); 4963 4964 Val = DISubprogram::getFlag(Lex.getStrVal()); 4965 if (!Val) 4966 return tokError(Twine("invalid subprogram debug info flag '") + 4967 Lex.getStrVal() + "'"); 4968 Lex.Lex(); 4969 return false; 4970 }; 4971 4972 // parse the flags and combine them together. 4973 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero; 4974 do { 4975 DISubprogram::DISPFlags Val; 4976 if (parseFlag(Val)) 4977 return true; 4978 Combined |= Val; 4979 } while (EatIfPresent(lltok::bar)); 4980 4981 Result.assign(Combined); 4982 return false; 4983 } 4984 4985 template <> 4986 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) { 4987 if (Lex.getKind() != lltok::APSInt) 4988 return tokError("expected signed integer"); 4989 4990 auto &S = Lex.getAPSIntVal(); 4991 if (S < Result.Min) 4992 return tokError("value for '" + Name + "' too small, limit is " + 4993 Twine(Result.Min)); 4994 if (S > Result.Max) 4995 return tokError("value for '" + Name + "' too large, limit is " + 4996 Twine(Result.Max)); 4997 Result.assign(S.getExtValue()); 4998 assert(Result.Val >= Result.Min && "Expected value in range"); 4999 assert(Result.Val <= Result.Max && "Expected value in range"); 5000 Lex.Lex(); 5001 return false; 5002 } 5003 5004 template <> 5005 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) { 5006 switch (Lex.getKind()) { 5007 default: 5008 return tokError("expected 'true' or 'false'"); 5009 case lltok::kw_true: 5010 Result.assign(true); 5011 break; 5012 case lltok::kw_false: 5013 Result.assign(false); 5014 break; 5015 } 5016 Lex.Lex(); 5017 return false; 5018 } 5019 5020 template <> 5021 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) { 5022 if (Lex.getKind() == lltok::kw_null) { 5023 if (!Result.AllowNull) 5024 return tokError("'" + Name + "' cannot be null"); 5025 Lex.Lex(); 5026 Result.assign(nullptr); 5027 return false; 5028 } 5029 5030 Metadata *MD; 5031 if (parseMetadata(MD, nullptr)) 5032 return true; 5033 5034 Result.assign(MD); 5035 return false; 5036 } 5037 5038 template <> 5039 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 5040 MDSignedOrMDField &Result) { 5041 // Try to parse a signed int. 5042 if (Lex.getKind() == lltok::APSInt) { 5043 MDSignedField Res = Result.A; 5044 if (!parseMDField(Loc, Name, Res)) { 5045 Result.assign(Res); 5046 return false; 5047 } 5048 return true; 5049 } 5050 5051 // Otherwise, try to parse as an MDField. 5052 MDField Res = Result.B; 5053 if (!parseMDField(Loc, Name, Res)) { 5054 Result.assign(Res); 5055 return false; 5056 } 5057 5058 return true; 5059 } 5060 5061 template <> 5062 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) { 5063 LocTy ValueLoc = Lex.getLoc(); 5064 std::string S; 5065 if (parseStringConstant(S)) 5066 return true; 5067 5068 if (!Result.AllowEmpty && S.empty()) 5069 return error(ValueLoc, "'" + Name + "' cannot be empty"); 5070 5071 Result.assign(S.empty() ? nullptr : MDString::get(Context, S)); 5072 return false; 5073 } 5074 5075 template <> 5076 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) { 5077 SmallVector<Metadata *, 4> MDs; 5078 if (parseMDNodeVector(MDs)) 5079 return true; 5080 5081 Result.assign(std::move(MDs)); 5082 return false; 5083 } 5084 5085 template <> 5086 bool LLParser::parseMDField(LocTy Loc, StringRef Name, 5087 ChecksumKindField &Result) { 5088 std::optional<DIFile::ChecksumKind> CSKind = 5089 DIFile::getChecksumKind(Lex.getStrVal()); 5090 5091 if (Lex.getKind() != lltok::ChecksumKind || !CSKind) 5092 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() + 5093 "'"); 5094 5095 Result.assign(*CSKind); 5096 Lex.Lex(); 5097 return false; 5098 } 5099 5100 } // end namespace llvm 5101 5102 template <class ParserTy> 5103 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) { 5104 do { 5105 if (Lex.getKind() != lltok::LabelStr) 5106 return tokError("expected field label here"); 5107 5108 if (ParseField()) 5109 return true; 5110 } while (EatIfPresent(lltok::comma)); 5111 5112 return false; 5113 } 5114 5115 template <class ParserTy> 5116 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) { 5117 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5118 Lex.Lex(); 5119 5120 if (parseToken(lltok::lparen, "expected '(' here")) 5121 return true; 5122 if (Lex.getKind() != lltok::rparen) 5123 if (parseMDFieldsImplBody(ParseField)) 5124 return true; 5125 5126 ClosingLoc = Lex.getLoc(); 5127 return parseToken(lltok::rparen, "expected ')' here"); 5128 } 5129 5130 template <class FieldTy> 5131 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) { 5132 if (Result.Seen) 5133 return tokError("field '" + Name + "' cannot be specified more than once"); 5134 5135 LocTy Loc = Lex.getLoc(); 5136 Lex.Lex(); 5137 return parseMDField(Loc, Name, Result); 5138 } 5139 5140 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) { 5141 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5142 5143 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 5144 if (Lex.getStrVal() == #CLASS) \ 5145 return parse##CLASS(N, IsDistinct); 5146 #include "llvm/IR/Metadata.def" 5147 5148 return tokError("expected metadata type"); 5149 } 5150 5151 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT 5152 #define NOP_FIELD(NAME, TYPE, INIT) 5153 #define REQUIRE_FIELD(NAME, TYPE, INIT) \ 5154 if (!NAME.Seen) \ 5155 return error(ClosingLoc, "missing required field '" #NAME "'"); 5156 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \ 5157 if (Lex.getStrVal() == #NAME) \ 5158 return parseMDField(#NAME, NAME); 5159 #define PARSE_MD_FIELDS() \ 5160 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \ 5161 do { \ 5162 LocTy ClosingLoc; \ 5163 if (parseMDFieldsImpl( \ 5164 [&]() -> bool { \ 5165 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \ 5166 return tokError(Twine("invalid field '") + Lex.getStrVal() + \ 5167 "'"); \ 5168 }, \ 5169 ClosingLoc)) \ 5170 return true; \ 5171 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \ 5172 } while (false) 5173 #define GET_OR_DISTINCT(CLASS, ARGS) \ 5174 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 5175 5176 /// parseDILocationFields: 5177 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6, 5178 /// isImplicitCode: true) 5179 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) { 5180 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5181 OPTIONAL(line, LineField, ); \ 5182 OPTIONAL(column, ColumnField, ); \ 5183 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5184 OPTIONAL(inlinedAt, MDField, ); \ 5185 OPTIONAL(isImplicitCode, MDBoolField, (false)); 5186 PARSE_MD_FIELDS(); 5187 #undef VISIT_MD_FIELDS 5188 5189 Result = 5190 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val, 5191 inlinedAt.Val, isImplicitCode.Val)); 5192 return false; 5193 } 5194 5195 /// parseDIAssignID: 5196 /// ::= distinct !DIAssignID() 5197 bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) { 5198 if (!IsDistinct) 5199 return tokError("missing 'distinct', required for !DIAssignID()"); 5200 5201 Lex.Lex(); 5202 5203 // Now eat the parens. 5204 if (parseToken(lltok::lparen, "expected '(' here")) 5205 return true; 5206 if (parseToken(lltok::rparen, "expected ')' here")) 5207 return true; 5208 5209 Result = DIAssignID::getDistinct(Context); 5210 return false; 5211 } 5212 5213 /// parseGenericDINode: 5214 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...}) 5215 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) { 5216 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5217 REQUIRED(tag, DwarfTagField, ); \ 5218 OPTIONAL(header, MDStringField, ); \ 5219 OPTIONAL(operands, MDFieldList, ); 5220 PARSE_MD_FIELDS(); 5221 #undef VISIT_MD_FIELDS 5222 5223 Result = GET_OR_DISTINCT(GenericDINode, 5224 (Context, tag.Val, header.Val, operands.Val)); 5225 return false; 5226 } 5227 5228 /// parseDISubrange: 5229 /// ::= !DISubrange(count: 30, lowerBound: 2) 5230 /// ::= !DISubrange(count: !node, lowerBound: 2) 5231 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3) 5232 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) { 5233 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5234 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \ 5235 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 5236 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 5237 OPTIONAL(stride, MDSignedOrMDField, ); 5238 PARSE_MD_FIELDS(); 5239 #undef VISIT_MD_FIELDS 5240 5241 Metadata *Count = nullptr; 5242 Metadata *LowerBound = nullptr; 5243 Metadata *UpperBound = nullptr; 5244 Metadata *Stride = nullptr; 5245 5246 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * { 5247 if (Bound.isMDSignedField()) 5248 return ConstantAsMetadata::get(ConstantInt::getSigned( 5249 Type::getInt64Ty(Context), Bound.getMDSignedValue())); 5250 if (Bound.isMDField()) 5251 return Bound.getMDFieldValue(); 5252 return nullptr; 5253 }; 5254 5255 Count = convToMetadata(count); 5256 LowerBound = convToMetadata(lowerBound); 5257 UpperBound = convToMetadata(upperBound); 5258 Stride = convToMetadata(stride); 5259 5260 Result = GET_OR_DISTINCT(DISubrange, 5261 (Context, Count, LowerBound, UpperBound, Stride)); 5262 5263 return false; 5264 } 5265 5266 /// parseDIGenericSubrange: 5267 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride: 5268 /// !node3) 5269 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) { 5270 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5271 OPTIONAL(count, MDSignedOrMDField, ); \ 5272 OPTIONAL(lowerBound, MDSignedOrMDField, ); \ 5273 OPTIONAL(upperBound, MDSignedOrMDField, ); \ 5274 OPTIONAL(stride, MDSignedOrMDField, ); 5275 PARSE_MD_FIELDS(); 5276 #undef VISIT_MD_FIELDS 5277 5278 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * { 5279 if (Bound.isMDSignedField()) 5280 return DIExpression::get( 5281 Context, {dwarf::DW_OP_consts, 5282 static_cast<uint64_t>(Bound.getMDSignedValue())}); 5283 if (Bound.isMDField()) 5284 return Bound.getMDFieldValue(); 5285 return nullptr; 5286 }; 5287 5288 Metadata *Count = ConvToMetadata(count); 5289 Metadata *LowerBound = ConvToMetadata(lowerBound); 5290 Metadata *UpperBound = ConvToMetadata(upperBound); 5291 Metadata *Stride = ConvToMetadata(stride); 5292 5293 Result = GET_OR_DISTINCT(DIGenericSubrange, 5294 (Context, Count, LowerBound, UpperBound, Stride)); 5295 5296 return false; 5297 } 5298 5299 /// parseDIEnumerator: 5300 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind") 5301 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) { 5302 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5303 REQUIRED(name, MDStringField, ); \ 5304 REQUIRED(value, MDAPSIntField, ); \ 5305 OPTIONAL(isUnsigned, MDBoolField, (false)); 5306 PARSE_MD_FIELDS(); 5307 #undef VISIT_MD_FIELDS 5308 5309 if (isUnsigned.Val && value.Val.isNegative()) 5310 return tokError("unsigned enumerator with negative value"); 5311 5312 APSInt Value(value.Val); 5313 // Add a leading zero so that unsigned values with the msb set are not 5314 // mistaken for negative values when used for signed enumerators. 5315 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet()) 5316 Value = Value.zext(Value.getBitWidth() + 1); 5317 5318 Result = 5319 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val)); 5320 5321 return false; 5322 } 5323 5324 /// parseDIBasicType: 5325 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32, 5326 /// encoding: DW_ATE_encoding, flags: 0) 5327 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) { 5328 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5329 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \ 5330 OPTIONAL(name, MDStringField, ); \ 5331 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 5332 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5333 OPTIONAL(encoding, DwarfAttEncodingField, ); \ 5334 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \ 5335 OPTIONAL(flags, DIFlagField, ); 5336 PARSE_MD_FIELDS(); 5337 #undef VISIT_MD_FIELDS 5338 5339 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val, 5340 align.Val, encoding.Val, 5341 num_extra_inhabitants.Val, flags.Val)); 5342 return false; 5343 } 5344 5345 /// parseDIStringType: 5346 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32) 5347 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) { 5348 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5349 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \ 5350 OPTIONAL(name, MDStringField, ); \ 5351 OPTIONAL(stringLength, MDField, ); \ 5352 OPTIONAL(stringLengthExpression, MDField, ); \ 5353 OPTIONAL(stringLocationExpression, MDField, ); \ 5354 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 5355 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5356 OPTIONAL(encoding, DwarfAttEncodingField, ); 5357 PARSE_MD_FIELDS(); 5358 #undef VISIT_MD_FIELDS 5359 5360 Result = GET_OR_DISTINCT( 5361 DIStringType, 5362 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val, 5363 stringLocationExpression.Val, size.Val, align.Val, encoding.Val)); 5364 return false; 5365 } 5366 5367 /// parseDIDerivedType: 5368 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0, 5369 /// line: 7, scope: !1, baseType: !2, size: 32, 5370 /// align: 32, offset: 0, flags: 0, extraData: !3, 5371 /// dwarfAddressSpace: 3, ptrAuthKey: 1, 5372 /// ptrAuthIsAddressDiscriminated: true, 5373 /// ptrAuthExtraDiscriminator: 0x1234, 5374 /// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1 5375 /// ) 5376 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) { 5377 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5378 REQUIRED(tag, DwarfTagField, ); \ 5379 OPTIONAL(name, MDStringField, ); \ 5380 OPTIONAL(file, MDField, ); \ 5381 OPTIONAL(line, LineField, ); \ 5382 OPTIONAL(scope, MDField, ); \ 5383 REQUIRED(baseType, MDField, ); \ 5384 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 5385 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5386 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 5387 OPTIONAL(flags, DIFlagField, ); \ 5388 OPTIONAL(extraData, MDField, ); \ 5389 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \ 5390 OPTIONAL(annotations, MDField, ); \ 5391 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \ 5392 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \ 5393 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \ 5394 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \ 5395 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, ); 5396 PARSE_MD_FIELDS(); 5397 #undef VISIT_MD_FIELDS 5398 5399 std::optional<unsigned> DWARFAddressSpace; 5400 if (dwarfAddressSpace.Val != UINT32_MAX) 5401 DWARFAddressSpace = dwarfAddressSpace.Val; 5402 std::optional<DIDerivedType::PtrAuthData> PtrAuthData; 5403 if (ptrAuthKey.Val) 5404 PtrAuthData.emplace( 5405 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val, 5406 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val, 5407 ptrAuthAuthenticatesNullValues.Val); 5408 5409 Result = GET_OR_DISTINCT(DIDerivedType, 5410 (Context, tag.Val, name.Val, file.Val, line.Val, 5411 scope.Val, baseType.Val, size.Val, align.Val, 5412 offset.Val, DWARFAddressSpace, PtrAuthData, 5413 flags.Val, extraData.Val, annotations.Val)); 5414 return false; 5415 } 5416 5417 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) { 5418 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5419 REQUIRED(tag, DwarfTagField, ); \ 5420 OPTIONAL(name, MDStringField, ); \ 5421 OPTIONAL(file, MDField, ); \ 5422 OPTIONAL(line, LineField, ); \ 5423 OPTIONAL(scope, MDField, ); \ 5424 OPTIONAL(baseType, MDField, ); \ 5425 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \ 5426 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5427 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \ 5428 OPTIONAL(flags, DIFlagField, ); \ 5429 OPTIONAL(elements, MDField, ); \ 5430 OPTIONAL(runtimeLang, DwarfLangField, ); \ 5431 OPTIONAL(vtableHolder, MDField, ); \ 5432 OPTIONAL(templateParams, MDField, ); \ 5433 OPTIONAL(identifier, MDStringField, ); \ 5434 OPTIONAL(discriminator, MDField, ); \ 5435 OPTIONAL(dataLocation, MDField, ); \ 5436 OPTIONAL(associated, MDField, ); \ 5437 OPTIONAL(allocated, MDField, ); \ 5438 OPTIONAL(rank, MDSignedOrMDField, ); \ 5439 OPTIONAL(annotations, MDField, ); \ 5440 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \ 5441 OPTIONAL(specification, MDField, ); 5442 PARSE_MD_FIELDS(); 5443 #undef VISIT_MD_FIELDS 5444 5445 Metadata *Rank = nullptr; 5446 if (rank.isMDSignedField()) 5447 Rank = ConstantAsMetadata::get(ConstantInt::getSigned( 5448 Type::getInt64Ty(Context), rank.getMDSignedValue())); 5449 else if (rank.isMDField()) 5450 Rank = rank.getMDFieldValue(); 5451 5452 // If this has an identifier try to build an ODR type. 5453 if (identifier.Val) 5454 if (auto *CT = DICompositeType::buildODRType( 5455 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val, 5456 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, 5457 specification.Val, num_extra_inhabitants.Val, flags.Val, 5458 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val, 5459 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, 5460 Rank, annotations.Val)) { 5461 Result = CT; 5462 return false; 5463 } 5464 5465 // Create a new node, and save it in the context if it belongs in the type 5466 // map. 5467 Result = GET_OR_DISTINCT( 5468 DICompositeType, 5469 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val, 5470 size.Val, align.Val, offset.Val, flags.Val, elements.Val, 5471 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val, 5472 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank, 5473 annotations.Val, specification.Val, num_extra_inhabitants.Val)); 5474 return false; 5475 } 5476 5477 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) { 5478 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5479 OPTIONAL(flags, DIFlagField, ); \ 5480 OPTIONAL(cc, DwarfCCField, ); \ 5481 REQUIRED(types, MDField, ); 5482 PARSE_MD_FIELDS(); 5483 #undef VISIT_MD_FIELDS 5484 5485 Result = GET_OR_DISTINCT(DISubroutineType, 5486 (Context, flags.Val, cc.Val, types.Val)); 5487 return false; 5488 } 5489 5490 /// parseDIFileType: 5491 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir", 5492 /// checksumkind: CSK_MD5, 5493 /// checksum: "000102030405060708090a0b0c0d0e0f", 5494 /// source: "source file contents") 5495 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) { 5496 // The default constructed value for checksumkind is required, but will never 5497 // be used, as the parser checks if the field was actually Seen before using 5498 // the Val. 5499 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5500 REQUIRED(filename, MDStringField, ); \ 5501 REQUIRED(directory, MDStringField, ); \ 5502 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \ 5503 OPTIONAL(checksum, MDStringField, ); \ 5504 OPTIONAL(source, MDStringField, ); 5505 PARSE_MD_FIELDS(); 5506 #undef VISIT_MD_FIELDS 5507 5508 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum; 5509 if (checksumkind.Seen && checksum.Seen) 5510 OptChecksum.emplace(checksumkind.Val, checksum.Val); 5511 else if (checksumkind.Seen || checksum.Seen) 5512 return tokError("'checksumkind' and 'checksum' must be provided together"); 5513 5514 MDString *Source = nullptr; 5515 if (source.Seen) 5516 Source = source.Val; 5517 Result = GET_OR_DISTINCT( 5518 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source)); 5519 return false; 5520 } 5521 5522 /// parseDICompileUnit: 5523 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang", 5524 /// isOptimized: true, flags: "-O2", runtimeVersion: 1, 5525 /// splitDebugFilename: "abc.debug", 5526 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2, 5527 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd, 5528 /// sysroot: "/", sdk: "MacOSX.sdk") 5529 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) { 5530 if (!IsDistinct) 5531 return tokError("missing 'distinct', required for !DICompileUnit"); 5532 5533 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5534 REQUIRED(language, DwarfLangField, ); \ 5535 REQUIRED(file, MDField, (/* AllowNull */ false)); \ 5536 OPTIONAL(producer, MDStringField, ); \ 5537 OPTIONAL(isOptimized, MDBoolField, ); \ 5538 OPTIONAL(flags, MDStringField, ); \ 5539 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \ 5540 OPTIONAL(splitDebugFilename, MDStringField, ); \ 5541 OPTIONAL(emissionKind, EmissionKindField, ); \ 5542 OPTIONAL(enums, MDField, ); \ 5543 OPTIONAL(retainedTypes, MDField, ); \ 5544 OPTIONAL(globals, MDField, ); \ 5545 OPTIONAL(imports, MDField, ); \ 5546 OPTIONAL(macros, MDField, ); \ 5547 OPTIONAL(dwoId, MDUnsignedField, ); \ 5548 OPTIONAL(splitDebugInlining, MDBoolField, = true); \ 5549 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \ 5550 OPTIONAL(nameTableKind, NameTableKindField, ); \ 5551 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \ 5552 OPTIONAL(sysroot, MDStringField, ); \ 5553 OPTIONAL(sdk, MDStringField, ); 5554 PARSE_MD_FIELDS(); 5555 #undef VISIT_MD_FIELDS 5556 5557 Result = DICompileUnit::getDistinct( 5558 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val, 5559 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val, 5560 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val, 5561 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val, 5562 rangesBaseAddress.Val, sysroot.Val, sdk.Val); 5563 return false; 5564 } 5565 5566 /// parseDISubprogram: 5567 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo", 5568 /// file: !1, line: 7, type: !2, isLocal: false, 5569 /// isDefinition: true, scopeLine: 8, containingType: !3, 5570 /// virtuality: DW_VIRTUALTIY_pure_virtual, 5571 /// virtualIndex: 10, thisAdjustment: 4, flags: 11, 5572 /// spFlags: 10, isOptimized: false, templateParams: !4, 5573 /// declaration: !5, retainedNodes: !6, thrownTypes: !7, 5574 /// annotations: !8) 5575 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) { 5576 auto Loc = Lex.getLoc(); 5577 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5578 OPTIONAL(scope, MDField, ); \ 5579 OPTIONAL(name, MDStringField, ); \ 5580 OPTIONAL(linkageName, MDStringField, ); \ 5581 OPTIONAL(file, MDField, ); \ 5582 OPTIONAL(line, LineField, ); \ 5583 OPTIONAL(type, MDField, ); \ 5584 OPTIONAL(isLocal, MDBoolField, ); \ 5585 OPTIONAL(isDefinition, MDBoolField, (true)); \ 5586 OPTIONAL(scopeLine, LineField, ); \ 5587 OPTIONAL(containingType, MDField, ); \ 5588 OPTIONAL(virtuality, DwarfVirtualityField, ); \ 5589 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \ 5590 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \ 5591 OPTIONAL(flags, DIFlagField, ); \ 5592 OPTIONAL(spFlags, DISPFlagField, ); \ 5593 OPTIONAL(isOptimized, MDBoolField, ); \ 5594 OPTIONAL(unit, MDField, ); \ 5595 OPTIONAL(templateParams, MDField, ); \ 5596 OPTIONAL(declaration, MDField, ); \ 5597 OPTIONAL(retainedNodes, MDField, ); \ 5598 OPTIONAL(thrownTypes, MDField, ); \ 5599 OPTIONAL(annotations, MDField, ); \ 5600 OPTIONAL(targetFuncName, MDStringField, ); 5601 PARSE_MD_FIELDS(); 5602 #undef VISIT_MD_FIELDS 5603 5604 // An explicit spFlags field takes precedence over individual fields in 5605 // older IR versions. 5606 DISubprogram::DISPFlags SPFlags = 5607 spFlags.Seen ? spFlags.Val 5608 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val, 5609 isOptimized.Val, virtuality.Val); 5610 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct) 5611 return error( 5612 Loc, 5613 "missing 'distinct', required for !DISubprogram that is a Definition"); 5614 Result = GET_OR_DISTINCT( 5615 DISubprogram, 5616 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val, 5617 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val, 5618 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val, 5619 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val, 5620 targetFuncName.Val)); 5621 return false; 5622 } 5623 5624 /// parseDILexicalBlock: 5625 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9) 5626 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) { 5627 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5628 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5629 OPTIONAL(file, MDField, ); \ 5630 OPTIONAL(line, LineField, ); \ 5631 OPTIONAL(column, ColumnField, ); 5632 PARSE_MD_FIELDS(); 5633 #undef VISIT_MD_FIELDS 5634 5635 Result = GET_OR_DISTINCT( 5636 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val)); 5637 return false; 5638 } 5639 5640 /// parseDILexicalBlockFile: 5641 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9) 5642 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) { 5643 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5644 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5645 OPTIONAL(file, MDField, ); \ 5646 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX)); 5647 PARSE_MD_FIELDS(); 5648 #undef VISIT_MD_FIELDS 5649 5650 Result = GET_OR_DISTINCT(DILexicalBlockFile, 5651 (Context, scope.Val, file.Val, discriminator.Val)); 5652 return false; 5653 } 5654 5655 /// parseDICommonBlock: 5656 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9) 5657 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) { 5658 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5659 REQUIRED(scope, MDField, ); \ 5660 OPTIONAL(declaration, MDField, ); \ 5661 OPTIONAL(name, MDStringField, ); \ 5662 OPTIONAL(file, MDField, ); \ 5663 OPTIONAL(line, LineField, ); 5664 PARSE_MD_FIELDS(); 5665 #undef VISIT_MD_FIELDS 5666 5667 Result = GET_OR_DISTINCT(DICommonBlock, 5668 (Context, scope.Val, declaration.Val, name.Val, 5669 file.Val, line.Val)); 5670 return false; 5671 } 5672 5673 /// parseDINamespace: 5674 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9) 5675 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) { 5676 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5677 REQUIRED(scope, MDField, ); \ 5678 OPTIONAL(name, MDStringField, ); \ 5679 OPTIONAL(exportSymbols, MDBoolField, ); 5680 PARSE_MD_FIELDS(); 5681 #undef VISIT_MD_FIELDS 5682 5683 Result = GET_OR_DISTINCT(DINamespace, 5684 (Context, scope.Val, name.Val, exportSymbols.Val)); 5685 return false; 5686 } 5687 5688 /// parseDIMacro: 5689 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: 5690 /// "SomeValue") 5691 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) { 5692 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5693 REQUIRED(type, DwarfMacinfoTypeField, ); \ 5694 OPTIONAL(line, LineField, ); \ 5695 REQUIRED(name, MDStringField, ); \ 5696 OPTIONAL(value, MDStringField, ); 5697 PARSE_MD_FIELDS(); 5698 #undef VISIT_MD_FIELDS 5699 5700 Result = GET_OR_DISTINCT(DIMacro, 5701 (Context, type.Val, line.Val, name.Val, value.Val)); 5702 return false; 5703 } 5704 5705 /// parseDIMacroFile: 5706 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3) 5707 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) { 5708 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5709 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \ 5710 OPTIONAL(line, LineField, ); \ 5711 REQUIRED(file, MDField, ); \ 5712 OPTIONAL(nodes, MDField, ); 5713 PARSE_MD_FIELDS(); 5714 #undef VISIT_MD_FIELDS 5715 5716 Result = GET_OR_DISTINCT(DIMacroFile, 5717 (Context, type.Val, line.Val, file.Val, nodes.Val)); 5718 return false; 5719 } 5720 5721 /// parseDIModule: 5722 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: 5723 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes", 5724 /// file: !1, line: 4, isDecl: false) 5725 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) { 5726 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5727 REQUIRED(scope, MDField, ); \ 5728 REQUIRED(name, MDStringField, ); \ 5729 OPTIONAL(configMacros, MDStringField, ); \ 5730 OPTIONAL(includePath, MDStringField, ); \ 5731 OPTIONAL(apinotes, MDStringField, ); \ 5732 OPTIONAL(file, MDField, ); \ 5733 OPTIONAL(line, LineField, ); \ 5734 OPTIONAL(isDecl, MDBoolField, ); 5735 PARSE_MD_FIELDS(); 5736 #undef VISIT_MD_FIELDS 5737 5738 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val, 5739 configMacros.Val, includePath.Val, 5740 apinotes.Val, line.Val, isDecl.Val)); 5741 return false; 5742 } 5743 5744 /// parseDITemplateTypeParameter: 5745 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false) 5746 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) { 5747 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5748 OPTIONAL(name, MDStringField, ); \ 5749 REQUIRED(type, MDField, ); \ 5750 OPTIONAL(defaulted, MDBoolField, ); 5751 PARSE_MD_FIELDS(); 5752 #undef VISIT_MD_FIELDS 5753 5754 Result = GET_OR_DISTINCT(DITemplateTypeParameter, 5755 (Context, name.Val, type.Val, defaulted.Val)); 5756 return false; 5757 } 5758 5759 /// parseDITemplateValueParameter: 5760 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter, 5761 /// name: "V", type: !1, defaulted: false, 5762 /// value: i32 7) 5763 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) { 5764 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5765 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \ 5766 OPTIONAL(name, MDStringField, ); \ 5767 OPTIONAL(type, MDField, ); \ 5768 OPTIONAL(defaulted, MDBoolField, ); \ 5769 REQUIRED(value, MDField, ); 5770 5771 PARSE_MD_FIELDS(); 5772 #undef VISIT_MD_FIELDS 5773 5774 Result = GET_OR_DISTINCT( 5775 DITemplateValueParameter, 5776 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val)); 5777 return false; 5778 } 5779 5780 /// parseDIGlobalVariable: 5781 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo", 5782 /// file: !1, line: 7, type: !2, isLocal: false, 5783 /// isDefinition: true, templateParams: !3, 5784 /// declaration: !4, align: 8) 5785 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) { 5786 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5787 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \ 5788 OPTIONAL(scope, MDField, ); \ 5789 OPTIONAL(linkageName, MDStringField, ); \ 5790 OPTIONAL(file, MDField, ); \ 5791 OPTIONAL(line, LineField, ); \ 5792 OPTIONAL(type, MDField, ); \ 5793 OPTIONAL(isLocal, MDBoolField, ); \ 5794 OPTIONAL(isDefinition, MDBoolField, (true)); \ 5795 OPTIONAL(templateParams, MDField, ); \ 5796 OPTIONAL(declaration, MDField, ); \ 5797 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5798 OPTIONAL(annotations, MDField, ); 5799 PARSE_MD_FIELDS(); 5800 #undef VISIT_MD_FIELDS 5801 5802 Result = 5803 GET_OR_DISTINCT(DIGlobalVariable, 5804 (Context, scope.Val, name.Val, linkageName.Val, file.Val, 5805 line.Val, type.Val, isLocal.Val, isDefinition.Val, 5806 declaration.Val, templateParams.Val, align.Val, 5807 annotations.Val)); 5808 return false; 5809 } 5810 5811 /// parseDILocalVariable: 5812 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo", 5813 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5814 /// align: 8) 5815 /// ::= !DILocalVariable(scope: !0, name: "foo", 5816 /// file: !1, line: 7, type: !2, arg: 2, flags: 7, 5817 /// align: 8) 5818 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) { 5819 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5820 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5821 OPTIONAL(name, MDStringField, ); \ 5822 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \ 5823 OPTIONAL(file, MDField, ); \ 5824 OPTIONAL(line, LineField, ); \ 5825 OPTIONAL(type, MDField, ); \ 5826 OPTIONAL(flags, DIFlagField, ); \ 5827 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \ 5828 OPTIONAL(annotations, MDField, ); 5829 PARSE_MD_FIELDS(); 5830 #undef VISIT_MD_FIELDS 5831 5832 Result = GET_OR_DISTINCT(DILocalVariable, 5833 (Context, scope.Val, name.Val, file.Val, line.Val, 5834 type.Val, arg.Val, flags.Val, align.Val, 5835 annotations.Val)); 5836 return false; 5837 } 5838 5839 /// parseDILabel: 5840 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7) 5841 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) { 5842 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5843 REQUIRED(scope, MDField, (/* AllowNull */ false)); \ 5844 REQUIRED(name, MDStringField, ); \ 5845 REQUIRED(file, MDField, ); \ 5846 REQUIRED(line, LineField, ); 5847 PARSE_MD_FIELDS(); 5848 #undef VISIT_MD_FIELDS 5849 5850 Result = GET_OR_DISTINCT(DILabel, 5851 (Context, scope.Val, name.Val, file.Val, line.Val)); 5852 return false; 5853 } 5854 5855 /// parseDIExpressionBody: 5856 /// ::= (0, 7, -1) 5857 bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) { 5858 if (parseToken(lltok::lparen, "expected '(' here")) 5859 return true; 5860 5861 SmallVector<uint64_t, 8> Elements; 5862 if (Lex.getKind() != lltok::rparen) 5863 do { 5864 if (Lex.getKind() == lltok::DwarfOp) { 5865 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) { 5866 Lex.Lex(); 5867 Elements.push_back(Op); 5868 continue; 5869 } 5870 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'"); 5871 } 5872 5873 if (Lex.getKind() == lltok::DwarfAttEncoding) { 5874 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) { 5875 Lex.Lex(); 5876 Elements.push_back(Op); 5877 continue; 5878 } 5879 return tokError(Twine("invalid DWARF attribute encoding '") + 5880 Lex.getStrVal() + "'"); 5881 } 5882 5883 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 5884 return tokError("expected unsigned integer"); 5885 5886 auto &U = Lex.getAPSIntVal(); 5887 if (U.ugt(UINT64_MAX)) 5888 return tokError("element too large, limit is " + Twine(UINT64_MAX)); 5889 Elements.push_back(U.getZExtValue()); 5890 Lex.Lex(); 5891 } while (EatIfPresent(lltok::comma)); 5892 5893 if (parseToken(lltok::rparen, "expected ')' here")) 5894 return true; 5895 5896 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements)); 5897 return false; 5898 } 5899 5900 /// parseDIExpression: 5901 /// ::= !DIExpression(0, 7, -1) 5902 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) { 5903 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5904 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'"); 5905 Lex.Lex(); 5906 5907 return parseDIExpressionBody(Result, IsDistinct); 5908 } 5909 5910 /// ParseDIArgList: 5911 /// ::= !DIArgList(i32 7, i64 %0) 5912 bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) { 5913 assert(PFS && "Expected valid function state"); 5914 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name"); 5915 Lex.Lex(); 5916 5917 if (parseToken(lltok::lparen, "expected '(' here")) 5918 return true; 5919 5920 SmallVector<ValueAsMetadata *, 4> Args; 5921 if (Lex.getKind() != lltok::rparen) 5922 do { 5923 Metadata *MD; 5924 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS)) 5925 return true; 5926 Args.push_back(dyn_cast<ValueAsMetadata>(MD)); 5927 } while (EatIfPresent(lltok::comma)); 5928 5929 if (parseToken(lltok::rparen, "expected ')' here")) 5930 return true; 5931 5932 MD = DIArgList::get(Context, Args); 5933 return false; 5934 } 5935 5936 /// parseDIGlobalVariableExpression: 5937 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1) 5938 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result, 5939 bool IsDistinct) { 5940 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5941 REQUIRED(var, MDField, ); \ 5942 REQUIRED(expr, MDField, ); 5943 PARSE_MD_FIELDS(); 5944 #undef VISIT_MD_FIELDS 5945 5946 Result = 5947 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val)); 5948 return false; 5949 } 5950 5951 /// parseDIObjCProperty: 5952 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo", 5953 /// getter: "getFoo", attributes: 7, type: !2) 5954 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) { 5955 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5956 OPTIONAL(name, MDStringField, ); \ 5957 OPTIONAL(file, MDField, ); \ 5958 OPTIONAL(line, LineField, ); \ 5959 OPTIONAL(setter, MDStringField, ); \ 5960 OPTIONAL(getter, MDStringField, ); \ 5961 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \ 5962 OPTIONAL(type, MDField, ); 5963 PARSE_MD_FIELDS(); 5964 #undef VISIT_MD_FIELDS 5965 5966 Result = GET_OR_DISTINCT(DIObjCProperty, 5967 (Context, name.Val, file.Val, line.Val, setter.Val, 5968 getter.Val, attributes.Val, type.Val)); 5969 return false; 5970 } 5971 5972 /// parseDIImportedEntity: 5973 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1, 5974 /// line: 7, name: "foo", elements: !2) 5975 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) { 5976 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \ 5977 REQUIRED(tag, DwarfTagField, ); \ 5978 REQUIRED(scope, MDField, ); \ 5979 OPTIONAL(entity, MDField, ); \ 5980 OPTIONAL(file, MDField, ); \ 5981 OPTIONAL(line, LineField, ); \ 5982 OPTIONAL(name, MDStringField, ); \ 5983 OPTIONAL(elements, MDField, ); 5984 PARSE_MD_FIELDS(); 5985 #undef VISIT_MD_FIELDS 5986 5987 Result = GET_OR_DISTINCT(DIImportedEntity, 5988 (Context, tag.Val, scope.Val, entity.Val, file.Val, 5989 line.Val, name.Val, elements.Val)); 5990 return false; 5991 } 5992 5993 #undef PARSE_MD_FIELD 5994 #undef NOP_FIELD 5995 #undef REQUIRE_FIELD 5996 #undef DECLARE_FIELD 5997 5998 /// parseMetadataAsValue 5999 /// ::= metadata i32 %local 6000 /// ::= metadata i32 @global 6001 /// ::= metadata i32 7 6002 /// ::= metadata !0 6003 /// ::= metadata !{...} 6004 /// ::= metadata !"string" 6005 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) { 6006 // Note: the type 'metadata' has already been parsed. 6007 Metadata *MD; 6008 if (parseMetadata(MD, &PFS)) 6009 return true; 6010 6011 V = MetadataAsValue::get(Context, MD); 6012 return false; 6013 } 6014 6015 /// parseValueAsMetadata 6016 /// ::= i32 %local 6017 /// ::= i32 @global 6018 /// ::= i32 7 6019 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg, 6020 PerFunctionState *PFS) { 6021 Type *Ty; 6022 LocTy Loc; 6023 if (parseType(Ty, TypeMsg, Loc)) 6024 return true; 6025 if (Ty->isMetadataTy()) 6026 return error(Loc, "invalid metadata-value-metadata roundtrip"); 6027 6028 Value *V; 6029 if (parseValue(Ty, V, PFS)) 6030 return true; 6031 6032 MD = ValueAsMetadata::get(V); 6033 return false; 6034 } 6035 6036 /// parseMetadata 6037 /// ::= i32 %local 6038 /// ::= i32 @global 6039 /// ::= i32 7 6040 /// ::= !42 6041 /// ::= !{...} 6042 /// ::= !"string" 6043 /// ::= !DILocation(...) 6044 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) { 6045 if (Lex.getKind() == lltok::MetadataVar) { 6046 // DIArgLists are a special case, as they are a list of ValueAsMetadata and 6047 // so parsing this requires a Function State. 6048 if (Lex.getStrVal() == "DIArgList") { 6049 Metadata *AL; 6050 if (parseDIArgList(AL, PFS)) 6051 return true; 6052 MD = AL; 6053 return false; 6054 } 6055 MDNode *N; 6056 if (parseSpecializedMDNode(N)) { 6057 return true; 6058 } 6059 MD = N; 6060 return false; 6061 } 6062 6063 // ValueAsMetadata: 6064 // <type> <value> 6065 if (Lex.getKind() != lltok::exclaim) 6066 return parseValueAsMetadata(MD, "expected metadata operand", PFS); 6067 6068 // '!'. 6069 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here"); 6070 Lex.Lex(); 6071 6072 // MDString: 6073 // ::= '!' STRINGCONSTANT 6074 if (Lex.getKind() == lltok::StringConstant) { 6075 MDString *S; 6076 if (parseMDString(S)) 6077 return true; 6078 MD = S; 6079 return false; 6080 } 6081 6082 // MDNode: 6083 // !{ ... } 6084 // !7 6085 MDNode *N; 6086 if (parseMDNodeTail(N)) 6087 return true; 6088 MD = N; 6089 return false; 6090 } 6091 6092 //===----------------------------------------------------------------------===// 6093 // Function Parsing. 6094 //===----------------------------------------------------------------------===// 6095 6096 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V, 6097 PerFunctionState *PFS) { 6098 if (Ty->isFunctionTy()) 6099 return error(ID.Loc, "functions are not values, refer to them as pointers"); 6100 6101 switch (ID.Kind) { 6102 case ValID::t_LocalID: 6103 if (!PFS) 6104 return error(ID.Loc, "invalid use of function-local name"); 6105 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc); 6106 return V == nullptr; 6107 case ValID::t_LocalName: 6108 if (!PFS) 6109 return error(ID.Loc, "invalid use of function-local name"); 6110 V = PFS->getVal(ID.StrVal, Ty, ID.Loc); 6111 return V == nullptr; 6112 case ValID::t_InlineAsm: { 6113 if (!ID.FTy) 6114 return error(ID.Loc, "invalid type for inline asm constraint string"); 6115 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2)) 6116 return error(ID.Loc, toString(std::move(Err))); 6117 V = InlineAsm::get( 6118 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1, 6119 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1); 6120 return false; 6121 } 6122 case ValID::t_GlobalName: 6123 V = getGlobalVal(ID.StrVal, Ty, ID.Loc); 6124 if (V && ID.NoCFI) 6125 V = NoCFIValue::get(cast<GlobalValue>(V)); 6126 return V == nullptr; 6127 case ValID::t_GlobalID: 6128 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc); 6129 if (V && ID.NoCFI) 6130 V = NoCFIValue::get(cast<GlobalValue>(V)); 6131 return V == nullptr; 6132 case ValID::t_APSInt: 6133 if (!Ty->isIntegerTy()) 6134 return error(ID.Loc, "integer constant must have integer type"); 6135 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits()); 6136 V = ConstantInt::get(Context, ID.APSIntVal); 6137 return false; 6138 case ValID::t_APFloat: 6139 if (!Ty->isFloatingPointTy() || 6140 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal)) 6141 return error(ID.Loc, "floating point constant invalid for type"); 6142 6143 // The lexer has no type info, so builds all half, bfloat, float, and double 6144 // FP constants as double. Fix this here. Long double does not need this. 6145 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) { 6146 // Check for signaling before potentially converting and losing that info. 6147 bool IsSNAN = ID.APFloatVal.isSignaling(); 6148 bool Ignored; 6149 if (Ty->isHalfTy()) 6150 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, 6151 &Ignored); 6152 else if (Ty->isBFloatTy()) 6153 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, 6154 &Ignored); 6155 else if (Ty->isFloatTy()) 6156 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 6157 &Ignored); 6158 if (IsSNAN) { 6159 // The convert call above may quiet an SNaN, so manufacture another 6160 // SNaN. The bitcast works because the payload (significand) parameter 6161 // is truncated to fit. 6162 APInt Payload = ID.APFloatVal.bitcastToAPInt(); 6163 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(), 6164 ID.APFloatVal.isNegative(), &Payload); 6165 } 6166 } 6167 V = ConstantFP::get(Context, ID.APFloatVal); 6168 6169 if (V->getType() != Ty) 6170 return error(ID.Loc, "floating point constant does not have type '" + 6171 getTypeString(Ty) + "'"); 6172 6173 return false; 6174 case ValID::t_Null: 6175 if (!Ty->isPointerTy()) 6176 return error(ID.Loc, "null must be a pointer type"); 6177 V = ConstantPointerNull::get(cast<PointerType>(Ty)); 6178 return false; 6179 case ValID::t_Undef: 6180 // FIXME: LabelTy should not be a first-class type. 6181 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 6182 return error(ID.Loc, "invalid type for undef constant"); 6183 V = UndefValue::get(Ty); 6184 return false; 6185 case ValID::t_EmptyArray: 6186 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0) 6187 return error(ID.Loc, "invalid empty array initializer"); 6188 V = UndefValue::get(Ty); 6189 return false; 6190 case ValID::t_Zero: 6191 // FIXME: LabelTy should not be a first-class type. 6192 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 6193 return error(ID.Loc, "invalid type for null constant"); 6194 if (auto *TETy = dyn_cast<TargetExtType>(Ty)) 6195 if (!TETy->hasProperty(TargetExtType::HasZeroInit)) 6196 return error(ID.Loc, "invalid type for null constant"); 6197 V = Constant::getNullValue(Ty); 6198 return false; 6199 case ValID::t_None: 6200 if (!Ty->isTokenTy()) 6201 return error(ID.Loc, "invalid type for none constant"); 6202 V = Constant::getNullValue(Ty); 6203 return false; 6204 case ValID::t_Poison: 6205 // FIXME: LabelTy should not be a first-class type. 6206 if (!Ty->isFirstClassType() || Ty->isLabelTy()) 6207 return error(ID.Loc, "invalid type for poison constant"); 6208 V = PoisonValue::get(Ty); 6209 return false; 6210 case ValID::t_Constant: 6211 if (ID.ConstantVal->getType() != Ty) 6212 return error(ID.Loc, "constant expression type mismatch: got type '" + 6213 getTypeString(ID.ConstantVal->getType()) + 6214 "' but expected '" + getTypeString(Ty) + "'"); 6215 V = ID.ConstantVal; 6216 return false; 6217 case ValID::t_ConstantSplat: 6218 if (!Ty->isVectorTy()) 6219 return error(ID.Loc, "vector constant must have vector type"); 6220 if (ID.ConstantVal->getType() != Ty->getScalarType()) 6221 return error(ID.Loc, "constant expression type mismatch: got type '" + 6222 getTypeString(ID.ConstantVal->getType()) + 6223 "' but expected '" + 6224 getTypeString(Ty->getScalarType()) + "'"); 6225 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(), 6226 ID.ConstantVal); 6227 return false; 6228 case ValID::t_ConstantStruct: 6229 case ValID::t_PackedConstantStruct: 6230 if (StructType *ST = dyn_cast<StructType>(Ty)) { 6231 if (ST->getNumElements() != ID.UIntVal) 6232 return error(ID.Loc, 6233 "initializer with struct type has wrong # elements"); 6234 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct)) 6235 return error(ID.Loc, "packed'ness of initializer and type don't match"); 6236 6237 // Verify that the elements are compatible with the structtype. 6238 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i) 6239 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i)) 6240 return error( 6241 ID.Loc, 6242 "element " + Twine(i) + 6243 " of struct initializer doesn't match struct element type"); 6244 6245 V = ConstantStruct::get( 6246 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal)); 6247 } else 6248 return error(ID.Loc, "constant expression type mismatch"); 6249 return false; 6250 } 6251 llvm_unreachable("Invalid ValID"); 6252 } 6253 6254 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) { 6255 C = nullptr; 6256 ValID ID; 6257 auto Loc = Lex.getLoc(); 6258 if (parseValID(ID, /*PFS=*/nullptr)) 6259 return true; 6260 switch (ID.Kind) { 6261 case ValID::t_APSInt: 6262 case ValID::t_APFloat: 6263 case ValID::t_Undef: 6264 case ValID::t_Constant: 6265 case ValID::t_ConstantSplat: 6266 case ValID::t_ConstantStruct: 6267 case ValID::t_PackedConstantStruct: { 6268 Value *V; 6269 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr)) 6270 return true; 6271 assert(isa<Constant>(V) && "Expected a constant value"); 6272 C = cast<Constant>(V); 6273 return false; 6274 } 6275 case ValID::t_Null: 6276 C = Constant::getNullValue(Ty); 6277 return false; 6278 default: 6279 return error(Loc, "expected a constant value"); 6280 } 6281 } 6282 6283 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 6284 V = nullptr; 6285 ValID ID; 6286 return parseValID(ID, PFS, Ty) || 6287 convertValIDToValue(Ty, ID, V, PFS); 6288 } 6289 6290 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { 6291 Type *Ty = nullptr; 6292 return parseType(Ty) || parseValue(Ty, V, PFS); 6293 } 6294 6295 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 6296 PerFunctionState &PFS) { 6297 Value *V; 6298 Loc = Lex.getLoc(); 6299 if (parseTypeAndValue(V, PFS)) 6300 return true; 6301 if (!isa<BasicBlock>(V)) 6302 return error(Loc, "expected a basic block"); 6303 BB = cast<BasicBlock>(V); 6304 return false; 6305 } 6306 6307 bool isOldDbgFormatIntrinsic(StringRef Name) { 6308 // Exit early for the common (non-debug-intrinsic) case. 6309 // We can make this the only check when we begin supporting all "llvm.dbg" 6310 // intrinsics in the new debug info format. 6311 if (!Name.starts_with("llvm.dbg.")) 6312 return false; 6313 Intrinsic::ID FnID = Intrinsic::lookupIntrinsicID(Name); 6314 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value || 6315 FnID == Intrinsic::dbg_assign; 6316 } 6317 6318 /// FunctionHeader 6319 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 6320 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 6321 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 6322 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 6323 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine, 6324 unsigned &FunctionNumber, 6325 SmallVectorImpl<unsigned> &UnnamedArgNums) { 6326 // parse the linkage. 6327 LocTy LinkageLoc = Lex.getLoc(); 6328 unsigned Linkage; 6329 unsigned Visibility; 6330 unsigned DLLStorageClass; 6331 bool DSOLocal; 6332 AttrBuilder RetAttrs(M->getContext()); 6333 unsigned CC; 6334 bool HasLinkage; 6335 Type *RetType = nullptr; 6336 LocTy RetTypeLoc = Lex.getLoc(); 6337 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 6338 DSOLocal) || 6339 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6340 parseType(RetType, RetTypeLoc, true /*void allowed*/)) 6341 return true; 6342 6343 // Verify that the linkage is ok. 6344 switch ((GlobalValue::LinkageTypes)Linkage) { 6345 case GlobalValue::ExternalLinkage: 6346 break; // always ok. 6347 case GlobalValue::ExternalWeakLinkage: 6348 if (IsDefine) 6349 return error(LinkageLoc, "invalid linkage for function definition"); 6350 break; 6351 case GlobalValue::PrivateLinkage: 6352 case GlobalValue::InternalLinkage: 6353 case GlobalValue::AvailableExternallyLinkage: 6354 case GlobalValue::LinkOnceAnyLinkage: 6355 case GlobalValue::LinkOnceODRLinkage: 6356 case GlobalValue::WeakAnyLinkage: 6357 case GlobalValue::WeakODRLinkage: 6358 if (!IsDefine) 6359 return error(LinkageLoc, "invalid linkage for function declaration"); 6360 break; 6361 case GlobalValue::AppendingLinkage: 6362 case GlobalValue::CommonLinkage: 6363 return error(LinkageLoc, "invalid function linkage type"); 6364 } 6365 6366 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 6367 return error(LinkageLoc, 6368 "symbol with local linkage must have default visibility"); 6369 6370 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage)) 6371 return error(LinkageLoc, 6372 "symbol with local linkage cannot have a DLL storage class"); 6373 6374 if (!FunctionType::isValidReturnType(RetType)) 6375 return error(RetTypeLoc, "invalid function return type"); 6376 6377 LocTy NameLoc = Lex.getLoc(); 6378 6379 std::string FunctionName; 6380 if (Lex.getKind() == lltok::GlobalVar) { 6381 FunctionName = Lex.getStrVal(); 6382 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 6383 FunctionNumber = Lex.getUIntVal(); 6384 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(), 6385 FunctionNumber)) 6386 return true; 6387 } else { 6388 return tokError("expected function name"); 6389 } 6390 6391 Lex.Lex(); 6392 6393 if (Lex.getKind() != lltok::lparen) 6394 return tokError("expected '(' in function argument list"); 6395 6396 SmallVector<ArgInfo, 8> ArgList; 6397 bool IsVarArg; 6398 AttrBuilder FuncAttrs(M->getContext()); 6399 std::vector<unsigned> FwdRefAttrGrps; 6400 LocTy BuiltinLoc; 6401 std::string Section; 6402 std::string Partition; 6403 MaybeAlign Alignment; 6404 std::string GC; 6405 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 6406 unsigned AddrSpace = 0; 6407 Constant *Prefix = nullptr; 6408 Constant *Prologue = nullptr; 6409 Constant *PersonalityFn = nullptr; 6410 Comdat *C; 6411 6412 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) || 6413 parseOptionalUnnamedAddr(UnnamedAddr) || 6414 parseOptionalProgramAddrSpace(AddrSpace) || 6415 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 6416 BuiltinLoc) || 6417 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) || 6418 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) || 6419 parseOptionalComdat(FunctionName, C) || 6420 parseOptionalAlignment(Alignment) || 6421 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) || 6422 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) || 6423 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) || 6424 (EatIfPresent(lltok::kw_personality) && 6425 parseGlobalTypeAndValue(PersonalityFn))) 6426 return true; 6427 6428 if (FuncAttrs.contains(Attribute::Builtin)) 6429 return error(BuiltinLoc, "'builtin' attribute not valid on function"); 6430 6431 // If the alignment was parsed as an attribute, move to the alignment field. 6432 if (MaybeAlign A = FuncAttrs.getAlignment()) { 6433 Alignment = A; 6434 FuncAttrs.removeAttribute(Attribute::Alignment); 6435 } 6436 6437 // Okay, if we got here, the function is syntactically valid. Convert types 6438 // and do semantic checks. 6439 std::vector<Type*> ParamTypeList; 6440 SmallVector<AttributeSet, 8> Attrs; 6441 6442 for (const ArgInfo &Arg : ArgList) { 6443 ParamTypeList.push_back(Arg.Ty); 6444 Attrs.push_back(Arg.Attrs); 6445 } 6446 6447 AttributeList PAL = 6448 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 6449 AttributeSet::get(Context, RetAttrs), Attrs); 6450 6451 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy()) 6452 return error(RetTypeLoc, "functions with 'sret' argument must return void"); 6453 6454 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg); 6455 PointerType *PFT = PointerType::get(FT, AddrSpace); 6456 6457 Fn = nullptr; 6458 GlobalValue *FwdFn = nullptr; 6459 if (!FunctionName.empty()) { 6460 // If this was a definition of a forward reference, remove the definition 6461 // from the forward reference table and fill in the forward ref. 6462 auto FRVI = ForwardRefVals.find(FunctionName); 6463 if (FRVI != ForwardRefVals.end()) { 6464 FwdFn = FRVI->second.first; 6465 if (FwdFn->getType() != PFT) 6466 return error(FRVI->second.second, 6467 "invalid forward reference to " 6468 "function '" + 6469 FunctionName + 6470 "' with wrong type: " 6471 "expected '" + 6472 getTypeString(PFT) + "' but was '" + 6473 getTypeString(FwdFn->getType()) + "'"); 6474 ForwardRefVals.erase(FRVI); 6475 } else if ((Fn = M->getFunction(FunctionName))) { 6476 // Reject redefinitions. 6477 return error(NameLoc, 6478 "invalid redefinition of function '" + FunctionName + "'"); 6479 } else if (M->getNamedValue(FunctionName)) { 6480 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 6481 } 6482 6483 } else { 6484 // Handle @"", where a name is syntactically specified, but semantically 6485 // missing. 6486 if (FunctionNumber == (unsigned)-1) 6487 FunctionNumber = NumberedVals.getNext(); 6488 6489 // If this is a definition of a forward referenced function, make sure the 6490 // types agree. 6491 auto I = ForwardRefValIDs.find(FunctionNumber); 6492 if (I != ForwardRefValIDs.end()) { 6493 FwdFn = I->second.first; 6494 if (FwdFn->getType() != PFT) 6495 return error(NameLoc, "type of definition and forward reference of '@" + 6496 Twine(FunctionNumber) + 6497 "' disagree: " 6498 "expected '" + 6499 getTypeString(PFT) + "' but was '" + 6500 getTypeString(FwdFn->getType()) + "'"); 6501 ForwardRefValIDs.erase(I); 6502 } 6503 } 6504 6505 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 6506 FunctionName, M); 6507 6508 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 6509 6510 if (FunctionName.empty()) 6511 NumberedVals.add(FunctionNumber, Fn); 6512 6513 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 6514 maybeSetDSOLocal(DSOLocal, *Fn); 6515 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 6516 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 6517 Fn->setCallingConv(CC); 6518 Fn->setAttributes(PAL); 6519 Fn->setUnnamedAddr(UnnamedAddr); 6520 if (Alignment) 6521 Fn->setAlignment(*Alignment); 6522 Fn->setSection(Section); 6523 Fn->setPartition(Partition); 6524 Fn->setComdat(C); 6525 Fn->setPersonalityFn(PersonalityFn); 6526 if (!GC.empty()) Fn->setGC(GC); 6527 Fn->setPrefixData(Prefix); 6528 Fn->setPrologueData(Prologue); 6529 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 6530 6531 // Add all of the arguments we parsed to the function. 6532 Function::arg_iterator ArgIt = Fn->arg_begin(); 6533 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 6534 // If the argument has a name, insert it into the argument symbol table. 6535 if (ArgList[i].Name.empty()) continue; 6536 6537 // Set the name, if it conflicted, it will be auto-renamed. 6538 ArgIt->setName(ArgList[i].Name); 6539 6540 if (ArgIt->getName() != ArgList[i].Name) 6541 return error(ArgList[i].Loc, 6542 "redefinition of argument '%" + ArgList[i].Name + "'"); 6543 } 6544 6545 if (FwdFn) { 6546 FwdFn->replaceAllUsesWith(Fn); 6547 FwdFn->eraseFromParent(); 6548 } 6549 6550 if (IsDefine) 6551 return false; 6552 6553 // Check the declaration has no block address forward references. 6554 ValID ID; 6555 if (FunctionName.empty()) { 6556 ID.Kind = ValID::t_GlobalID; 6557 ID.UIntVal = FunctionNumber; 6558 } else { 6559 ID.Kind = ValID::t_GlobalName; 6560 ID.StrVal = FunctionName; 6561 } 6562 auto Blocks = ForwardRefBlockAddresses.find(ID); 6563 if (Blocks != ForwardRefBlockAddresses.end()) 6564 return error(Blocks->first.Loc, 6565 "cannot take blockaddress inside a declaration"); 6566 return false; 6567 } 6568 6569 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 6570 ValID ID; 6571 if (FunctionNumber == -1) { 6572 ID.Kind = ValID::t_GlobalName; 6573 ID.StrVal = std::string(F.getName()); 6574 } else { 6575 ID.Kind = ValID::t_GlobalID; 6576 ID.UIntVal = FunctionNumber; 6577 } 6578 6579 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 6580 if (Blocks == P.ForwardRefBlockAddresses.end()) 6581 return false; 6582 6583 for (const auto &I : Blocks->second) { 6584 const ValID &BBID = I.first; 6585 GlobalValue *GV = I.second; 6586 6587 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 6588 "Expected local id or name"); 6589 BasicBlock *BB; 6590 if (BBID.Kind == ValID::t_LocalName) 6591 BB = getBB(BBID.StrVal, BBID.Loc); 6592 else 6593 BB = getBB(BBID.UIntVal, BBID.Loc); 6594 if (!BB) 6595 return P.error(BBID.Loc, "referenced value is not a basic block"); 6596 6597 Value *ResolvedVal = BlockAddress::get(&F, BB); 6598 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(), 6599 ResolvedVal); 6600 if (!ResolvedVal) 6601 return true; 6602 GV->replaceAllUsesWith(ResolvedVal); 6603 GV->eraseFromParent(); 6604 } 6605 6606 P.ForwardRefBlockAddresses.erase(Blocks); 6607 return false; 6608 } 6609 6610 /// parseFunctionBody 6611 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 6612 bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber, 6613 ArrayRef<unsigned> UnnamedArgNums) { 6614 if (Lex.getKind() != lltok::lbrace) 6615 return tokError("expected '{' in function body"); 6616 Lex.Lex(); // eat the {. 6617 6618 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums); 6619 6620 // Resolve block addresses and allow basic blocks to be forward-declared 6621 // within this function. 6622 if (PFS.resolveForwardRefBlockAddresses()) 6623 return true; 6624 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS); 6625 6626 // We need at least one basic block. 6627 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 6628 return tokError("function body requires at least one basic block"); 6629 6630 while (Lex.getKind() != lltok::rbrace && 6631 Lex.getKind() != lltok::kw_uselistorder) 6632 if (parseBasicBlock(PFS)) 6633 return true; 6634 6635 while (Lex.getKind() != lltok::rbrace) 6636 if (parseUseListOrder(&PFS)) 6637 return true; 6638 6639 // Eat the }. 6640 Lex.Lex(); 6641 6642 // Verify function is ok. 6643 return PFS.finishFunction(); 6644 } 6645 6646 /// parseBasicBlock 6647 /// ::= (LabelStr|LabelID)? Instruction* 6648 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 6649 // If this basic block starts out with a name, remember it. 6650 std::string Name; 6651 int NameID = -1; 6652 LocTy NameLoc = Lex.getLoc(); 6653 if (Lex.getKind() == lltok::LabelStr) { 6654 Name = Lex.getStrVal(); 6655 Lex.Lex(); 6656 } else if (Lex.getKind() == lltok::LabelID) { 6657 NameID = Lex.getUIntVal(); 6658 Lex.Lex(); 6659 } 6660 6661 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 6662 if (!BB) 6663 return true; 6664 6665 std::string NameStr; 6666 6667 // Parse the instructions and debug values in this block until we get a 6668 // terminator. 6669 Instruction *Inst; 6670 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); }; 6671 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>; 6672 SmallVector<DbgRecordPtr> TrailingDbgRecord; 6673 do { 6674 // Handle debug records first - there should always be an instruction 6675 // following the debug records, i.e. they cannot appear after the block 6676 // terminator. 6677 while (Lex.getKind() == lltok::hash) { 6678 if (SeenOldDbgInfoFormat) 6679 return error(Lex.getLoc(), "debug record should not appear in a module " 6680 "containing debug info intrinsics"); 6681 if (!SeenNewDbgInfoFormat) 6682 M->setNewDbgInfoFormatFlag(true); 6683 SeenNewDbgInfoFormat = true; 6684 Lex.Lex(); 6685 6686 DbgRecord *DR; 6687 if (parseDebugRecord(DR, PFS)) 6688 return true; 6689 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord); 6690 } 6691 6692 // This instruction may have three possibilities for a name: a) none 6693 // specified, b) name specified "%foo =", c) number specified: "%4 =". 6694 LocTy NameLoc = Lex.getLoc(); 6695 int NameID = -1; 6696 NameStr = ""; 6697 6698 if (Lex.getKind() == lltok::LocalVarID) { 6699 NameID = Lex.getUIntVal(); 6700 Lex.Lex(); 6701 if (parseToken(lltok::equal, "expected '=' after instruction id")) 6702 return true; 6703 } else if (Lex.getKind() == lltok::LocalVar) { 6704 NameStr = Lex.getStrVal(); 6705 Lex.Lex(); 6706 if (parseToken(lltok::equal, "expected '=' after instruction name")) 6707 return true; 6708 } 6709 6710 switch (parseInstruction(Inst, BB, PFS)) { 6711 default: 6712 llvm_unreachable("Unknown parseInstruction result!"); 6713 case InstError: return true; 6714 case InstNormal: 6715 Inst->insertInto(BB, BB->end()); 6716 6717 // With a normal result, we check to see if the instruction is followed by 6718 // a comma and metadata. 6719 if (EatIfPresent(lltok::comma)) 6720 if (parseInstructionMetadata(*Inst)) 6721 return true; 6722 break; 6723 case InstExtraComma: 6724 Inst->insertInto(BB, BB->end()); 6725 6726 // If the instruction parser ate an extra comma at the end of it, it 6727 // *must* be followed by metadata. 6728 if (parseInstructionMetadata(*Inst)) 6729 return true; 6730 break; 6731 } 6732 6733 // Set the name on the instruction. 6734 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 6735 return true; 6736 6737 // Attach any preceding debug values to this instruction. 6738 for (DbgRecordPtr &DR : TrailingDbgRecord) 6739 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator()); 6740 TrailingDbgRecord.clear(); 6741 } while (!Inst->isTerminator()); 6742 6743 assert(TrailingDbgRecord.empty() && 6744 "All debug values should have been attached to an instruction."); 6745 6746 return false; 6747 } 6748 6749 /// parseDebugRecord 6750 /// ::= #dbg_label '(' MDNode ')' 6751 /// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ',' 6752 /// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')' 6753 bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) { 6754 using RecordKind = DbgRecord::Kind; 6755 using LocType = DbgVariableRecord::LocationType; 6756 LocTy DVRLoc = Lex.getLoc(); 6757 if (Lex.getKind() != lltok::DbgRecordType) 6758 return error(DVRLoc, "expected debug record type here"); 6759 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal()) 6760 .Case("declare", RecordKind::ValueKind) 6761 .Case("value", RecordKind::ValueKind) 6762 .Case("assign", RecordKind::ValueKind) 6763 .Case("label", RecordKind::LabelKind); 6764 6765 // Parsing labels is trivial; parse here and early exit, otherwise go into the 6766 // full DbgVariableRecord processing stage. 6767 if (RecordType == RecordKind::LabelKind) { 6768 Lex.Lex(); 6769 if (parseToken(lltok::lparen, "Expected '(' here")) 6770 return true; 6771 MDNode *Label; 6772 if (parseMDNode(Label)) 6773 return true; 6774 if (parseToken(lltok::comma, "Expected ',' here")) 6775 return true; 6776 MDNode *DbgLoc; 6777 if (parseMDNode(DbgLoc)) 6778 return true; 6779 if (parseToken(lltok::rparen, "Expected ')' here")) 6780 return true; 6781 DR = DbgLabelRecord::createUnresolvedDbgLabelRecord(Label, DbgLoc); 6782 return false; 6783 } 6784 6785 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal()) 6786 .Case("declare", LocType::Declare) 6787 .Case("value", LocType::Value) 6788 .Case("assign", LocType::Assign); 6789 6790 Lex.Lex(); 6791 if (parseToken(lltok::lparen, "Expected '(' here")) 6792 return true; 6793 6794 // Parse Value field. 6795 Metadata *ValLocMD; 6796 if (parseMetadata(ValLocMD, &PFS)) 6797 return true; 6798 if (parseToken(lltok::comma, "Expected ',' here")) 6799 return true; 6800 6801 // Parse Variable field. 6802 MDNode *Variable; 6803 if (parseMDNode(Variable)) 6804 return true; 6805 if (parseToken(lltok::comma, "Expected ',' here")) 6806 return true; 6807 6808 // Parse Expression field. 6809 MDNode *Expression; 6810 if (parseMDNode(Expression)) 6811 return true; 6812 if (parseToken(lltok::comma, "Expected ',' here")) 6813 return true; 6814 6815 // Parse additional fields for #dbg_assign. 6816 MDNode *AssignID = nullptr; 6817 Metadata *AddressLocation = nullptr; 6818 MDNode *AddressExpression = nullptr; 6819 if (ValueType == LocType::Assign) { 6820 // Parse DIAssignID. 6821 if (parseMDNode(AssignID)) 6822 return true; 6823 if (parseToken(lltok::comma, "Expected ',' here")) 6824 return true; 6825 6826 // Parse address ValueAsMetadata. 6827 if (parseMetadata(AddressLocation, &PFS)) 6828 return true; 6829 if (parseToken(lltok::comma, "Expected ',' here")) 6830 return true; 6831 6832 // Parse address DIExpression. 6833 if (parseMDNode(AddressExpression)) 6834 return true; 6835 if (parseToken(lltok::comma, "Expected ',' here")) 6836 return true; 6837 } 6838 6839 /// Parse DILocation. 6840 MDNode *DebugLoc; 6841 if (parseMDNode(DebugLoc)) 6842 return true; 6843 6844 if (parseToken(lltok::rparen, "Expected ')' here")) 6845 return true; 6846 DR = DbgVariableRecord::createUnresolvedDbgVariableRecord( 6847 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation, 6848 AddressExpression, DebugLoc); 6849 return false; 6850 } 6851 //===----------------------------------------------------------------------===// 6852 // Instruction Parsing. 6853 //===----------------------------------------------------------------------===// 6854 6855 /// parseInstruction - parse one of the many different instructions. 6856 /// 6857 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 6858 PerFunctionState &PFS) { 6859 lltok::Kind Token = Lex.getKind(); 6860 if (Token == lltok::Eof) 6861 return tokError("found end of file when expecting more instructions"); 6862 LocTy Loc = Lex.getLoc(); 6863 unsigned KeywordVal = Lex.getUIntVal(); 6864 Lex.Lex(); // Eat the keyword. 6865 6866 switch (Token) { 6867 default: 6868 return error(Loc, "expected instruction opcode"); 6869 // Terminator Instructions. 6870 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 6871 case lltok::kw_ret: 6872 return parseRet(Inst, BB, PFS); 6873 case lltok::kw_br: 6874 return parseBr(Inst, PFS); 6875 case lltok::kw_switch: 6876 return parseSwitch(Inst, PFS); 6877 case lltok::kw_indirectbr: 6878 return parseIndirectBr(Inst, PFS); 6879 case lltok::kw_invoke: 6880 return parseInvoke(Inst, PFS); 6881 case lltok::kw_resume: 6882 return parseResume(Inst, PFS); 6883 case lltok::kw_cleanupret: 6884 return parseCleanupRet(Inst, PFS); 6885 case lltok::kw_catchret: 6886 return parseCatchRet(Inst, PFS); 6887 case lltok::kw_catchswitch: 6888 return parseCatchSwitch(Inst, PFS); 6889 case lltok::kw_catchpad: 6890 return parseCatchPad(Inst, PFS); 6891 case lltok::kw_cleanuppad: 6892 return parseCleanupPad(Inst, PFS); 6893 case lltok::kw_callbr: 6894 return parseCallBr(Inst, PFS); 6895 // Unary Operators. 6896 case lltok::kw_fneg: { 6897 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6898 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 6899 if (Res != 0) 6900 return Res; 6901 if (FMF.any()) 6902 Inst->setFastMathFlags(FMF); 6903 return false; 6904 } 6905 // Binary Operators. 6906 case lltok::kw_add: 6907 case lltok::kw_sub: 6908 case lltok::kw_mul: 6909 case lltok::kw_shl: { 6910 bool NUW = EatIfPresent(lltok::kw_nuw); 6911 bool NSW = EatIfPresent(lltok::kw_nsw); 6912 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 6913 6914 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6915 return true; 6916 6917 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 6918 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 6919 return false; 6920 } 6921 case lltok::kw_fadd: 6922 case lltok::kw_fsub: 6923 case lltok::kw_fmul: 6924 case lltok::kw_fdiv: 6925 case lltok::kw_frem: { 6926 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6927 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 6928 if (Res != 0) 6929 return Res; 6930 if (FMF.any()) 6931 Inst->setFastMathFlags(FMF); 6932 return 0; 6933 } 6934 6935 case lltok::kw_sdiv: 6936 case lltok::kw_udiv: 6937 case lltok::kw_lshr: 6938 case lltok::kw_ashr: { 6939 bool Exact = EatIfPresent(lltok::kw_exact); 6940 6941 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6942 return true; 6943 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 6944 return false; 6945 } 6946 6947 case lltok::kw_urem: 6948 case lltok::kw_srem: 6949 return parseArithmetic(Inst, PFS, KeywordVal, 6950 /*IsFP*/ false); 6951 case lltok::kw_or: { 6952 bool Disjoint = EatIfPresent(lltok::kw_disjoint); 6953 if (parseLogical(Inst, PFS, KeywordVal)) 6954 return true; 6955 if (Disjoint) 6956 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true); 6957 return false; 6958 } 6959 case lltok::kw_and: 6960 case lltok::kw_xor: 6961 return parseLogical(Inst, PFS, KeywordVal); 6962 case lltok::kw_icmp: { 6963 bool SameSign = EatIfPresent(lltok::kw_samesign); 6964 if (parseCompare(Inst, PFS, KeywordVal)) 6965 return true; 6966 if (SameSign) 6967 cast<ICmpInst>(Inst)->setSameSign(); 6968 return false; 6969 } 6970 case lltok::kw_fcmp: { 6971 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6972 int Res = parseCompare(Inst, PFS, KeywordVal); 6973 if (Res != 0) 6974 return Res; 6975 if (FMF.any()) 6976 Inst->setFastMathFlags(FMF); 6977 return 0; 6978 } 6979 6980 // Casts. 6981 case lltok::kw_uitofp: 6982 case lltok::kw_zext: { 6983 bool NonNeg = EatIfPresent(lltok::kw_nneg); 6984 bool Res = parseCast(Inst, PFS, KeywordVal); 6985 if (Res != 0) 6986 return Res; 6987 if (NonNeg) 6988 Inst->setNonNeg(); 6989 return 0; 6990 } 6991 case lltok::kw_trunc: { 6992 bool NUW = EatIfPresent(lltok::kw_nuw); 6993 bool NSW = EatIfPresent(lltok::kw_nsw); 6994 if (!NUW) 6995 NUW = EatIfPresent(lltok::kw_nuw); 6996 if (parseCast(Inst, PFS, KeywordVal)) 6997 return true; 6998 if (NUW) 6999 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true); 7000 if (NSW) 7001 cast<TruncInst>(Inst)->setHasNoSignedWrap(true); 7002 return false; 7003 } 7004 case lltok::kw_sext: 7005 case lltok::kw_fptrunc: 7006 case lltok::kw_fpext: 7007 case lltok::kw_bitcast: 7008 case lltok::kw_addrspacecast: 7009 case lltok::kw_sitofp: 7010 case lltok::kw_fptoui: 7011 case lltok::kw_fptosi: 7012 case lltok::kw_inttoptr: 7013 case lltok::kw_ptrtoint: 7014 return parseCast(Inst, PFS, KeywordVal); 7015 // Other. 7016 case lltok::kw_select: { 7017 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7018 int Res = parseSelect(Inst, PFS); 7019 if (Res != 0) 7020 return Res; 7021 if (FMF.any()) { 7022 if (!isa<FPMathOperator>(Inst)) 7023 return error(Loc, "fast-math-flags specified for select without " 7024 "floating-point scalar or vector return type"); 7025 Inst->setFastMathFlags(FMF); 7026 } 7027 return 0; 7028 } 7029 case lltok::kw_va_arg: 7030 return parseVAArg(Inst, PFS); 7031 case lltok::kw_extractelement: 7032 return parseExtractElement(Inst, PFS); 7033 case lltok::kw_insertelement: 7034 return parseInsertElement(Inst, PFS); 7035 case lltok::kw_shufflevector: 7036 return parseShuffleVector(Inst, PFS); 7037 case lltok::kw_phi: { 7038 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7039 int Res = parsePHI(Inst, PFS); 7040 if (Res != 0) 7041 return Res; 7042 if (FMF.any()) { 7043 if (!isa<FPMathOperator>(Inst)) 7044 return error(Loc, "fast-math-flags specified for phi without " 7045 "floating-point scalar or vector return type"); 7046 Inst->setFastMathFlags(FMF); 7047 } 7048 return 0; 7049 } 7050 case lltok::kw_landingpad: 7051 return parseLandingPad(Inst, PFS); 7052 case lltok::kw_freeze: 7053 return parseFreeze(Inst, PFS); 7054 // Call. 7055 case lltok::kw_call: 7056 return parseCall(Inst, PFS, CallInst::TCK_None); 7057 case lltok::kw_tail: 7058 return parseCall(Inst, PFS, CallInst::TCK_Tail); 7059 case lltok::kw_musttail: 7060 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 7061 case lltok::kw_notail: 7062 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 7063 // Memory. 7064 case lltok::kw_alloca: 7065 return parseAlloc(Inst, PFS); 7066 case lltok::kw_load: 7067 return parseLoad(Inst, PFS); 7068 case lltok::kw_store: 7069 return parseStore(Inst, PFS); 7070 case lltok::kw_cmpxchg: 7071 return parseCmpXchg(Inst, PFS); 7072 case lltok::kw_atomicrmw: 7073 return parseAtomicRMW(Inst, PFS); 7074 case lltok::kw_fence: 7075 return parseFence(Inst, PFS); 7076 case lltok::kw_getelementptr: 7077 return parseGetElementPtr(Inst, PFS); 7078 case lltok::kw_extractvalue: 7079 return parseExtractValue(Inst, PFS); 7080 case lltok::kw_insertvalue: 7081 return parseInsertValue(Inst, PFS); 7082 } 7083 } 7084 7085 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 7086 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 7087 if (Opc == Instruction::FCmp) { 7088 switch (Lex.getKind()) { 7089 default: 7090 return tokError("expected fcmp predicate (e.g. 'oeq')"); 7091 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 7092 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 7093 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 7094 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 7095 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 7096 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 7097 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 7098 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 7099 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 7100 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 7101 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 7102 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 7103 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 7104 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 7105 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 7106 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 7107 } 7108 } else { 7109 switch (Lex.getKind()) { 7110 default: 7111 return tokError("expected icmp predicate (e.g. 'eq')"); 7112 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 7113 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 7114 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 7115 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 7116 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 7117 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 7118 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 7119 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 7120 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 7121 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 7122 } 7123 } 7124 Lex.Lex(); 7125 return false; 7126 } 7127 7128 //===----------------------------------------------------------------------===// 7129 // Terminator Instructions. 7130 //===----------------------------------------------------------------------===// 7131 7132 /// parseRet - parse a return instruction. 7133 /// ::= 'ret' void (',' !dbg, !1)* 7134 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 7135 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 7136 PerFunctionState &PFS) { 7137 SMLoc TypeLoc = Lex.getLoc(); 7138 Type *Ty = nullptr; 7139 if (parseType(Ty, true /*void allowed*/)) 7140 return true; 7141 7142 Type *ResType = PFS.getFunction().getReturnType(); 7143 7144 if (Ty->isVoidTy()) { 7145 if (!ResType->isVoidTy()) 7146 return error(TypeLoc, "value doesn't match function result type '" + 7147 getTypeString(ResType) + "'"); 7148 7149 Inst = ReturnInst::Create(Context); 7150 return false; 7151 } 7152 7153 Value *RV; 7154 if (parseValue(Ty, RV, PFS)) 7155 return true; 7156 7157 if (ResType != RV->getType()) 7158 return error(TypeLoc, "value doesn't match function result type '" + 7159 getTypeString(ResType) + "'"); 7160 7161 Inst = ReturnInst::Create(Context, RV); 7162 return false; 7163 } 7164 7165 /// parseBr 7166 /// ::= 'br' TypeAndValue 7167 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7168 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 7169 LocTy Loc, Loc2; 7170 Value *Op0; 7171 BasicBlock *Op1, *Op2; 7172 if (parseTypeAndValue(Op0, Loc, PFS)) 7173 return true; 7174 7175 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 7176 Inst = BranchInst::Create(BB); 7177 return false; 7178 } 7179 7180 if (Op0->getType() != Type::getInt1Ty(Context)) 7181 return error(Loc, "branch condition must have 'i1' type"); 7182 7183 if (parseToken(lltok::comma, "expected ',' after branch condition") || 7184 parseTypeAndBasicBlock(Op1, Loc, PFS) || 7185 parseToken(lltok::comma, "expected ',' after true destination") || 7186 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 7187 return true; 7188 7189 Inst = BranchInst::Create(Op1, Op2, Op0); 7190 return false; 7191 } 7192 7193 /// parseSwitch 7194 /// Instruction 7195 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 7196 /// JumpTable 7197 /// ::= (TypeAndValue ',' TypeAndValue)* 7198 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 7199 LocTy CondLoc, BBLoc; 7200 Value *Cond; 7201 BasicBlock *DefaultBB; 7202 if (parseTypeAndValue(Cond, CondLoc, PFS) || 7203 parseToken(lltok::comma, "expected ',' after switch condition") || 7204 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 7205 parseToken(lltok::lsquare, "expected '[' with switch table")) 7206 return true; 7207 7208 if (!Cond->getType()->isIntegerTy()) 7209 return error(CondLoc, "switch condition must have integer type"); 7210 7211 // parse the jump table pairs. 7212 SmallPtrSet<Value*, 32> SeenCases; 7213 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 7214 while (Lex.getKind() != lltok::rsquare) { 7215 Value *Constant; 7216 BasicBlock *DestBB; 7217 7218 if (parseTypeAndValue(Constant, CondLoc, PFS) || 7219 parseToken(lltok::comma, "expected ',' after case value") || 7220 parseTypeAndBasicBlock(DestBB, PFS)) 7221 return true; 7222 7223 if (!SeenCases.insert(Constant).second) 7224 return error(CondLoc, "duplicate case value in switch"); 7225 if (!isa<ConstantInt>(Constant)) 7226 return error(CondLoc, "case value is not a constant integer"); 7227 7228 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 7229 } 7230 7231 Lex.Lex(); // Eat the ']'. 7232 7233 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 7234 for (unsigned i = 0, e = Table.size(); i != e; ++i) 7235 SI->addCase(Table[i].first, Table[i].second); 7236 Inst = SI; 7237 return false; 7238 } 7239 7240 /// parseIndirectBr 7241 /// Instruction 7242 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 7243 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 7244 LocTy AddrLoc; 7245 Value *Address; 7246 if (parseTypeAndValue(Address, AddrLoc, PFS) || 7247 parseToken(lltok::comma, "expected ',' after indirectbr address") || 7248 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 7249 return true; 7250 7251 if (!Address->getType()->isPointerTy()) 7252 return error(AddrLoc, "indirectbr address must have pointer type"); 7253 7254 // parse the destination list. 7255 SmallVector<BasicBlock*, 16> DestList; 7256 7257 if (Lex.getKind() != lltok::rsquare) { 7258 BasicBlock *DestBB; 7259 if (parseTypeAndBasicBlock(DestBB, PFS)) 7260 return true; 7261 DestList.push_back(DestBB); 7262 7263 while (EatIfPresent(lltok::comma)) { 7264 if (parseTypeAndBasicBlock(DestBB, PFS)) 7265 return true; 7266 DestList.push_back(DestBB); 7267 } 7268 } 7269 7270 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 7271 return true; 7272 7273 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 7274 for (BasicBlock *Dest : DestList) 7275 IBI->addDestination(Dest); 7276 Inst = IBI; 7277 return false; 7278 } 7279 7280 // If RetType is a non-function pointer type, then this is the short syntax 7281 // for the call, which means that RetType is just the return type. Infer the 7282 // rest of the function argument types from the arguments that are present. 7283 bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList, 7284 FunctionType *&FuncTy) { 7285 FuncTy = dyn_cast<FunctionType>(RetType); 7286 if (!FuncTy) { 7287 // Pull out the types of all of the arguments... 7288 SmallVector<Type *, 8> ParamTypes; 7289 ParamTypes.reserve(ArgList.size()); 7290 for (const ParamInfo &Arg : ArgList) 7291 ParamTypes.push_back(Arg.V->getType()); 7292 7293 if (!FunctionType::isValidReturnType(RetType)) 7294 return true; 7295 7296 FuncTy = FunctionType::get(RetType, ParamTypes, false); 7297 } 7298 return false; 7299 } 7300 7301 /// parseInvoke 7302 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 7303 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 7304 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 7305 LocTy CallLoc = Lex.getLoc(); 7306 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 7307 std::vector<unsigned> FwdRefAttrGrps; 7308 LocTy NoBuiltinLoc; 7309 unsigned CC; 7310 unsigned InvokeAddrSpace; 7311 Type *RetType = nullptr; 7312 LocTy RetTypeLoc; 7313 ValID CalleeID; 7314 SmallVector<ParamInfo, 16> ArgList; 7315 SmallVector<OperandBundleDef, 2> BundleList; 7316 7317 BasicBlock *NormalBB, *UnwindBB; 7318 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7319 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 7320 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7321 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 7322 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 7323 NoBuiltinLoc) || 7324 parseOptionalOperandBundles(BundleList, PFS) || 7325 parseToken(lltok::kw_to, "expected 'to' in invoke") || 7326 parseTypeAndBasicBlock(NormalBB, PFS) || 7327 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 7328 parseTypeAndBasicBlock(UnwindBB, PFS)) 7329 return true; 7330 7331 // If RetType is a non-function pointer type, then this is the short syntax 7332 // for the call, which means that RetType is just the return type. Infer the 7333 // rest of the function argument types from the arguments that are present. 7334 FunctionType *Ty; 7335 if (resolveFunctionType(RetType, ArgList, Ty)) 7336 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7337 7338 CalleeID.FTy = Ty; 7339 7340 // Look up the callee. 7341 Value *Callee; 7342 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 7343 Callee, &PFS)) 7344 return true; 7345 7346 // Set up the Attribute for the function. 7347 SmallVector<Value *, 8> Args; 7348 SmallVector<AttributeSet, 8> ArgAttrs; 7349 7350 // Loop through FunctionType's arguments and ensure they are specified 7351 // correctly. Also, gather any parameter attributes. 7352 FunctionType::param_iterator I = Ty->param_begin(); 7353 FunctionType::param_iterator E = Ty->param_end(); 7354 for (const ParamInfo &Arg : ArgList) { 7355 Type *ExpectedTy = nullptr; 7356 if (I != E) { 7357 ExpectedTy = *I++; 7358 } else if (!Ty->isVarArg()) { 7359 return error(Arg.Loc, "too many arguments specified"); 7360 } 7361 7362 if (ExpectedTy && ExpectedTy != Arg.V->getType()) 7363 return error(Arg.Loc, "argument is not of expected type '" + 7364 getTypeString(ExpectedTy) + "'"); 7365 Args.push_back(Arg.V); 7366 ArgAttrs.push_back(Arg.Attrs); 7367 } 7368 7369 if (I != E) 7370 return error(CallLoc, "not enough parameters specified for call"); 7371 7372 // Finish off the Attribute and check them 7373 AttributeList PAL = 7374 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7375 AttributeSet::get(Context, RetAttrs), ArgAttrs); 7376 7377 InvokeInst *II = 7378 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 7379 II->setCallingConv(CC); 7380 II->setAttributes(PAL); 7381 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 7382 Inst = II; 7383 return false; 7384 } 7385 7386 /// parseResume 7387 /// ::= 'resume' TypeAndValue 7388 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 7389 Value *Exn; LocTy ExnLoc; 7390 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 7391 return true; 7392 7393 ResumeInst *RI = ResumeInst::Create(Exn); 7394 Inst = RI; 7395 return false; 7396 } 7397 7398 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 7399 PerFunctionState &PFS) { 7400 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 7401 return true; 7402 7403 while (Lex.getKind() != lltok::rsquare) { 7404 // If this isn't the first argument, we need a comma. 7405 if (!Args.empty() && 7406 parseToken(lltok::comma, "expected ',' in argument list")) 7407 return true; 7408 7409 // parse the argument. 7410 LocTy ArgLoc; 7411 Type *ArgTy = nullptr; 7412 if (parseType(ArgTy, ArgLoc)) 7413 return true; 7414 7415 Value *V; 7416 if (ArgTy->isMetadataTy()) { 7417 if (parseMetadataAsValue(V, PFS)) 7418 return true; 7419 } else { 7420 if (parseValue(ArgTy, V, PFS)) 7421 return true; 7422 } 7423 Args.push_back(V); 7424 } 7425 7426 Lex.Lex(); // Lex the ']'. 7427 return false; 7428 } 7429 7430 /// parseCleanupRet 7431 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 7432 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 7433 Value *CleanupPad = nullptr; 7434 7435 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 7436 return true; 7437 7438 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 7439 return true; 7440 7441 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 7442 return true; 7443 7444 BasicBlock *UnwindBB = nullptr; 7445 if (Lex.getKind() == lltok::kw_to) { 7446 Lex.Lex(); 7447 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 7448 return true; 7449 } else { 7450 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 7451 return true; 7452 } 7453 } 7454 7455 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 7456 return false; 7457 } 7458 7459 /// parseCatchRet 7460 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 7461 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 7462 Value *CatchPad = nullptr; 7463 7464 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 7465 return true; 7466 7467 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 7468 return true; 7469 7470 BasicBlock *BB; 7471 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 7472 parseTypeAndBasicBlock(BB, PFS)) 7473 return true; 7474 7475 Inst = CatchReturnInst::Create(CatchPad, BB); 7476 return false; 7477 } 7478 7479 /// parseCatchSwitch 7480 /// ::= 'catchswitch' within Parent 7481 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 7482 Value *ParentPad; 7483 7484 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 7485 return true; 7486 7487 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 7488 Lex.getKind() != lltok::LocalVarID) 7489 return tokError("expected scope value for catchswitch"); 7490 7491 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 7492 return true; 7493 7494 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 7495 return true; 7496 7497 SmallVector<BasicBlock *, 32> Table; 7498 do { 7499 BasicBlock *DestBB; 7500 if (parseTypeAndBasicBlock(DestBB, PFS)) 7501 return true; 7502 Table.push_back(DestBB); 7503 } while (EatIfPresent(lltok::comma)); 7504 7505 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 7506 return true; 7507 7508 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 7509 return true; 7510 7511 BasicBlock *UnwindBB = nullptr; 7512 if (EatIfPresent(lltok::kw_to)) { 7513 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 7514 return true; 7515 } else { 7516 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 7517 return true; 7518 } 7519 7520 auto *CatchSwitch = 7521 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 7522 for (BasicBlock *DestBB : Table) 7523 CatchSwitch->addHandler(DestBB); 7524 Inst = CatchSwitch; 7525 return false; 7526 } 7527 7528 /// parseCatchPad 7529 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 7530 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 7531 Value *CatchSwitch = nullptr; 7532 7533 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 7534 return true; 7535 7536 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 7537 return tokError("expected scope value for catchpad"); 7538 7539 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 7540 return true; 7541 7542 SmallVector<Value *, 8> Args; 7543 if (parseExceptionArgs(Args, PFS)) 7544 return true; 7545 7546 Inst = CatchPadInst::Create(CatchSwitch, Args); 7547 return false; 7548 } 7549 7550 /// parseCleanupPad 7551 /// ::= 'cleanuppad' within Parent ParamList 7552 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 7553 Value *ParentPad = nullptr; 7554 7555 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 7556 return true; 7557 7558 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 7559 Lex.getKind() != lltok::LocalVarID) 7560 return tokError("expected scope value for cleanuppad"); 7561 7562 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 7563 return true; 7564 7565 SmallVector<Value *, 8> Args; 7566 if (parseExceptionArgs(Args, PFS)) 7567 return true; 7568 7569 Inst = CleanupPadInst::Create(ParentPad, Args); 7570 return false; 7571 } 7572 7573 //===----------------------------------------------------------------------===// 7574 // Unary Operators. 7575 //===----------------------------------------------------------------------===// 7576 7577 /// parseUnaryOp 7578 /// ::= UnaryOp TypeAndValue ',' Value 7579 /// 7580 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 7581 /// operand is allowed. 7582 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 7583 unsigned Opc, bool IsFP) { 7584 LocTy Loc; Value *LHS; 7585 if (parseTypeAndValue(LHS, Loc, PFS)) 7586 return true; 7587 7588 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 7589 : LHS->getType()->isIntOrIntVectorTy(); 7590 7591 if (!Valid) 7592 return error(Loc, "invalid operand type for instruction"); 7593 7594 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 7595 return false; 7596 } 7597 7598 /// parseCallBr 7599 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 7600 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 7601 /// '[' LabelList ']' 7602 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 7603 LocTy CallLoc = Lex.getLoc(); 7604 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 7605 std::vector<unsigned> FwdRefAttrGrps; 7606 LocTy NoBuiltinLoc; 7607 unsigned CC; 7608 Type *RetType = nullptr; 7609 LocTy RetTypeLoc; 7610 ValID CalleeID; 7611 SmallVector<ParamInfo, 16> ArgList; 7612 SmallVector<OperandBundleDef, 2> BundleList; 7613 7614 BasicBlock *DefaultDest; 7615 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7616 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7617 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 7618 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 7619 NoBuiltinLoc) || 7620 parseOptionalOperandBundles(BundleList, PFS) || 7621 parseToken(lltok::kw_to, "expected 'to' in callbr") || 7622 parseTypeAndBasicBlock(DefaultDest, PFS) || 7623 parseToken(lltok::lsquare, "expected '[' in callbr")) 7624 return true; 7625 7626 // parse the destination list. 7627 SmallVector<BasicBlock *, 16> IndirectDests; 7628 7629 if (Lex.getKind() != lltok::rsquare) { 7630 BasicBlock *DestBB; 7631 if (parseTypeAndBasicBlock(DestBB, PFS)) 7632 return true; 7633 IndirectDests.push_back(DestBB); 7634 7635 while (EatIfPresent(lltok::comma)) { 7636 if (parseTypeAndBasicBlock(DestBB, PFS)) 7637 return true; 7638 IndirectDests.push_back(DestBB); 7639 } 7640 } 7641 7642 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 7643 return true; 7644 7645 // If RetType is a non-function pointer type, then this is the short syntax 7646 // for the call, which means that RetType is just the return type. Infer the 7647 // rest of the function argument types from the arguments that are present. 7648 FunctionType *Ty; 7649 if (resolveFunctionType(RetType, ArgList, Ty)) 7650 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7651 7652 CalleeID.FTy = Ty; 7653 7654 // Look up the callee. 7655 Value *Callee; 7656 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 7657 return true; 7658 7659 // Set up the Attribute for the function. 7660 SmallVector<Value *, 8> Args; 7661 SmallVector<AttributeSet, 8> ArgAttrs; 7662 7663 // Loop through FunctionType's arguments and ensure they are specified 7664 // correctly. Also, gather any parameter attributes. 7665 FunctionType::param_iterator I = Ty->param_begin(); 7666 FunctionType::param_iterator E = Ty->param_end(); 7667 for (const ParamInfo &Arg : ArgList) { 7668 Type *ExpectedTy = nullptr; 7669 if (I != E) { 7670 ExpectedTy = *I++; 7671 } else if (!Ty->isVarArg()) { 7672 return error(Arg.Loc, "too many arguments specified"); 7673 } 7674 7675 if (ExpectedTy && ExpectedTy != Arg.V->getType()) 7676 return error(Arg.Loc, "argument is not of expected type '" + 7677 getTypeString(ExpectedTy) + "'"); 7678 Args.push_back(Arg.V); 7679 ArgAttrs.push_back(Arg.Attrs); 7680 } 7681 7682 if (I != E) 7683 return error(CallLoc, "not enough parameters specified for call"); 7684 7685 // Finish off the Attribute and check them 7686 AttributeList PAL = 7687 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7688 AttributeSet::get(Context, RetAttrs), ArgAttrs); 7689 7690 CallBrInst *CBI = 7691 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 7692 BundleList); 7693 CBI->setCallingConv(CC); 7694 CBI->setAttributes(PAL); 7695 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 7696 Inst = CBI; 7697 return false; 7698 } 7699 7700 //===----------------------------------------------------------------------===// 7701 // Binary Operators. 7702 //===----------------------------------------------------------------------===// 7703 7704 /// parseArithmetic 7705 /// ::= ArithmeticOps TypeAndValue ',' Value 7706 /// 7707 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 7708 /// operand is allowed. 7709 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 7710 unsigned Opc, bool IsFP) { 7711 LocTy Loc; Value *LHS, *RHS; 7712 if (parseTypeAndValue(LHS, Loc, PFS) || 7713 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 7714 parseValue(LHS->getType(), RHS, PFS)) 7715 return true; 7716 7717 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 7718 : LHS->getType()->isIntOrIntVectorTy(); 7719 7720 if (!Valid) 7721 return error(Loc, "invalid operand type for instruction"); 7722 7723 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 7724 return false; 7725 } 7726 7727 /// parseLogical 7728 /// ::= ArithmeticOps TypeAndValue ',' Value { 7729 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 7730 unsigned Opc) { 7731 LocTy Loc; Value *LHS, *RHS; 7732 if (parseTypeAndValue(LHS, Loc, PFS) || 7733 parseToken(lltok::comma, "expected ',' in logical operation") || 7734 parseValue(LHS->getType(), RHS, PFS)) 7735 return true; 7736 7737 if (!LHS->getType()->isIntOrIntVectorTy()) 7738 return error(Loc, 7739 "instruction requires integer or integer vector operands"); 7740 7741 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 7742 return false; 7743 } 7744 7745 /// parseCompare 7746 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 7747 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 7748 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 7749 unsigned Opc) { 7750 // parse the integer/fp comparison predicate. 7751 LocTy Loc; 7752 unsigned Pred; 7753 Value *LHS, *RHS; 7754 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 7755 parseToken(lltok::comma, "expected ',' after compare value") || 7756 parseValue(LHS->getType(), RHS, PFS)) 7757 return true; 7758 7759 if (Opc == Instruction::FCmp) { 7760 if (!LHS->getType()->isFPOrFPVectorTy()) 7761 return error(Loc, "fcmp requires floating point operands"); 7762 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 7763 } else { 7764 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 7765 if (!LHS->getType()->isIntOrIntVectorTy() && 7766 !LHS->getType()->isPtrOrPtrVectorTy()) 7767 return error(Loc, "icmp requires integer operands"); 7768 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 7769 } 7770 return false; 7771 } 7772 7773 //===----------------------------------------------------------------------===// 7774 // Other Instructions. 7775 //===----------------------------------------------------------------------===// 7776 7777 /// parseCast 7778 /// ::= CastOpc TypeAndValue 'to' Type 7779 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 7780 unsigned Opc) { 7781 LocTy Loc; 7782 Value *Op; 7783 Type *DestTy = nullptr; 7784 if (parseTypeAndValue(Op, Loc, PFS) || 7785 parseToken(lltok::kw_to, "expected 'to' after cast value") || 7786 parseType(DestTy)) 7787 return true; 7788 7789 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 7790 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 7791 return error(Loc, "invalid cast opcode for cast from '" + 7792 getTypeString(Op->getType()) + "' to '" + 7793 getTypeString(DestTy) + "'"); 7794 } 7795 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 7796 return false; 7797 } 7798 7799 /// parseSelect 7800 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7801 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 7802 LocTy Loc; 7803 Value *Op0, *Op1, *Op2; 7804 if (parseTypeAndValue(Op0, Loc, PFS) || 7805 parseToken(lltok::comma, "expected ',' after select condition") || 7806 parseTypeAndValue(Op1, PFS) || 7807 parseToken(lltok::comma, "expected ',' after select value") || 7808 parseTypeAndValue(Op2, PFS)) 7809 return true; 7810 7811 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 7812 return error(Loc, Reason); 7813 7814 Inst = SelectInst::Create(Op0, Op1, Op2); 7815 return false; 7816 } 7817 7818 /// parseVAArg 7819 /// ::= 'va_arg' TypeAndValue ',' Type 7820 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 7821 Value *Op; 7822 Type *EltTy = nullptr; 7823 LocTy TypeLoc; 7824 if (parseTypeAndValue(Op, PFS) || 7825 parseToken(lltok::comma, "expected ',' after vaarg operand") || 7826 parseType(EltTy, TypeLoc)) 7827 return true; 7828 7829 if (!EltTy->isFirstClassType()) 7830 return error(TypeLoc, "va_arg requires operand with first class type"); 7831 7832 Inst = new VAArgInst(Op, EltTy); 7833 return false; 7834 } 7835 7836 /// parseExtractElement 7837 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 7838 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 7839 LocTy Loc; 7840 Value *Op0, *Op1; 7841 if (parseTypeAndValue(Op0, Loc, PFS) || 7842 parseToken(lltok::comma, "expected ',' after extract value") || 7843 parseTypeAndValue(Op1, PFS)) 7844 return true; 7845 7846 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 7847 return error(Loc, "invalid extractelement operands"); 7848 7849 Inst = ExtractElementInst::Create(Op0, Op1); 7850 return false; 7851 } 7852 7853 /// parseInsertElement 7854 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7855 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 7856 LocTy Loc; 7857 Value *Op0, *Op1, *Op2; 7858 if (parseTypeAndValue(Op0, Loc, PFS) || 7859 parseToken(lltok::comma, "expected ',' after insertelement value") || 7860 parseTypeAndValue(Op1, PFS) || 7861 parseToken(lltok::comma, "expected ',' after insertelement value") || 7862 parseTypeAndValue(Op2, PFS)) 7863 return true; 7864 7865 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 7866 return error(Loc, "invalid insertelement operands"); 7867 7868 Inst = InsertElementInst::Create(Op0, Op1, Op2); 7869 return false; 7870 } 7871 7872 /// parseShuffleVector 7873 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7874 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 7875 LocTy Loc; 7876 Value *Op0, *Op1, *Op2; 7877 if (parseTypeAndValue(Op0, Loc, PFS) || 7878 parseToken(lltok::comma, "expected ',' after shuffle mask") || 7879 parseTypeAndValue(Op1, PFS) || 7880 parseToken(lltok::comma, "expected ',' after shuffle value") || 7881 parseTypeAndValue(Op2, PFS)) 7882 return true; 7883 7884 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 7885 return error(Loc, "invalid shufflevector operands"); 7886 7887 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 7888 return false; 7889 } 7890 7891 /// parsePHI 7892 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 7893 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 7894 Type *Ty = nullptr; LocTy TypeLoc; 7895 Value *Op0, *Op1; 7896 7897 if (parseType(Ty, TypeLoc)) 7898 return true; 7899 7900 if (!Ty->isFirstClassType()) 7901 return error(TypeLoc, "phi node must have first class type"); 7902 7903 bool First = true; 7904 bool AteExtraComma = false; 7905 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 7906 7907 while (true) { 7908 if (First) { 7909 if (Lex.getKind() != lltok::lsquare) 7910 break; 7911 First = false; 7912 } else if (!EatIfPresent(lltok::comma)) 7913 break; 7914 7915 if (Lex.getKind() == lltok::MetadataVar) { 7916 AteExtraComma = true; 7917 break; 7918 } 7919 7920 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 7921 parseValue(Ty, Op0, PFS) || 7922 parseToken(lltok::comma, "expected ',' after insertelement value") || 7923 parseValue(Type::getLabelTy(Context), Op1, PFS) || 7924 parseToken(lltok::rsquare, "expected ']' in phi value list")) 7925 return true; 7926 7927 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 7928 } 7929 7930 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 7931 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 7932 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 7933 Inst = PN; 7934 return AteExtraComma ? InstExtraComma : InstNormal; 7935 } 7936 7937 /// parseLandingPad 7938 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 7939 /// Clause 7940 /// ::= 'catch' TypeAndValue 7941 /// ::= 'filter' 7942 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 7943 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 7944 Type *Ty = nullptr; LocTy TyLoc; 7945 7946 if (parseType(Ty, TyLoc)) 7947 return true; 7948 7949 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 7950 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 7951 7952 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 7953 LandingPadInst::ClauseType CT; 7954 if (EatIfPresent(lltok::kw_catch)) 7955 CT = LandingPadInst::Catch; 7956 else if (EatIfPresent(lltok::kw_filter)) 7957 CT = LandingPadInst::Filter; 7958 else 7959 return tokError("expected 'catch' or 'filter' clause type"); 7960 7961 Value *V; 7962 LocTy VLoc; 7963 if (parseTypeAndValue(V, VLoc, PFS)) 7964 return true; 7965 7966 // A 'catch' type expects a non-array constant. A filter clause expects an 7967 // array constant. 7968 if (CT == LandingPadInst::Catch) { 7969 if (isa<ArrayType>(V->getType())) 7970 return error(VLoc, "'catch' clause has an invalid type"); 7971 } else { 7972 if (!isa<ArrayType>(V->getType())) 7973 return error(VLoc, "'filter' clause has an invalid type"); 7974 } 7975 7976 Constant *CV = dyn_cast<Constant>(V); 7977 if (!CV) 7978 return error(VLoc, "clause argument must be a constant"); 7979 LP->addClause(CV); 7980 } 7981 7982 Inst = LP.release(); 7983 return false; 7984 } 7985 7986 /// parseFreeze 7987 /// ::= 'freeze' Type Value 7988 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 7989 LocTy Loc; 7990 Value *Op; 7991 if (parseTypeAndValue(Op, Loc, PFS)) 7992 return true; 7993 7994 Inst = new FreezeInst(Op); 7995 return false; 7996 } 7997 7998 /// parseCall 7999 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 8000 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8001 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 8002 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8003 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 8004 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8005 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 8006 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8007 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 8008 CallInst::TailCallKind TCK) { 8009 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 8010 std::vector<unsigned> FwdRefAttrGrps; 8011 LocTy BuiltinLoc; 8012 unsigned CallAddrSpace; 8013 unsigned CC; 8014 Type *RetType = nullptr; 8015 LocTy RetTypeLoc; 8016 ValID CalleeID; 8017 SmallVector<ParamInfo, 16> ArgList; 8018 SmallVector<OperandBundleDef, 2> BundleList; 8019 LocTy CallLoc = Lex.getLoc(); 8020 8021 if (TCK != CallInst::TCK_None && 8022 parseToken(lltok::kw_call, 8023 "expected 'tail call', 'musttail call', or 'notail call'")) 8024 return true; 8025 8026 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 8027 8028 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 8029 parseOptionalProgramAddrSpace(CallAddrSpace) || 8030 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 8031 parseValID(CalleeID, &PFS) || 8032 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 8033 PFS.getFunction().isVarArg()) || 8034 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 8035 parseOptionalOperandBundles(BundleList, PFS)) 8036 return true; 8037 8038 // If RetType is a non-function pointer type, then this is the short syntax 8039 // for the call, which means that RetType is just the return type. Infer the 8040 // rest of the function argument types from the arguments that are present. 8041 FunctionType *Ty; 8042 if (resolveFunctionType(RetType, ArgList, Ty)) 8043 return error(RetTypeLoc, "Invalid result type for LLVM function"); 8044 8045 CalleeID.FTy = Ty; 8046 8047 // Look up the callee. 8048 Value *Callee; 8049 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 8050 &PFS)) 8051 return true; 8052 8053 // Set up the Attribute for the function. 8054 SmallVector<AttributeSet, 8> Attrs; 8055 8056 SmallVector<Value*, 8> Args; 8057 8058 // Loop through FunctionType's arguments and ensure they are specified 8059 // correctly. Also, gather any parameter attributes. 8060 FunctionType::param_iterator I = Ty->param_begin(); 8061 FunctionType::param_iterator E = Ty->param_end(); 8062 for (const ParamInfo &Arg : ArgList) { 8063 Type *ExpectedTy = nullptr; 8064 if (I != E) { 8065 ExpectedTy = *I++; 8066 } else if (!Ty->isVarArg()) { 8067 return error(Arg.Loc, "too many arguments specified"); 8068 } 8069 8070 if (ExpectedTy && ExpectedTy != Arg.V->getType()) 8071 return error(Arg.Loc, "argument is not of expected type '" + 8072 getTypeString(ExpectedTy) + "'"); 8073 Args.push_back(Arg.V); 8074 Attrs.push_back(Arg.Attrs); 8075 } 8076 8077 if (I != E) 8078 return error(CallLoc, "not enough parameters specified for call"); 8079 8080 // Finish off the Attribute and check them 8081 AttributeList PAL = 8082 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 8083 AttributeSet::get(Context, RetAttrs), Attrs); 8084 8085 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 8086 CI->setTailCallKind(TCK); 8087 CI->setCallingConv(CC); 8088 if (FMF.any()) { 8089 if (!isa<FPMathOperator>(CI)) { 8090 CI->deleteValue(); 8091 return error(CallLoc, "fast-math-flags specified for call without " 8092 "floating-point scalar or vector return type"); 8093 } 8094 CI->setFastMathFlags(FMF); 8095 } 8096 8097 if (CalleeID.Kind == ValID::t_GlobalName && 8098 isOldDbgFormatIntrinsic(CalleeID.StrVal)) { 8099 if (SeenNewDbgInfoFormat) { 8100 CI->deleteValue(); 8101 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module " 8102 "using non-intrinsic debug info"); 8103 } 8104 if (!SeenOldDbgInfoFormat) 8105 M->setNewDbgInfoFormatFlag(false); 8106 SeenOldDbgInfoFormat = true; 8107 } 8108 CI->setAttributes(PAL); 8109 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 8110 Inst = CI; 8111 return false; 8112 } 8113 8114 //===----------------------------------------------------------------------===// 8115 // Memory Instructions. 8116 //===----------------------------------------------------------------------===// 8117 8118 /// parseAlloc 8119 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 8120 /// (',' 'align' i32)? (',', 'addrspace(n))? 8121 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 8122 Value *Size = nullptr; 8123 LocTy SizeLoc, TyLoc, ASLoc; 8124 MaybeAlign Alignment; 8125 unsigned AddrSpace = 0; 8126 Type *Ty = nullptr; 8127 8128 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 8129 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 8130 8131 if (parseType(Ty, TyLoc)) 8132 return true; 8133 8134 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 8135 return error(TyLoc, "invalid type for alloca"); 8136 8137 bool AteExtraComma = false; 8138 if (EatIfPresent(lltok::comma)) { 8139 if (Lex.getKind() == lltok::kw_align) { 8140 if (parseOptionalAlignment(Alignment)) 8141 return true; 8142 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 8143 return true; 8144 } else if (Lex.getKind() == lltok::kw_addrspace) { 8145 ASLoc = Lex.getLoc(); 8146 if (parseOptionalAddrSpace(AddrSpace)) 8147 return true; 8148 } else if (Lex.getKind() == lltok::MetadataVar) { 8149 AteExtraComma = true; 8150 } else { 8151 if (parseTypeAndValue(Size, SizeLoc, PFS)) 8152 return true; 8153 if (EatIfPresent(lltok::comma)) { 8154 if (Lex.getKind() == lltok::kw_align) { 8155 if (parseOptionalAlignment(Alignment)) 8156 return true; 8157 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 8158 return true; 8159 } else if (Lex.getKind() == lltok::kw_addrspace) { 8160 ASLoc = Lex.getLoc(); 8161 if (parseOptionalAddrSpace(AddrSpace)) 8162 return true; 8163 } else if (Lex.getKind() == lltok::MetadataVar) { 8164 AteExtraComma = true; 8165 } 8166 } 8167 } 8168 } 8169 8170 if (Size && !Size->getType()->isIntegerTy()) 8171 return error(SizeLoc, "element count must have integer type"); 8172 8173 SmallPtrSet<Type *, 4> Visited; 8174 if (!Alignment && !Ty->isSized(&Visited)) 8175 return error(TyLoc, "Cannot allocate unsized type"); 8176 if (!Alignment) 8177 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 8178 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 8179 AI->setUsedWithInAlloca(IsInAlloca); 8180 AI->setSwiftError(IsSwiftError); 8181 Inst = AI; 8182 return AteExtraComma ? InstExtraComma : InstNormal; 8183 } 8184 8185 /// parseLoad 8186 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 8187 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 8188 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 8189 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 8190 Value *Val; LocTy Loc; 8191 MaybeAlign Alignment; 8192 bool AteExtraComma = false; 8193 bool isAtomic = false; 8194 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8195 SyncScope::ID SSID = SyncScope::System; 8196 8197 if (Lex.getKind() == lltok::kw_atomic) { 8198 isAtomic = true; 8199 Lex.Lex(); 8200 } 8201 8202 bool isVolatile = false; 8203 if (Lex.getKind() == lltok::kw_volatile) { 8204 isVolatile = true; 8205 Lex.Lex(); 8206 } 8207 8208 Type *Ty; 8209 LocTy ExplicitTypeLoc = Lex.getLoc(); 8210 if (parseType(Ty) || 8211 parseToken(lltok::comma, "expected comma after load's type") || 8212 parseTypeAndValue(Val, Loc, PFS) || 8213 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 8214 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8215 return true; 8216 8217 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 8218 return error(Loc, "load operand must be a pointer to a first class type"); 8219 if (isAtomic && !Alignment) 8220 return error(Loc, "atomic load must have explicit non-zero alignment"); 8221 if (Ordering == AtomicOrdering::Release || 8222 Ordering == AtomicOrdering::AcquireRelease) 8223 return error(Loc, "atomic load cannot use Release ordering"); 8224 8225 SmallPtrSet<Type *, 4> Visited; 8226 if (!Alignment && !Ty->isSized(&Visited)) 8227 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 8228 if (!Alignment) 8229 Alignment = M->getDataLayout().getABITypeAlign(Ty); 8230 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 8231 return AteExtraComma ? InstExtraComma : InstNormal; 8232 } 8233 8234 /// parseStore 8235 8236 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 8237 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 8238 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 8239 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 8240 Value *Val, *Ptr; LocTy Loc, PtrLoc; 8241 MaybeAlign Alignment; 8242 bool AteExtraComma = false; 8243 bool isAtomic = false; 8244 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8245 SyncScope::ID SSID = SyncScope::System; 8246 8247 if (Lex.getKind() == lltok::kw_atomic) { 8248 isAtomic = true; 8249 Lex.Lex(); 8250 } 8251 8252 bool isVolatile = false; 8253 if (Lex.getKind() == lltok::kw_volatile) { 8254 isVolatile = true; 8255 Lex.Lex(); 8256 } 8257 8258 if (parseTypeAndValue(Val, Loc, PFS) || 8259 parseToken(lltok::comma, "expected ',' after store operand") || 8260 parseTypeAndValue(Ptr, PtrLoc, PFS) || 8261 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 8262 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8263 return true; 8264 8265 if (!Ptr->getType()->isPointerTy()) 8266 return error(PtrLoc, "store operand must be a pointer"); 8267 if (!Val->getType()->isFirstClassType()) 8268 return error(Loc, "store operand must be a first class value"); 8269 if (isAtomic && !Alignment) 8270 return error(Loc, "atomic store must have explicit non-zero alignment"); 8271 if (Ordering == AtomicOrdering::Acquire || 8272 Ordering == AtomicOrdering::AcquireRelease) 8273 return error(Loc, "atomic store cannot use Acquire ordering"); 8274 SmallPtrSet<Type *, 4> Visited; 8275 if (!Alignment && !Val->getType()->isSized(&Visited)) 8276 return error(Loc, "storing unsized types is not allowed"); 8277 if (!Alignment) 8278 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 8279 8280 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 8281 return AteExtraComma ? InstExtraComma : InstNormal; 8282 } 8283 8284 /// parseCmpXchg 8285 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 8286 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ',' 8287 /// 'Align'? 8288 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 8289 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 8290 bool AteExtraComma = false; 8291 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 8292 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 8293 SyncScope::ID SSID = SyncScope::System; 8294 bool isVolatile = false; 8295 bool isWeak = false; 8296 MaybeAlign Alignment; 8297 8298 if (EatIfPresent(lltok::kw_weak)) 8299 isWeak = true; 8300 8301 if (EatIfPresent(lltok::kw_volatile)) 8302 isVolatile = true; 8303 8304 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 8305 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 8306 parseTypeAndValue(Cmp, CmpLoc, PFS) || 8307 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 8308 parseTypeAndValue(New, NewLoc, PFS) || 8309 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 8310 parseOrdering(FailureOrdering) || 8311 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8312 return true; 8313 8314 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 8315 return tokError("invalid cmpxchg success ordering"); 8316 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 8317 return tokError("invalid cmpxchg failure ordering"); 8318 if (!Ptr->getType()->isPointerTy()) 8319 return error(PtrLoc, "cmpxchg operand must be a pointer"); 8320 if (Cmp->getType() != New->getType()) 8321 return error(NewLoc, "compare value and new value type do not match"); 8322 if (!New->getType()->isFirstClassType()) 8323 return error(NewLoc, "cmpxchg operand must be a first class value"); 8324 8325 const Align DefaultAlignment( 8326 PFS.getFunction().getDataLayout().getTypeStoreSize( 8327 Cmp->getType())); 8328 8329 AtomicCmpXchgInst *CXI = 8330 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment), 8331 SuccessOrdering, FailureOrdering, SSID); 8332 CXI->setVolatile(isVolatile); 8333 CXI->setWeak(isWeak); 8334 8335 Inst = CXI; 8336 return AteExtraComma ? InstExtraComma : InstNormal; 8337 } 8338 8339 /// parseAtomicRMW 8340 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 8341 /// 'singlethread'? AtomicOrdering 8342 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 8343 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 8344 bool AteExtraComma = false; 8345 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8346 SyncScope::ID SSID = SyncScope::System; 8347 bool isVolatile = false; 8348 bool IsFP = false; 8349 AtomicRMWInst::BinOp Operation; 8350 MaybeAlign Alignment; 8351 8352 if (EatIfPresent(lltok::kw_volatile)) 8353 isVolatile = true; 8354 8355 switch (Lex.getKind()) { 8356 default: 8357 return tokError("expected binary operation in atomicrmw"); 8358 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 8359 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 8360 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 8361 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 8362 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 8363 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 8364 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 8365 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 8366 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 8367 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 8368 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 8369 case lltok::kw_uinc_wrap: 8370 Operation = AtomicRMWInst::UIncWrap; 8371 break; 8372 case lltok::kw_udec_wrap: 8373 Operation = AtomicRMWInst::UDecWrap; 8374 break; 8375 case lltok::kw_usub_cond: 8376 Operation = AtomicRMWInst::USubCond; 8377 break; 8378 case lltok::kw_usub_sat: 8379 Operation = AtomicRMWInst::USubSat; 8380 break; 8381 case lltok::kw_fadd: 8382 Operation = AtomicRMWInst::FAdd; 8383 IsFP = true; 8384 break; 8385 case lltok::kw_fsub: 8386 Operation = AtomicRMWInst::FSub; 8387 IsFP = true; 8388 break; 8389 case lltok::kw_fmax: 8390 Operation = AtomicRMWInst::FMax; 8391 IsFP = true; 8392 break; 8393 case lltok::kw_fmin: 8394 Operation = AtomicRMWInst::FMin; 8395 IsFP = true; 8396 break; 8397 } 8398 Lex.Lex(); // Eat the operation. 8399 8400 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 8401 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 8402 parseTypeAndValue(Val, ValLoc, PFS) || 8403 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) || 8404 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8405 return true; 8406 8407 if (Ordering == AtomicOrdering::Unordered) 8408 return tokError("atomicrmw cannot be unordered"); 8409 if (!Ptr->getType()->isPointerTy()) 8410 return error(PtrLoc, "atomicrmw operand must be a pointer"); 8411 if (Val->getType()->isScalableTy()) 8412 return error(ValLoc, "atomicrmw operand may not be scalable"); 8413 8414 if (Operation == AtomicRMWInst::Xchg) { 8415 if (!Val->getType()->isIntegerTy() && 8416 !Val->getType()->isFloatingPointTy() && 8417 !Val->getType()->isPointerTy()) { 8418 return error( 8419 ValLoc, 8420 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 8421 " operand must be an integer, floating point, or pointer type"); 8422 } 8423 } else if (IsFP) { 8424 if (!Val->getType()->isFPOrFPVectorTy()) { 8425 return error(ValLoc, "atomicrmw " + 8426 AtomicRMWInst::getOperationName(Operation) + 8427 " operand must be a floating point type"); 8428 } 8429 } else { 8430 if (!Val->getType()->isIntegerTy()) { 8431 return error(ValLoc, "atomicrmw " + 8432 AtomicRMWInst::getOperationName(Operation) + 8433 " operand must be an integer"); 8434 } 8435 } 8436 8437 unsigned Size = 8438 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits( 8439 Val->getType()); 8440 if (Size < 8 || (Size & (Size - 1))) 8441 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 8442 " integer"); 8443 const Align DefaultAlignment( 8444 PFS.getFunction().getDataLayout().getTypeStoreSize( 8445 Val->getType())); 8446 AtomicRMWInst *RMWI = 8447 new AtomicRMWInst(Operation, Ptr, Val, 8448 Alignment.value_or(DefaultAlignment), Ordering, SSID); 8449 RMWI->setVolatile(isVolatile); 8450 Inst = RMWI; 8451 return AteExtraComma ? InstExtraComma : InstNormal; 8452 } 8453 8454 /// parseFence 8455 /// ::= 'fence' 'singlethread'? AtomicOrdering 8456 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 8457 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8458 SyncScope::ID SSID = SyncScope::System; 8459 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 8460 return true; 8461 8462 if (Ordering == AtomicOrdering::Unordered) 8463 return tokError("fence cannot be unordered"); 8464 if (Ordering == AtomicOrdering::Monotonic) 8465 return tokError("fence cannot be monotonic"); 8466 8467 Inst = new FenceInst(Context, Ordering, SSID); 8468 return InstNormal; 8469 } 8470 8471 /// parseGetElementPtr 8472 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 8473 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 8474 Value *Ptr = nullptr; 8475 Value *Val = nullptr; 8476 LocTy Loc, EltLoc; 8477 GEPNoWrapFlags NW; 8478 8479 while (true) { 8480 if (EatIfPresent(lltok::kw_inbounds)) 8481 NW |= GEPNoWrapFlags::inBounds(); 8482 else if (EatIfPresent(lltok::kw_nusw)) 8483 NW |= GEPNoWrapFlags::noUnsignedSignedWrap(); 8484 else if (EatIfPresent(lltok::kw_nuw)) 8485 NW |= GEPNoWrapFlags::noUnsignedWrap(); 8486 else 8487 break; 8488 } 8489 8490 Type *Ty = nullptr; 8491 if (parseType(Ty) || 8492 parseToken(lltok::comma, "expected comma after getelementptr's type") || 8493 parseTypeAndValue(Ptr, Loc, PFS)) 8494 return true; 8495 8496 Type *BaseType = Ptr->getType(); 8497 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 8498 if (!BasePointerType) 8499 return error(Loc, "base of getelementptr must be a pointer"); 8500 8501 SmallVector<Value*, 16> Indices; 8502 bool AteExtraComma = false; 8503 // GEP returns a vector of pointers if at least one of parameters is a vector. 8504 // All vector parameters should have the same vector width. 8505 ElementCount GEPWidth = BaseType->isVectorTy() 8506 ? cast<VectorType>(BaseType)->getElementCount() 8507 : ElementCount::getFixed(0); 8508 8509 while (EatIfPresent(lltok::comma)) { 8510 if (Lex.getKind() == lltok::MetadataVar) { 8511 AteExtraComma = true; 8512 break; 8513 } 8514 if (parseTypeAndValue(Val, EltLoc, PFS)) 8515 return true; 8516 if (!Val->getType()->isIntOrIntVectorTy()) 8517 return error(EltLoc, "getelementptr index must be an integer"); 8518 8519 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 8520 ElementCount ValNumEl = ValVTy->getElementCount(); 8521 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 8522 return error( 8523 EltLoc, 8524 "getelementptr vector index has a wrong number of elements"); 8525 GEPWidth = ValNumEl; 8526 } 8527 Indices.push_back(Val); 8528 } 8529 8530 SmallPtrSet<Type*, 4> Visited; 8531 if (!Indices.empty() && !Ty->isSized(&Visited)) 8532 return error(Loc, "base element of getelementptr must be sized"); 8533 8534 auto *STy = dyn_cast<StructType>(Ty); 8535 if (STy && STy->isScalableTy()) 8536 return error(Loc, "getelementptr cannot target structure that contains " 8537 "scalable vector type"); 8538 8539 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 8540 return error(Loc, "invalid getelementptr indices"); 8541 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices); 8542 Inst = GEP; 8543 GEP->setNoWrapFlags(NW); 8544 return AteExtraComma ? InstExtraComma : InstNormal; 8545 } 8546 8547 /// parseExtractValue 8548 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 8549 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 8550 Value *Val; LocTy Loc; 8551 SmallVector<unsigned, 4> Indices; 8552 bool AteExtraComma; 8553 if (parseTypeAndValue(Val, Loc, PFS) || 8554 parseIndexList(Indices, AteExtraComma)) 8555 return true; 8556 8557 if (!Val->getType()->isAggregateType()) 8558 return error(Loc, "extractvalue operand must be aggregate type"); 8559 8560 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 8561 return error(Loc, "invalid indices for extractvalue"); 8562 Inst = ExtractValueInst::Create(Val, Indices); 8563 return AteExtraComma ? InstExtraComma : InstNormal; 8564 } 8565 8566 /// parseInsertValue 8567 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 8568 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 8569 Value *Val0, *Val1; LocTy Loc0, Loc1; 8570 SmallVector<unsigned, 4> Indices; 8571 bool AteExtraComma; 8572 if (parseTypeAndValue(Val0, Loc0, PFS) || 8573 parseToken(lltok::comma, "expected comma after insertvalue operand") || 8574 parseTypeAndValue(Val1, Loc1, PFS) || 8575 parseIndexList(Indices, AteExtraComma)) 8576 return true; 8577 8578 if (!Val0->getType()->isAggregateType()) 8579 return error(Loc0, "insertvalue operand must be aggregate type"); 8580 8581 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 8582 if (!IndexedType) 8583 return error(Loc0, "invalid indices for insertvalue"); 8584 if (IndexedType != Val1->getType()) 8585 return error(Loc1, "insertvalue operand and field disagree in type: '" + 8586 getTypeString(Val1->getType()) + "' instead of '" + 8587 getTypeString(IndexedType) + "'"); 8588 Inst = InsertValueInst::Create(Val0, Val1, Indices); 8589 return AteExtraComma ? InstExtraComma : InstNormal; 8590 } 8591 8592 //===----------------------------------------------------------------------===// 8593 // Embedded metadata. 8594 //===----------------------------------------------------------------------===// 8595 8596 /// parseMDNodeVector 8597 /// ::= { Element (',' Element)* } 8598 /// Element 8599 /// ::= 'null' | Metadata 8600 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 8601 if (parseToken(lltok::lbrace, "expected '{' here")) 8602 return true; 8603 8604 // Check for an empty list. 8605 if (EatIfPresent(lltok::rbrace)) 8606 return false; 8607 8608 do { 8609 if (EatIfPresent(lltok::kw_null)) { 8610 Elts.push_back(nullptr); 8611 continue; 8612 } 8613 8614 Metadata *MD; 8615 if (parseMetadata(MD, nullptr)) 8616 return true; 8617 Elts.push_back(MD); 8618 } while (EatIfPresent(lltok::comma)); 8619 8620 return parseToken(lltok::rbrace, "expected end of metadata node"); 8621 } 8622 8623 //===----------------------------------------------------------------------===// 8624 // Use-list order directives. 8625 //===----------------------------------------------------------------------===// 8626 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 8627 SMLoc Loc) { 8628 if (V->use_empty()) 8629 return error(Loc, "value has no uses"); 8630 8631 unsigned NumUses = 0; 8632 SmallDenseMap<const Use *, unsigned, 16> Order; 8633 for (const Use &U : V->uses()) { 8634 if (++NumUses > Indexes.size()) 8635 break; 8636 Order[&U] = Indexes[NumUses - 1]; 8637 } 8638 if (NumUses < 2) 8639 return error(Loc, "value only has one use"); 8640 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 8641 return error(Loc, 8642 "wrong number of indexes, expected " + Twine(V->getNumUses())); 8643 8644 V->sortUseList([&](const Use &L, const Use &R) { 8645 return Order.lookup(&L) < Order.lookup(&R); 8646 }); 8647 return false; 8648 } 8649 8650 /// parseUseListOrderIndexes 8651 /// ::= '{' uint32 (',' uint32)+ '}' 8652 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 8653 SMLoc Loc = Lex.getLoc(); 8654 if (parseToken(lltok::lbrace, "expected '{' here")) 8655 return true; 8656 if (Lex.getKind() == lltok::rbrace) 8657 return tokError("expected non-empty list of uselistorder indexes"); 8658 8659 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 8660 // indexes should be distinct numbers in the range [0, size-1], and should 8661 // not be in order. 8662 unsigned Offset = 0; 8663 unsigned Max = 0; 8664 bool IsOrdered = true; 8665 assert(Indexes.empty() && "Expected empty order vector"); 8666 do { 8667 unsigned Index; 8668 if (parseUInt32(Index)) 8669 return true; 8670 8671 // Update consistency checks. 8672 Offset += Index - Indexes.size(); 8673 Max = std::max(Max, Index); 8674 IsOrdered &= Index == Indexes.size(); 8675 8676 Indexes.push_back(Index); 8677 } while (EatIfPresent(lltok::comma)); 8678 8679 if (parseToken(lltok::rbrace, "expected '}' here")) 8680 return true; 8681 8682 if (Indexes.size() < 2) 8683 return error(Loc, "expected >= 2 uselistorder indexes"); 8684 if (Offset != 0 || Max >= Indexes.size()) 8685 return error(Loc, 8686 "expected distinct uselistorder indexes in range [0, size)"); 8687 if (IsOrdered) 8688 return error(Loc, "expected uselistorder indexes to change the order"); 8689 8690 return false; 8691 } 8692 8693 /// parseUseListOrder 8694 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 8695 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 8696 SMLoc Loc = Lex.getLoc(); 8697 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 8698 return true; 8699 8700 Value *V; 8701 SmallVector<unsigned, 16> Indexes; 8702 if (parseTypeAndValue(V, PFS) || 8703 parseToken(lltok::comma, "expected comma in uselistorder directive") || 8704 parseUseListOrderIndexes(Indexes)) 8705 return true; 8706 8707 return sortUseListOrder(V, Indexes, Loc); 8708 } 8709 8710 /// parseUseListOrderBB 8711 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 8712 bool LLParser::parseUseListOrderBB() { 8713 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 8714 SMLoc Loc = Lex.getLoc(); 8715 Lex.Lex(); 8716 8717 ValID Fn, Label; 8718 SmallVector<unsigned, 16> Indexes; 8719 if (parseValID(Fn, /*PFS=*/nullptr) || 8720 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 8721 parseValID(Label, /*PFS=*/nullptr) || 8722 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 8723 parseUseListOrderIndexes(Indexes)) 8724 return true; 8725 8726 // Check the function. 8727 GlobalValue *GV; 8728 if (Fn.Kind == ValID::t_GlobalName) 8729 GV = M->getNamedValue(Fn.StrVal); 8730 else if (Fn.Kind == ValID::t_GlobalID) 8731 GV = NumberedVals.get(Fn.UIntVal); 8732 else 8733 return error(Fn.Loc, "expected function name in uselistorder_bb"); 8734 if (!GV) 8735 return error(Fn.Loc, 8736 "invalid function forward reference in uselistorder_bb"); 8737 auto *F = dyn_cast<Function>(GV); 8738 if (!F) 8739 return error(Fn.Loc, "expected function name in uselistorder_bb"); 8740 if (F->isDeclaration()) 8741 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 8742 8743 // Check the basic block. 8744 if (Label.Kind == ValID::t_LocalID) 8745 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 8746 if (Label.Kind != ValID::t_LocalName) 8747 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 8748 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 8749 if (!V) 8750 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 8751 if (!isa<BasicBlock>(V)) 8752 return error(Label.Loc, "expected basic block in uselistorder_bb"); 8753 8754 return sortUseListOrder(V, Indexes, Loc); 8755 } 8756 8757 /// ModuleEntry 8758 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 8759 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 8760 bool LLParser::parseModuleEntry(unsigned ID) { 8761 assert(Lex.getKind() == lltok::kw_module); 8762 Lex.Lex(); 8763 8764 std::string Path; 8765 if (parseToken(lltok::colon, "expected ':' here") || 8766 parseToken(lltok::lparen, "expected '(' here") || 8767 parseToken(lltok::kw_path, "expected 'path' here") || 8768 parseToken(lltok::colon, "expected ':' here") || 8769 parseStringConstant(Path) || 8770 parseToken(lltok::comma, "expected ',' here") || 8771 parseToken(lltok::kw_hash, "expected 'hash' here") || 8772 parseToken(lltok::colon, "expected ':' here") || 8773 parseToken(lltok::lparen, "expected '(' here")) 8774 return true; 8775 8776 ModuleHash Hash; 8777 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 8778 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 8779 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 8780 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 8781 parseUInt32(Hash[4])) 8782 return true; 8783 8784 if (parseToken(lltok::rparen, "expected ')' here") || 8785 parseToken(lltok::rparen, "expected ')' here")) 8786 return true; 8787 8788 auto ModuleEntry = Index->addModule(Path, Hash); 8789 ModuleIdMap[ID] = ModuleEntry->first(); 8790 8791 return false; 8792 } 8793 8794 /// TypeIdEntry 8795 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 8796 bool LLParser::parseTypeIdEntry(unsigned ID) { 8797 assert(Lex.getKind() == lltok::kw_typeid); 8798 Lex.Lex(); 8799 8800 std::string Name; 8801 if (parseToken(lltok::colon, "expected ':' here") || 8802 parseToken(lltok::lparen, "expected '(' here") || 8803 parseToken(lltok::kw_name, "expected 'name' here") || 8804 parseToken(lltok::colon, "expected ':' here") || 8805 parseStringConstant(Name)) 8806 return true; 8807 8808 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 8809 if (parseToken(lltok::comma, "expected ',' here") || 8810 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 8811 return true; 8812 8813 // Check if this ID was forward referenced, and if so, update the 8814 // corresponding GUIDs. 8815 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 8816 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 8817 for (auto TIDRef : FwdRefTIDs->second) { 8818 assert(!*TIDRef.first && 8819 "Forward referenced type id GUID expected to be 0"); 8820 *TIDRef.first = GlobalValue::getGUID(Name); 8821 } 8822 ForwardRefTypeIds.erase(FwdRefTIDs); 8823 } 8824 8825 return false; 8826 } 8827 8828 /// TypeIdSummary 8829 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 8830 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 8831 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 8832 parseToken(lltok::colon, "expected ':' here") || 8833 parseToken(lltok::lparen, "expected '(' here") || 8834 parseTypeTestResolution(TIS.TTRes)) 8835 return true; 8836 8837 if (EatIfPresent(lltok::comma)) { 8838 // Expect optional wpdResolutions field 8839 if (parseOptionalWpdResolutions(TIS.WPDRes)) 8840 return true; 8841 } 8842 8843 if (parseToken(lltok::rparen, "expected ')' here")) 8844 return true; 8845 8846 return false; 8847 } 8848 8849 static ValueInfo EmptyVI = 8850 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 8851 8852 /// TypeIdCompatibleVtableEntry 8853 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 8854 /// TypeIdCompatibleVtableInfo 8855 /// ')' 8856 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 8857 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 8858 Lex.Lex(); 8859 8860 std::string Name; 8861 if (parseToken(lltok::colon, "expected ':' here") || 8862 parseToken(lltok::lparen, "expected '(' here") || 8863 parseToken(lltok::kw_name, "expected 'name' here") || 8864 parseToken(lltok::colon, "expected ':' here") || 8865 parseStringConstant(Name)) 8866 return true; 8867 8868 TypeIdCompatibleVtableInfo &TI = 8869 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 8870 if (parseToken(lltok::comma, "expected ',' here") || 8871 parseToken(lltok::kw_summary, "expected 'summary' here") || 8872 parseToken(lltok::colon, "expected ':' here") || 8873 parseToken(lltok::lparen, "expected '(' here")) 8874 return true; 8875 8876 IdToIndexMapType IdToIndexMap; 8877 // parse each call edge 8878 do { 8879 uint64_t Offset; 8880 if (parseToken(lltok::lparen, "expected '(' here") || 8881 parseToken(lltok::kw_offset, "expected 'offset' here") || 8882 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 8883 parseToken(lltok::comma, "expected ',' here")) 8884 return true; 8885 8886 LocTy Loc = Lex.getLoc(); 8887 unsigned GVId; 8888 ValueInfo VI; 8889 if (parseGVReference(VI, GVId)) 8890 return true; 8891 8892 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 8893 // forward reference. We will save the location of the ValueInfo needing an 8894 // update, but can only do so once the std::vector is finalized. 8895 if (VI == EmptyVI) 8896 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 8897 TI.push_back({Offset, VI}); 8898 8899 if (parseToken(lltok::rparen, "expected ')' in call")) 8900 return true; 8901 } while (EatIfPresent(lltok::comma)); 8902 8903 // Now that the TI vector is finalized, it is safe to save the locations 8904 // of any forward GV references that need updating later. 8905 for (auto I : IdToIndexMap) { 8906 auto &Infos = ForwardRefValueInfos[I.first]; 8907 for (auto P : I.second) { 8908 assert(TI[P.first].VTableVI == EmptyVI && 8909 "Forward referenced ValueInfo expected to be empty"); 8910 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 8911 } 8912 } 8913 8914 if (parseToken(lltok::rparen, "expected ')' here") || 8915 parseToken(lltok::rparen, "expected ')' here")) 8916 return true; 8917 8918 // Check if this ID was forward referenced, and if so, update the 8919 // corresponding GUIDs. 8920 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 8921 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 8922 for (auto TIDRef : FwdRefTIDs->second) { 8923 assert(!*TIDRef.first && 8924 "Forward referenced type id GUID expected to be 0"); 8925 *TIDRef.first = GlobalValue::getGUID(Name); 8926 } 8927 ForwardRefTypeIds.erase(FwdRefTIDs); 8928 } 8929 8930 return false; 8931 } 8932 8933 /// TypeTestResolution 8934 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 8935 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 8936 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 8937 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 8938 /// [',' 'inlinesBits' ':' UInt64]? ')' 8939 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 8940 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 8941 parseToken(lltok::colon, "expected ':' here") || 8942 parseToken(lltok::lparen, "expected '(' here") || 8943 parseToken(lltok::kw_kind, "expected 'kind' here") || 8944 parseToken(lltok::colon, "expected ':' here")) 8945 return true; 8946 8947 switch (Lex.getKind()) { 8948 case lltok::kw_unknown: 8949 TTRes.TheKind = TypeTestResolution::Unknown; 8950 break; 8951 case lltok::kw_unsat: 8952 TTRes.TheKind = TypeTestResolution::Unsat; 8953 break; 8954 case lltok::kw_byteArray: 8955 TTRes.TheKind = TypeTestResolution::ByteArray; 8956 break; 8957 case lltok::kw_inline: 8958 TTRes.TheKind = TypeTestResolution::Inline; 8959 break; 8960 case lltok::kw_single: 8961 TTRes.TheKind = TypeTestResolution::Single; 8962 break; 8963 case lltok::kw_allOnes: 8964 TTRes.TheKind = TypeTestResolution::AllOnes; 8965 break; 8966 default: 8967 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 8968 } 8969 Lex.Lex(); 8970 8971 if (parseToken(lltok::comma, "expected ',' here") || 8972 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 8973 parseToken(lltok::colon, "expected ':' here") || 8974 parseUInt32(TTRes.SizeM1BitWidth)) 8975 return true; 8976 8977 // parse optional fields 8978 while (EatIfPresent(lltok::comma)) { 8979 switch (Lex.getKind()) { 8980 case lltok::kw_alignLog2: 8981 Lex.Lex(); 8982 if (parseToken(lltok::colon, "expected ':'") || 8983 parseUInt64(TTRes.AlignLog2)) 8984 return true; 8985 break; 8986 case lltok::kw_sizeM1: 8987 Lex.Lex(); 8988 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 8989 return true; 8990 break; 8991 case lltok::kw_bitMask: { 8992 unsigned Val; 8993 Lex.Lex(); 8994 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 8995 return true; 8996 assert(Val <= 0xff); 8997 TTRes.BitMask = (uint8_t)Val; 8998 break; 8999 } 9000 case lltok::kw_inlineBits: 9001 Lex.Lex(); 9002 if (parseToken(lltok::colon, "expected ':'") || 9003 parseUInt64(TTRes.InlineBits)) 9004 return true; 9005 break; 9006 default: 9007 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 9008 } 9009 } 9010 9011 if (parseToken(lltok::rparen, "expected ')' here")) 9012 return true; 9013 9014 return false; 9015 } 9016 9017 /// OptionalWpdResolutions 9018 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 9019 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 9020 bool LLParser::parseOptionalWpdResolutions( 9021 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 9022 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 9023 parseToken(lltok::colon, "expected ':' here") || 9024 parseToken(lltok::lparen, "expected '(' here")) 9025 return true; 9026 9027 do { 9028 uint64_t Offset; 9029 WholeProgramDevirtResolution WPDRes; 9030 if (parseToken(lltok::lparen, "expected '(' here") || 9031 parseToken(lltok::kw_offset, "expected 'offset' here") || 9032 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 9033 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 9034 parseToken(lltok::rparen, "expected ')' here")) 9035 return true; 9036 WPDResMap[Offset] = WPDRes; 9037 } while (EatIfPresent(lltok::comma)); 9038 9039 if (parseToken(lltok::rparen, "expected ')' here")) 9040 return true; 9041 9042 return false; 9043 } 9044 9045 /// WpdRes 9046 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 9047 /// [',' OptionalResByArg]? ')' 9048 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 9049 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 9050 /// [',' OptionalResByArg]? ')' 9051 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 9052 /// [',' OptionalResByArg]? ')' 9053 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 9054 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 9055 parseToken(lltok::colon, "expected ':' here") || 9056 parseToken(lltok::lparen, "expected '(' here") || 9057 parseToken(lltok::kw_kind, "expected 'kind' here") || 9058 parseToken(lltok::colon, "expected ':' here")) 9059 return true; 9060 9061 switch (Lex.getKind()) { 9062 case lltok::kw_indir: 9063 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 9064 break; 9065 case lltok::kw_singleImpl: 9066 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 9067 break; 9068 case lltok::kw_branchFunnel: 9069 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 9070 break; 9071 default: 9072 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 9073 } 9074 Lex.Lex(); 9075 9076 // parse optional fields 9077 while (EatIfPresent(lltok::comma)) { 9078 switch (Lex.getKind()) { 9079 case lltok::kw_singleImplName: 9080 Lex.Lex(); 9081 if (parseToken(lltok::colon, "expected ':' here") || 9082 parseStringConstant(WPDRes.SingleImplName)) 9083 return true; 9084 break; 9085 case lltok::kw_resByArg: 9086 if (parseOptionalResByArg(WPDRes.ResByArg)) 9087 return true; 9088 break; 9089 default: 9090 return error(Lex.getLoc(), 9091 "expected optional WholeProgramDevirtResolution field"); 9092 } 9093 } 9094 9095 if (parseToken(lltok::rparen, "expected ')' here")) 9096 return true; 9097 9098 return false; 9099 } 9100 9101 /// OptionalResByArg 9102 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 9103 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 9104 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 9105 /// 'virtualConstProp' ) 9106 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 9107 /// [',' 'bit' ':' UInt32]? ')' 9108 bool LLParser::parseOptionalResByArg( 9109 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 9110 &ResByArg) { 9111 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 9112 parseToken(lltok::colon, "expected ':' here") || 9113 parseToken(lltok::lparen, "expected '(' here")) 9114 return true; 9115 9116 do { 9117 std::vector<uint64_t> Args; 9118 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 9119 parseToken(lltok::kw_byArg, "expected 'byArg here") || 9120 parseToken(lltok::colon, "expected ':' here") || 9121 parseToken(lltok::lparen, "expected '(' here") || 9122 parseToken(lltok::kw_kind, "expected 'kind' here") || 9123 parseToken(lltok::colon, "expected ':' here")) 9124 return true; 9125 9126 WholeProgramDevirtResolution::ByArg ByArg; 9127 switch (Lex.getKind()) { 9128 case lltok::kw_indir: 9129 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 9130 break; 9131 case lltok::kw_uniformRetVal: 9132 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 9133 break; 9134 case lltok::kw_uniqueRetVal: 9135 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 9136 break; 9137 case lltok::kw_virtualConstProp: 9138 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 9139 break; 9140 default: 9141 return error(Lex.getLoc(), 9142 "unexpected WholeProgramDevirtResolution::ByArg kind"); 9143 } 9144 Lex.Lex(); 9145 9146 // parse optional fields 9147 while (EatIfPresent(lltok::comma)) { 9148 switch (Lex.getKind()) { 9149 case lltok::kw_info: 9150 Lex.Lex(); 9151 if (parseToken(lltok::colon, "expected ':' here") || 9152 parseUInt64(ByArg.Info)) 9153 return true; 9154 break; 9155 case lltok::kw_byte: 9156 Lex.Lex(); 9157 if (parseToken(lltok::colon, "expected ':' here") || 9158 parseUInt32(ByArg.Byte)) 9159 return true; 9160 break; 9161 case lltok::kw_bit: 9162 Lex.Lex(); 9163 if (parseToken(lltok::colon, "expected ':' here") || 9164 parseUInt32(ByArg.Bit)) 9165 return true; 9166 break; 9167 default: 9168 return error(Lex.getLoc(), 9169 "expected optional whole program devirt field"); 9170 } 9171 } 9172 9173 if (parseToken(lltok::rparen, "expected ')' here")) 9174 return true; 9175 9176 ResByArg[Args] = ByArg; 9177 } while (EatIfPresent(lltok::comma)); 9178 9179 if (parseToken(lltok::rparen, "expected ')' here")) 9180 return true; 9181 9182 return false; 9183 } 9184 9185 /// OptionalResByArg 9186 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 9187 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 9188 if (parseToken(lltok::kw_args, "expected 'args' here") || 9189 parseToken(lltok::colon, "expected ':' here") || 9190 parseToken(lltok::lparen, "expected '(' here")) 9191 return true; 9192 9193 do { 9194 uint64_t Val; 9195 if (parseUInt64(Val)) 9196 return true; 9197 Args.push_back(Val); 9198 } while (EatIfPresent(lltok::comma)); 9199 9200 if (parseToken(lltok::rparen, "expected ')' here")) 9201 return true; 9202 9203 return false; 9204 } 9205 9206 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 9207 9208 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 9209 bool ReadOnly = Fwd->isReadOnly(); 9210 bool WriteOnly = Fwd->isWriteOnly(); 9211 assert(!(ReadOnly && WriteOnly)); 9212 *Fwd = Resolved; 9213 if (ReadOnly) 9214 Fwd->setReadOnly(); 9215 if (WriteOnly) 9216 Fwd->setWriteOnly(); 9217 } 9218 9219 /// Stores the given Name/GUID and associated summary into the Index. 9220 /// Also updates any forward references to the associated entry ID. 9221 bool LLParser::addGlobalValueToIndex( 9222 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 9223 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) { 9224 // First create the ValueInfo utilizing the Name or GUID. 9225 ValueInfo VI; 9226 if (GUID != 0) { 9227 assert(Name.empty()); 9228 VI = Index->getOrInsertValueInfo(GUID); 9229 } else { 9230 assert(!Name.empty()); 9231 if (M) { 9232 auto *GV = M->getNamedValue(Name); 9233 if (!GV) 9234 return error(Loc, "Reference to undefined global \"" + Name + "\""); 9235 9236 VI = Index->getOrInsertValueInfo(GV); 9237 } else { 9238 assert( 9239 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 9240 "Need a source_filename to compute GUID for local"); 9241 GUID = GlobalValue::getGUID( 9242 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 9243 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 9244 } 9245 } 9246 9247 // Resolve forward references from calls/refs 9248 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 9249 if (FwdRefVIs != ForwardRefValueInfos.end()) { 9250 for (auto VIRef : FwdRefVIs->second) { 9251 assert(VIRef.first->getRef() == FwdVIRef && 9252 "Forward referenced ValueInfo expected to be empty"); 9253 resolveFwdRef(VIRef.first, VI); 9254 } 9255 ForwardRefValueInfos.erase(FwdRefVIs); 9256 } 9257 9258 // Resolve forward references from aliases 9259 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 9260 if (FwdRefAliasees != ForwardRefAliasees.end()) { 9261 for (auto AliaseeRef : FwdRefAliasees->second) { 9262 assert(!AliaseeRef.first->hasAliasee() && 9263 "Forward referencing alias already has aliasee"); 9264 assert(Summary && "Aliasee must be a definition"); 9265 AliaseeRef.first->setAliasee(VI, Summary.get()); 9266 } 9267 ForwardRefAliasees.erase(FwdRefAliasees); 9268 } 9269 9270 // Add the summary if one was provided. 9271 if (Summary) 9272 Index->addGlobalValueSummary(VI, std::move(Summary)); 9273 9274 // Save the associated ValueInfo for use in later references by ID. 9275 if (ID == NumberedValueInfos.size()) 9276 NumberedValueInfos.push_back(VI); 9277 else { 9278 // Handle non-continuous numbers (to make test simplification easier). 9279 if (ID > NumberedValueInfos.size()) 9280 NumberedValueInfos.resize(ID + 1); 9281 NumberedValueInfos[ID] = VI; 9282 } 9283 9284 return false; 9285 } 9286 9287 /// parseSummaryIndexFlags 9288 /// ::= 'flags' ':' UInt64 9289 bool LLParser::parseSummaryIndexFlags() { 9290 assert(Lex.getKind() == lltok::kw_flags); 9291 Lex.Lex(); 9292 9293 if (parseToken(lltok::colon, "expected ':' here")) 9294 return true; 9295 uint64_t Flags; 9296 if (parseUInt64(Flags)) 9297 return true; 9298 if (Index) 9299 Index->setFlags(Flags); 9300 return false; 9301 } 9302 9303 /// parseBlockCount 9304 /// ::= 'blockcount' ':' UInt64 9305 bool LLParser::parseBlockCount() { 9306 assert(Lex.getKind() == lltok::kw_blockcount); 9307 Lex.Lex(); 9308 9309 if (parseToken(lltok::colon, "expected ':' here")) 9310 return true; 9311 uint64_t BlockCount; 9312 if (parseUInt64(BlockCount)) 9313 return true; 9314 if (Index) 9315 Index->setBlockCount(BlockCount); 9316 return false; 9317 } 9318 9319 /// parseGVEntry 9320 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 9321 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 9322 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 9323 bool LLParser::parseGVEntry(unsigned ID) { 9324 assert(Lex.getKind() == lltok::kw_gv); 9325 Lex.Lex(); 9326 9327 if (parseToken(lltok::colon, "expected ':' here") || 9328 parseToken(lltok::lparen, "expected '(' here")) 9329 return true; 9330 9331 LocTy Loc = Lex.getLoc(); 9332 std::string Name; 9333 GlobalValue::GUID GUID = 0; 9334 switch (Lex.getKind()) { 9335 case lltok::kw_name: 9336 Lex.Lex(); 9337 if (parseToken(lltok::colon, "expected ':' here") || 9338 parseStringConstant(Name)) 9339 return true; 9340 // Can't create GUID/ValueInfo until we have the linkage. 9341 break; 9342 case lltok::kw_guid: 9343 Lex.Lex(); 9344 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 9345 return true; 9346 break; 9347 default: 9348 return error(Lex.getLoc(), "expected name or guid tag"); 9349 } 9350 9351 if (!EatIfPresent(lltok::comma)) { 9352 // No summaries. Wrap up. 9353 if (parseToken(lltok::rparen, "expected ')' here")) 9354 return true; 9355 // This was created for a call to an external or indirect target. 9356 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 9357 // created for indirect calls with VP. A Name with no GUID came from 9358 // an external definition. We pass ExternalLinkage since that is only 9359 // used when the GUID must be computed from Name, and in that case 9360 // the symbol must have external linkage. 9361 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 9362 nullptr, Loc); 9363 } 9364 9365 // Have a list of summaries 9366 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 9367 parseToken(lltok::colon, "expected ':' here") || 9368 parseToken(lltok::lparen, "expected '(' here")) 9369 return true; 9370 do { 9371 switch (Lex.getKind()) { 9372 case lltok::kw_function: 9373 if (parseFunctionSummary(Name, GUID, ID)) 9374 return true; 9375 break; 9376 case lltok::kw_variable: 9377 if (parseVariableSummary(Name, GUID, ID)) 9378 return true; 9379 break; 9380 case lltok::kw_alias: 9381 if (parseAliasSummary(Name, GUID, ID)) 9382 return true; 9383 break; 9384 default: 9385 return error(Lex.getLoc(), "expected summary type"); 9386 } 9387 } while (EatIfPresent(lltok::comma)); 9388 9389 if (parseToken(lltok::rparen, "expected ')' here") || 9390 parseToken(lltok::rparen, "expected ')' here")) 9391 return true; 9392 9393 return false; 9394 } 9395 9396 /// FunctionSummary 9397 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 9398 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 9399 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 9400 /// [',' OptionalRefs]? ')' 9401 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 9402 unsigned ID) { 9403 LocTy Loc = Lex.getLoc(); 9404 assert(Lex.getKind() == lltok::kw_function); 9405 Lex.Lex(); 9406 9407 StringRef ModulePath; 9408 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 9409 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 9410 /*NotEligibleToImport=*/false, 9411 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, 9412 GlobalValueSummary::Definition); 9413 unsigned InstCount; 9414 SmallVector<FunctionSummary::EdgeTy, 0> Calls; 9415 FunctionSummary::TypeIdInfo TypeIdInfo; 9416 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 9417 SmallVector<ValueInfo, 0> Refs; 9418 std::vector<CallsiteInfo> Callsites; 9419 std::vector<AllocInfo> Allocs; 9420 // Default is all-zeros (conservative values). 9421 FunctionSummary::FFlags FFlags = {}; 9422 if (parseToken(lltok::colon, "expected ':' here") || 9423 parseToken(lltok::lparen, "expected '(' here") || 9424 parseModuleReference(ModulePath) || 9425 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 9426 parseToken(lltok::comma, "expected ',' here") || 9427 parseToken(lltok::kw_insts, "expected 'insts' here") || 9428 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 9429 return true; 9430 9431 // parse optional fields 9432 while (EatIfPresent(lltok::comma)) { 9433 switch (Lex.getKind()) { 9434 case lltok::kw_funcFlags: 9435 if (parseOptionalFFlags(FFlags)) 9436 return true; 9437 break; 9438 case lltok::kw_calls: 9439 if (parseOptionalCalls(Calls)) 9440 return true; 9441 break; 9442 case lltok::kw_typeIdInfo: 9443 if (parseOptionalTypeIdInfo(TypeIdInfo)) 9444 return true; 9445 break; 9446 case lltok::kw_refs: 9447 if (parseOptionalRefs(Refs)) 9448 return true; 9449 break; 9450 case lltok::kw_params: 9451 if (parseOptionalParamAccesses(ParamAccesses)) 9452 return true; 9453 break; 9454 case lltok::kw_allocs: 9455 if (parseOptionalAllocs(Allocs)) 9456 return true; 9457 break; 9458 case lltok::kw_callsites: 9459 if (parseOptionalCallsites(Callsites)) 9460 return true; 9461 break; 9462 default: 9463 return error(Lex.getLoc(), "expected optional function summary field"); 9464 } 9465 } 9466 9467 if (parseToken(lltok::rparen, "expected ')' here")) 9468 return true; 9469 9470 auto FS = std::make_unique<FunctionSummary>( 9471 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls), 9472 std::move(TypeIdInfo.TypeTests), 9473 std::move(TypeIdInfo.TypeTestAssumeVCalls), 9474 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 9475 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 9476 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 9477 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs)); 9478 9479 FS->setModulePath(ModulePath); 9480 9481 return addGlobalValueToIndex(Name, GUID, 9482 (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, 9483 std::move(FS), Loc); 9484 } 9485 9486 /// VariableSummary 9487 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 9488 /// [',' OptionalRefs]? ')' 9489 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 9490 unsigned ID) { 9491 LocTy Loc = Lex.getLoc(); 9492 assert(Lex.getKind() == lltok::kw_variable); 9493 Lex.Lex(); 9494 9495 StringRef ModulePath; 9496 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 9497 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 9498 /*NotEligibleToImport=*/false, 9499 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, 9500 GlobalValueSummary::Definition); 9501 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 9502 /* WriteOnly */ false, 9503 /* Constant */ false, 9504 GlobalObject::VCallVisibilityPublic); 9505 SmallVector<ValueInfo, 0> Refs; 9506 VTableFuncList VTableFuncs; 9507 if (parseToken(lltok::colon, "expected ':' here") || 9508 parseToken(lltok::lparen, "expected '(' here") || 9509 parseModuleReference(ModulePath) || 9510 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 9511 parseToken(lltok::comma, "expected ',' here") || 9512 parseGVarFlags(GVarFlags)) 9513 return true; 9514 9515 // parse optional fields 9516 while (EatIfPresent(lltok::comma)) { 9517 switch (Lex.getKind()) { 9518 case lltok::kw_vTableFuncs: 9519 if (parseOptionalVTableFuncs(VTableFuncs)) 9520 return true; 9521 break; 9522 case lltok::kw_refs: 9523 if (parseOptionalRefs(Refs)) 9524 return true; 9525 break; 9526 default: 9527 return error(Lex.getLoc(), "expected optional variable summary field"); 9528 } 9529 } 9530 9531 if (parseToken(lltok::rparen, "expected ')' here")) 9532 return true; 9533 9534 auto GS = 9535 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 9536 9537 GS->setModulePath(ModulePath); 9538 GS->setVTableFuncs(std::move(VTableFuncs)); 9539 9540 return addGlobalValueToIndex(Name, GUID, 9541 (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, 9542 std::move(GS), Loc); 9543 } 9544 9545 /// AliasSummary 9546 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 9547 /// 'aliasee' ':' GVReference ')' 9548 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 9549 unsigned ID) { 9550 assert(Lex.getKind() == lltok::kw_alias); 9551 LocTy Loc = Lex.getLoc(); 9552 Lex.Lex(); 9553 9554 StringRef ModulePath; 9555 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 9556 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 9557 /*NotEligibleToImport=*/false, 9558 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, 9559 GlobalValueSummary::Definition); 9560 if (parseToken(lltok::colon, "expected ':' here") || 9561 parseToken(lltok::lparen, "expected '(' here") || 9562 parseModuleReference(ModulePath) || 9563 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 9564 parseToken(lltok::comma, "expected ',' here") || 9565 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 9566 parseToken(lltok::colon, "expected ':' here")) 9567 return true; 9568 9569 ValueInfo AliaseeVI; 9570 unsigned GVId; 9571 if (parseGVReference(AliaseeVI, GVId)) 9572 return true; 9573 9574 if (parseToken(lltok::rparen, "expected ')' here")) 9575 return true; 9576 9577 auto AS = std::make_unique<AliasSummary>(GVFlags); 9578 9579 AS->setModulePath(ModulePath); 9580 9581 // Record forward reference if the aliasee is not parsed yet. 9582 if (AliaseeVI.getRef() == FwdVIRef) { 9583 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 9584 } else { 9585 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 9586 assert(Summary && "Aliasee must be a definition"); 9587 AS->setAliasee(AliaseeVI, Summary); 9588 } 9589 9590 return addGlobalValueToIndex(Name, GUID, 9591 (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, 9592 std::move(AS), Loc); 9593 } 9594 9595 /// Flag 9596 /// ::= [0|1] 9597 bool LLParser::parseFlag(unsigned &Val) { 9598 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 9599 return tokError("expected integer"); 9600 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 9601 Lex.Lex(); 9602 return false; 9603 } 9604 9605 /// OptionalFFlags 9606 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 9607 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 9608 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 9609 /// [',' 'noInline' ':' Flag]? ')' 9610 /// [',' 'alwaysInline' ':' Flag]? ')' 9611 /// [',' 'noUnwind' ':' Flag]? ')' 9612 /// [',' 'mayThrow' ':' Flag]? ')' 9613 /// [',' 'hasUnknownCall' ':' Flag]? ')' 9614 /// [',' 'mustBeUnreachable' ':' Flag]? ')' 9615 9616 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 9617 assert(Lex.getKind() == lltok::kw_funcFlags); 9618 Lex.Lex(); 9619 9620 if (parseToken(lltok::colon, "expected ':' in funcFlags") || 9621 parseToken(lltok::lparen, "expected '(' in funcFlags")) 9622 return true; 9623 9624 do { 9625 unsigned Val = 0; 9626 switch (Lex.getKind()) { 9627 case lltok::kw_readNone: 9628 Lex.Lex(); 9629 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9630 return true; 9631 FFlags.ReadNone = Val; 9632 break; 9633 case lltok::kw_readOnly: 9634 Lex.Lex(); 9635 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9636 return true; 9637 FFlags.ReadOnly = Val; 9638 break; 9639 case lltok::kw_noRecurse: 9640 Lex.Lex(); 9641 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9642 return true; 9643 FFlags.NoRecurse = Val; 9644 break; 9645 case lltok::kw_returnDoesNotAlias: 9646 Lex.Lex(); 9647 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9648 return true; 9649 FFlags.ReturnDoesNotAlias = Val; 9650 break; 9651 case lltok::kw_noInline: 9652 Lex.Lex(); 9653 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9654 return true; 9655 FFlags.NoInline = Val; 9656 break; 9657 case lltok::kw_alwaysInline: 9658 Lex.Lex(); 9659 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9660 return true; 9661 FFlags.AlwaysInline = Val; 9662 break; 9663 case lltok::kw_noUnwind: 9664 Lex.Lex(); 9665 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9666 return true; 9667 FFlags.NoUnwind = Val; 9668 break; 9669 case lltok::kw_mayThrow: 9670 Lex.Lex(); 9671 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9672 return true; 9673 FFlags.MayThrow = Val; 9674 break; 9675 case lltok::kw_hasUnknownCall: 9676 Lex.Lex(); 9677 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9678 return true; 9679 FFlags.HasUnknownCall = Val; 9680 break; 9681 case lltok::kw_mustBeUnreachable: 9682 Lex.Lex(); 9683 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9684 return true; 9685 FFlags.MustBeUnreachable = Val; 9686 break; 9687 default: 9688 return error(Lex.getLoc(), "expected function flag type"); 9689 } 9690 } while (EatIfPresent(lltok::comma)); 9691 9692 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 9693 return true; 9694 9695 return false; 9696 } 9697 9698 /// OptionalCalls 9699 /// := 'calls' ':' '(' Call [',' Call]* ')' 9700 /// Call ::= '(' 'callee' ':' GVReference 9701 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? 9702 /// [ ',' 'tail' ]? ')' 9703 bool LLParser::parseOptionalCalls( 9704 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) { 9705 assert(Lex.getKind() == lltok::kw_calls); 9706 Lex.Lex(); 9707 9708 if (parseToken(lltok::colon, "expected ':' in calls") || 9709 parseToken(lltok::lparen, "expected '(' in calls")) 9710 return true; 9711 9712 IdToIndexMapType IdToIndexMap; 9713 // parse each call edge 9714 do { 9715 ValueInfo VI; 9716 if (parseToken(lltok::lparen, "expected '(' in call") || 9717 parseToken(lltok::kw_callee, "expected 'callee' in call") || 9718 parseToken(lltok::colon, "expected ':'")) 9719 return true; 9720 9721 LocTy Loc = Lex.getLoc(); 9722 unsigned GVId; 9723 if (parseGVReference(VI, GVId)) 9724 return true; 9725 9726 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 9727 unsigned RelBF = 0; 9728 unsigned HasTailCall = false; 9729 9730 // parse optional fields 9731 while (EatIfPresent(lltok::comma)) { 9732 switch (Lex.getKind()) { 9733 case lltok::kw_hotness: 9734 Lex.Lex(); 9735 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 9736 return true; 9737 break; 9738 case lltok::kw_relbf: 9739 Lex.Lex(); 9740 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 9741 return true; 9742 break; 9743 case lltok::kw_tail: 9744 Lex.Lex(); 9745 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall)) 9746 return true; 9747 break; 9748 default: 9749 return error(Lex.getLoc(), "expected hotness, relbf, or tail"); 9750 } 9751 } 9752 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0) 9753 return tokError("Expected only one of hotness or relbf"); 9754 // Keep track of the Call array index needing a forward reference. 9755 // We will save the location of the ValueInfo needing an update, but 9756 // can only do so once the std::vector is finalized. 9757 if (VI.getRef() == FwdVIRef) 9758 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 9759 Calls.push_back( 9760 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)}); 9761 9762 if (parseToken(lltok::rparen, "expected ')' in call")) 9763 return true; 9764 } while (EatIfPresent(lltok::comma)); 9765 9766 // Now that the Calls vector is finalized, it is safe to save the locations 9767 // of any forward GV references that need updating later. 9768 for (auto I : IdToIndexMap) { 9769 auto &Infos = ForwardRefValueInfos[I.first]; 9770 for (auto P : I.second) { 9771 assert(Calls[P.first].first.getRef() == FwdVIRef && 9772 "Forward referenced ValueInfo expected to be empty"); 9773 Infos.emplace_back(&Calls[P.first].first, P.second); 9774 } 9775 } 9776 9777 if (parseToken(lltok::rparen, "expected ')' in calls")) 9778 return true; 9779 9780 return false; 9781 } 9782 9783 /// Hotness 9784 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 9785 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 9786 switch (Lex.getKind()) { 9787 case lltok::kw_unknown: 9788 Hotness = CalleeInfo::HotnessType::Unknown; 9789 break; 9790 case lltok::kw_cold: 9791 Hotness = CalleeInfo::HotnessType::Cold; 9792 break; 9793 case lltok::kw_none: 9794 Hotness = CalleeInfo::HotnessType::None; 9795 break; 9796 case lltok::kw_hot: 9797 Hotness = CalleeInfo::HotnessType::Hot; 9798 break; 9799 case lltok::kw_critical: 9800 Hotness = CalleeInfo::HotnessType::Critical; 9801 break; 9802 default: 9803 return error(Lex.getLoc(), "invalid call edge hotness"); 9804 } 9805 Lex.Lex(); 9806 return false; 9807 } 9808 9809 /// OptionalVTableFuncs 9810 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 9811 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 9812 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 9813 assert(Lex.getKind() == lltok::kw_vTableFuncs); 9814 Lex.Lex(); 9815 9816 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") || 9817 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 9818 return true; 9819 9820 IdToIndexMapType IdToIndexMap; 9821 // parse each virtual function pair 9822 do { 9823 ValueInfo VI; 9824 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 9825 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 9826 parseToken(lltok::colon, "expected ':'")) 9827 return true; 9828 9829 LocTy Loc = Lex.getLoc(); 9830 unsigned GVId; 9831 if (parseGVReference(VI, GVId)) 9832 return true; 9833 9834 uint64_t Offset; 9835 if (parseToken(lltok::comma, "expected comma") || 9836 parseToken(lltok::kw_offset, "expected offset") || 9837 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 9838 return true; 9839 9840 // Keep track of the VTableFuncs array index needing a forward reference. 9841 // We will save the location of the ValueInfo needing an update, but 9842 // can only do so once the std::vector is finalized. 9843 if (VI == EmptyVI) 9844 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 9845 VTableFuncs.push_back({VI, Offset}); 9846 9847 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 9848 return true; 9849 } while (EatIfPresent(lltok::comma)); 9850 9851 // Now that the VTableFuncs vector is finalized, it is safe to save the 9852 // locations of any forward GV references that need updating later. 9853 for (auto I : IdToIndexMap) { 9854 auto &Infos = ForwardRefValueInfos[I.first]; 9855 for (auto P : I.second) { 9856 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 9857 "Forward referenced ValueInfo expected to be empty"); 9858 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 9859 } 9860 } 9861 9862 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 9863 return true; 9864 9865 return false; 9866 } 9867 9868 /// ParamNo := 'param' ':' UInt64 9869 bool LLParser::parseParamNo(uint64_t &ParamNo) { 9870 if (parseToken(lltok::kw_param, "expected 'param' here") || 9871 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 9872 return true; 9873 return false; 9874 } 9875 9876 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 9877 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 9878 APSInt Lower; 9879 APSInt Upper; 9880 auto ParseAPSInt = [&](APSInt &Val) { 9881 if (Lex.getKind() != lltok::APSInt) 9882 return tokError("expected integer"); 9883 Val = Lex.getAPSIntVal(); 9884 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 9885 Val.setIsSigned(true); 9886 Lex.Lex(); 9887 return false; 9888 }; 9889 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 9890 parseToken(lltok::colon, "expected ':' here") || 9891 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 9892 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 9893 parseToken(lltok::rsquare, "expected ']' here")) 9894 return true; 9895 9896 ++Upper; 9897 Range = 9898 (Lower == Upper && !Lower.isMaxValue()) 9899 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 9900 : ConstantRange(Lower, Upper); 9901 9902 return false; 9903 } 9904 9905 /// ParamAccessCall 9906 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 9907 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 9908 IdLocListType &IdLocList) { 9909 if (parseToken(lltok::lparen, "expected '(' here") || 9910 parseToken(lltok::kw_callee, "expected 'callee' here") || 9911 parseToken(lltok::colon, "expected ':' here")) 9912 return true; 9913 9914 unsigned GVId; 9915 ValueInfo VI; 9916 LocTy Loc = Lex.getLoc(); 9917 if (parseGVReference(VI, GVId)) 9918 return true; 9919 9920 Call.Callee = VI; 9921 IdLocList.emplace_back(GVId, Loc); 9922 9923 if (parseToken(lltok::comma, "expected ',' here") || 9924 parseParamNo(Call.ParamNo) || 9925 parseToken(lltok::comma, "expected ',' here") || 9926 parseParamAccessOffset(Call.Offsets)) 9927 return true; 9928 9929 if (parseToken(lltok::rparen, "expected ')' here")) 9930 return true; 9931 9932 return false; 9933 } 9934 9935 /// ParamAccess 9936 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 9937 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 9938 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 9939 IdLocListType &IdLocList) { 9940 if (parseToken(lltok::lparen, "expected '(' here") || 9941 parseParamNo(Param.ParamNo) || 9942 parseToken(lltok::comma, "expected ',' here") || 9943 parseParamAccessOffset(Param.Use)) 9944 return true; 9945 9946 if (EatIfPresent(lltok::comma)) { 9947 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 9948 parseToken(lltok::colon, "expected ':' here") || 9949 parseToken(lltok::lparen, "expected '(' here")) 9950 return true; 9951 do { 9952 FunctionSummary::ParamAccess::Call Call; 9953 if (parseParamAccessCall(Call, IdLocList)) 9954 return true; 9955 Param.Calls.push_back(Call); 9956 } while (EatIfPresent(lltok::comma)); 9957 9958 if (parseToken(lltok::rparen, "expected ')' here")) 9959 return true; 9960 } 9961 9962 if (parseToken(lltok::rparen, "expected ')' here")) 9963 return true; 9964 9965 return false; 9966 } 9967 9968 /// OptionalParamAccesses 9969 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 9970 bool LLParser::parseOptionalParamAccesses( 9971 std::vector<FunctionSummary::ParamAccess> &Params) { 9972 assert(Lex.getKind() == lltok::kw_params); 9973 Lex.Lex(); 9974 9975 if (parseToken(lltok::colon, "expected ':' here") || 9976 parseToken(lltok::lparen, "expected '(' here")) 9977 return true; 9978 9979 IdLocListType VContexts; 9980 size_t CallsNum = 0; 9981 do { 9982 FunctionSummary::ParamAccess ParamAccess; 9983 if (parseParamAccess(ParamAccess, VContexts)) 9984 return true; 9985 CallsNum += ParamAccess.Calls.size(); 9986 assert(VContexts.size() == CallsNum); 9987 (void)CallsNum; 9988 Params.emplace_back(std::move(ParamAccess)); 9989 } while (EatIfPresent(lltok::comma)); 9990 9991 if (parseToken(lltok::rparen, "expected ')' here")) 9992 return true; 9993 9994 // Now that the Params is finalized, it is safe to save the locations 9995 // of any forward GV references that need updating later. 9996 IdLocListType::const_iterator ItContext = VContexts.begin(); 9997 for (auto &PA : Params) { 9998 for (auto &C : PA.Calls) { 9999 if (C.Callee.getRef() == FwdVIRef) 10000 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 10001 ItContext->second); 10002 ++ItContext; 10003 } 10004 } 10005 assert(ItContext == VContexts.end()); 10006 10007 return false; 10008 } 10009 10010 /// OptionalRefs 10011 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 10012 bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) { 10013 assert(Lex.getKind() == lltok::kw_refs); 10014 Lex.Lex(); 10015 10016 if (parseToken(lltok::colon, "expected ':' in refs") || 10017 parseToken(lltok::lparen, "expected '(' in refs")) 10018 return true; 10019 10020 struct ValueContext { 10021 ValueInfo VI; 10022 unsigned GVId; 10023 LocTy Loc; 10024 }; 10025 std::vector<ValueContext> VContexts; 10026 // parse each ref edge 10027 do { 10028 ValueContext VC; 10029 VC.Loc = Lex.getLoc(); 10030 if (parseGVReference(VC.VI, VC.GVId)) 10031 return true; 10032 VContexts.push_back(VC); 10033 } while (EatIfPresent(lltok::comma)); 10034 10035 // Sort value contexts so that ones with writeonly 10036 // and readonly ValueInfo are at the end of VContexts vector. 10037 // See FunctionSummary::specialRefCounts() 10038 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 10039 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 10040 }); 10041 10042 IdToIndexMapType IdToIndexMap; 10043 for (auto &VC : VContexts) { 10044 // Keep track of the Refs array index needing a forward reference. 10045 // We will save the location of the ValueInfo needing an update, but 10046 // can only do so once the std::vector is finalized. 10047 if (VC.VI.getRef() == FwdVIRef) 10048 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 10049 Refs.push_back(VC.VI); 10050 } 10051 10052 // Now that the Refs vector is finalized, it is safe to save the locations 10053 // of any forward GV references that need updating later. 10054 for (auto I : IdToIndexMap) { 10055 auto &Infos = ForwardRefValueInfos[I.first]; 10056 for (auto P : I.second) { 10057 assert(Refs[P.first].getRef() == FwdVIRef && 10058 "Forward referenced ValueInfo expected to be empty"); 10059 Infos.emplace_back(&Refs[P.first], P.second); 10060 } 10061 } 10062 10063 if (parseToken(lltok::rparen, "expected ')' in refs")) 10064 return true; 10065 10066 return false; 10067 } 10068 10069 /// OptionalTypeIdInfo 10070 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 10071 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 10072 /// [',' TypeCheckedLoadConstVCalls]? ')' 10073 bool LLParser::parseOptionalTypeIdInfo( 10074 FunctionSummary::TypeIdInfo &TypeIdInfo) { 10075 assert(Lex.getKind() == lltok::kw_typeIdInfo); 10076 Lex.Lex(); 10077 10078 if (parseToken(lltok::colon, "expected ':' here") || 10079 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 10080 return true; 10081 10082 do { 10083 switch (Lex.getKind()) { 10084 case lltok::kw_typeTests: 10085 if (parseTypeTests(TypeIdInfo.TypeTests)) 10086 return true; 10087 break; 10088 case lltok::kw_typeTestAssumeVCalls: 10089 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 10090 TypeIdInfo.TypeTestAssumeVCalls)) 10091 return true; 10092 break; 10093 case lltok::kw_typeCheckedLoadVCalls: 10094 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 10095 TypeIdInfo.TypeCheckedLoadVCalls)) 10096 return true; 10097 break; 10098 case lltok::kw_typeTestAssumeConstVCalls: 10099 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 10100 TypeIdInfo.TypeTestAssumeConstVCalls)) 10101 return true; 10102 break; 10103 case lltok::kw_typeCheckedLoadConstVCalls: 10104 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 10105 TypeIdInfo.TypeCheckedLoadConstVCalls)) 10106 return true; 10107 break; 10108 default: 10109 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 10110 } 10111 } while (EatIfPresent(lltok::comma)); 10112 10113 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 10114 return true; 10115 10116 return false; 10117 } 10118 10119 /// TypeTests 10120 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 10121 /// [',' (SummaryID | UInt64)]* ')' 10122 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 10123 assert(Lex.getKind() == lltok::kw_typeTests); 10124 Lex.Lex(); 10125 10126 if (parseToken(lltok::colon, "expected ':' here") || 10127 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 10128 return true; 10129 10130 IdToIndexMapType IdToIndexMap; 10131 do { 10132 GlobalValue::GUID GUID = 0; 10133 if (Lex.getKind() == lltok::SummaryID) { 10134 unsigned ID = Lex.getUIntVal(); 10135 LocTy Loc = Lex.getLoc(); 10136 // Keep track of the TypeTests array index needing a forward reference. 10137 // We will save the location of the GUID needing an update, but 10138 // can only do so once the std::vector is finalized. 10139 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 10140 Lex.Lex(); 10141 } else if (parseUInt64(GUID)) 10142 return true; 10143 TypeTests.push_back(GUID); 10144 } while (EatIfPresent(lltok::comma)); 10145 10146 // Now that the TypeTests vector is finalized, it is safe to save the 10147 // locations of any forward GV references that need updating later. 10148 for (auto I : IdToIndexMap) { 10149 auto &Ids = ForwardRefTypeIds[I.first]; 10150 for (auto P : I.second) { 10151 assert(TypeTests[P.first] == 0 && 10152 "Forward referenced type id GUID expected to be 0"); 10153 Ids.emplace_back(&TypeTests[P.first], P.second); 10154 } 10155 } 10156 10157 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 10158 return true; 10159 10160 return false; 10161 } 10162 10163 /// VFuncIdList 10164 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 10165 bool LLParser::parseVFuncIdList( 10166 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 10167 assert(Lex.getKind() == Kind); 10168 Lex.Lex(); 10169 10170 if (parseToken(lltok::colon, "expected ':' here") || 10171 parseToken(lltok::lparen, "expected '(' here")) 10172 return true; 10173 10174 IdToIndexMapType IdToIndexMap; 10175 do { 10176 FunctionSummary::VFuncId VFuncId; 10177 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 10178 return true; 10179 VFuncIdList.push_back(VFuncId); 10180 } while (EatIfPresent(lltok::comma)); 10181 10182 if (parseToken(lltok::rparen, "expected ')' here")) 10183 return true; 10184 10185 // Now that the VFuncIdList vector is finalized, it is safe to save the 10186 // locations of any forward GV references that need updating later. 10187 for (auto I : IdToIndexMap) { 10188 auto &Ids = ForwardRefTypeIds[I.first]; 10189 for (auto P : I.second) { 10190 assert(VFuncIdList[P.first].GUID == 0 && 10191 "Forward referenced type id GUID expected to be 0"); 10192 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 10193 } 10194 } 10195 10196 return false; 10197 } 10198 10199 /// ConstVCallList 10200 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 10201 bool LLParser::parseConstVCallList( 10202 lltok::Kind Kind, 10203 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 10204 assert(Lex.getKind() == Kind); 10205 Lex.Lex(); 10206 10207 if (parseToken(lltok::colon, "expected ':' here") || 10208 parseToken(lltok::lparen, "expected '(' here")) 10209 return true; 10210 10211 IdToIndexMapType IdToIndexMap; 10212 do { 10213 FunctionSummary::ConstVCall ConstVCall; 10214 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 10215 return true; 10216 ConstVCallList.push_back(ConstVCall); 10217 } while (EatIfPresent(lltok::comma)); 10218 10219 if (parseToken(lltok::rparen, "expected ')' here")) 10220 return true; 10221 10222 // Now that the ConstVCallList vector is finalized, it is safe to save the 10223 // locations of any forward GV references that need updating later. 10224 for (auto I : IdToIndexMap) { 10225 auto &Ids = ForwardRefTypeIds[I.first]; 10226 for (auto P : I.second) { 10227 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 10228 "Forward referenced type id GUID expected to be 0"); 10229 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 10230 } 10231 } 10232 10233 return false; 10234 } 10235 10236 /// ConstVCall 10237 /// ::= '(' VFuncId ',' Args ')' 10238 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 10239 IdToIndexMapType &IdToIndexMap, unsigned Index) { 10240 if (parseToken(lltok::lparen, "expected '(' here") || 10241 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 10242 return true; 10243 10244 if (EatIfPresent(lltok::comma)) 10245 if (parseArgs(ConstVCall.Args)) 10246 return true; 10247 10248 if (parseToken(lltok::rparen, "expected ')' here")) 10249 return true; 10250 10251 return false; 10252 } 10253 10254 /// VFuncId 10255 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 10256 /// 'offset' ':' UInt64 ')' 10257 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 10258 IdToIndexMapType &IdToIndexMap, unsigned Index) { 10259 assert(Lex.getKind() == lltok::kw_vFuncId); 10260 Lex.Lex(); 10261 10262 if (parseToken(lltok::colon, "expected ':' here") || 10263 parseToken(lltok::lparen, "expected '(' here")) 10264 return true; 10265 10266 if (Lex.getKind() == lltok::SummaryID) { 10267 VFuncId.GUID = 0; 10268 unsigned ID = Lex.getUIntVal(); 10269 LocTy Loc = Lex.getLoc(); 10270 // Keep track of the array index needing a forward reference. 10271 // We will save the location of the GUID needing an update, but 10272 // can only do so once the caller's std::vector is finalized. 10273 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 10274 Lex.Lex(); 10275 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 10276 parseToken(lltok::colon, "expected ':' here") || 10277 parseUInt64(VFuncId.GUID)) 10278 return true; 10279 10280 if (parseToken(lltok::comma, "expected ',' here") || 10281 parseToken(lltok::kw_offset, "expected 'offset' here") || 10282 parseToken(lltok::colon, "expected ':' here") || 10283 parseUInt64(VFuncId.Offset) || 10284 parseToken(lltok::rparen, "expected ')' here")) 10285 return true; 10286 10287 return false; 10288 } 10289 10290 /// GVFlags 10291 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 10292 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ',' 10293 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ',' 10294 /// 'canAutoHide' ':' Flag ',' ')' 10295 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 10296 assert(Lex.getKind() == lltok::kw_flags); 10297 Lex.Lex(); 10298 10299 if (parseToken(lltok::colon, "expected ':' here") || 10300 parseToken(lltok::lparen, "expected '(' here")) 10301 return true; 10302 10303 do { 10304 unsigned Flag = 0; 10305 switch (Lex.getKind()) { 10306 case lltok::kw_linkage: 10307 Lex.Lex(); 10308 if (parseToken(lltok::colon, "expected ':'")) 10309 return true; 10310 bool HasLinkage; 10311 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 10312 assert(HasLinkage && "Linkage not optional in summary entry"); 10313 Lex.Lex(); 10314 break; 10315 case lltok::kw_visibility: 10316 Lex.Lex(); 10317 if (parseToken(lltok::colon, "expected ':'")) 10318 return true; 10319 parseOptionalVisibility(Flag); 10320 GVFlags.Visibility = Flag; 10321 break; 10322 case lltok::kw_notEligibleToImport: 10323 Lex.Lex(); 10324 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10325 return true; 10326 GVFlags.NotEligibleToImport = Flag; 10327 break; 10328 case lltok::kw_live: 10329 Lex.Lex(); 10330 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10331 return true; 10332 GVFlags.Live = Flag; 10333 break; 10334 case lltok::kw_dsoLocal: 10335 Lex.Lex(); 10336 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10337 return true; 10338 GVFlags.DSOLocal = Flag; 10339 break; 10340 case lltok::kw_canAutoHide: 10341 Lex.Lex(); 10342 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10343 return true; 10344 GVFlags.CanAutoHide = Flag; 10345 break; 10346 case lltok::kw_importType: 10347 Lex.Lex(); 10348 if (parseToken(lltok::colon, "expected ':'")) 10349 return true; 10350 GlobalValueSummary::ImportKind IK; 10351 if (parseOptionalImportType(Lex.getKind(), IK)) 10352 return true; 10353 GVFlags.ImportType = static_cast<unsigned>(IK); 10354 Lex.Lex(); 10355 break; 10356 default: 10357 return error(Lex.getLoc(), "expected gv flag type"); 10358 } 10359 } while (EatIfPresent(lltok::comma)); 10360 10361 if (parseToken(lltok::rparen, "expected ')' here")) 10362 return true; 10363 10364 return false; 10365 } 10366 10367 /// GVarFlags 10368 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 10369 /// ',' 'writeonly' ':' Flag 10370 /// ',' 'constant' ':' Flag ')' 10371 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 10372 assert(Lex.getKind() == lltok::kw_varFlags); 10373 Lex.Lex(); 10374 10375 if (parseToken(lltok::colon, "expected ':' here") || 10376 parseToken(lltok::lparen, "expected '(' here")) 10377 return true; 10378 10379 auto ParseRest = [this](unsigned int &Val) { 10380 Lex.Lex(); 10381 if (parseToken(lltok::colon, "expected ':'")) 10382 return true; 10383 return parseFlag(Val); 10384 }; 10385 10386 do { 10387 unsigned Flag = 0; 10388 switch (Lex.getKind()) { 10389 case lltok::kw_readonly: 10390 if (ParseRest(Flag)) 10391 return true; 10392 GVarFlags.MaybeReadOnly = Flag; 10393 break; 10394 case lltok::kw_writeonly: 10395 if (ParseRest(Flag)) 10396 return true; 10397 GVarFlags.MaybeWriteOnly = Flag; 10398 break; 10399 case lltok::kw_constant: 10400 if (ParseRest(Flag)) 10401 return true; 10402 GVarFlags.Constant = Flag; 10403 break; 10404 case lltok::kw_vcall_visibility: 10405 if (ParseRest(Flag)) 10406 return true; 10407 GVarFlags.VCallVisibility = Flag; 10408 break; 10409 default: 10410 return error(Lex.getLoc(), "expected gvar flag type"); 10411 } 10412 } while (EatIfPresent(lltok::comma)); 10413 return parseToken(lltok::rparen, "expected ')' here"); 10414 } 10415 10416 /// ModuleReference 10417 /// ::= 'module' ':' UInt 10418 bool LLParser::parseModuleReference(StringRef &ModulePath) { 10419 // parse module id. 10420 if (parseToken(lltok::kw_module, "expected 'module' here") || 10421 parseToken(lltok::colon, "expected ':' here") || 10422 parseToken(lltok::SummaryID, "expected module ID")) 10423 return true; 10424 10425 unsigned ModuleID = Lex.getUIntVal(); 10426 auto I = ModuleIdMap.find(ModuleID); 10427 // We should have already parsed all module IDs 10428 assert(I != ModuleIdMap.end()); 10429 ModulePath = I->second; 10430 return false; 10431 } 10432 10433 /// GVReference 10434 /// ::= SummaryID 10435 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 10436 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 10437 if (!ReadOnly) 10438 WriteOnly = EatIfPresent(lltok::kw_writeonly); 10439 if (parseToken(lltok::SummaryID, "expected GV ID")) 10440 return true; 10441 10442 GVId = Lex.getUIntVal(); 10443 // Check if we already have a VI for this GV 10444 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) { 10445 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 10446 VI = NumberedValueInfos[GVId]; 10447 } else 10448 // We will create a forward reference to the stored location. 10449 VI = ValueInfo(false, FwdVIRef); 10450 10451 if (ReadOnly) 10452 VI.setReadOnly(); 10453 if (WriteOnly) 10454 VI.setWriteOnly(); 10455 return false; 10456 } 10457 10458 /// OptionalAllocs 10459 /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')' 10460 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')' 10461 /// ',' MemProfs ')' 10462 /// Version ::= UInt32 10463 bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) { 10464 assert(Lex.getKind() == lltok::kw_allocs); 10465 Lex.Lex(); 10466 10467 if (parseToken(lltok::colon, "expected ':' in allocs") || 10468 parseToken(lltok::lparen, "expected '(' in allocs")) 10469 return true; 10470 10471 // parse each alloc 10472 do { 10473 if (parseToken(lltok::lparen, "expected '(' in alloc") || 10474 parseToken(lltok::kw_versions, "expected 'versions' in alloc") || 10475 parseToken(lltok::colon, "expected ':'") || 10476 parseToken(lltok::lparen, "expected '(' in versions")) 10477 return true; 10478 10479 SmallVector<uint8_t> Versions; 10480 do { 10481 uint8_t V = 0; 10482 if (parseAllocType(V)) 10483 return true; 10484 Versions.push_back(V); 10485 } while (EatIfPresent(lltok::comma)); 10486 10487 if (parseToken(lltok::rparen, "expected ')' in versions") || 10488 parseToken(lltok::comma, "expected ',' in alloc")) 10489 return true; 10490 10491 std::vector<MIBInfo> MIBs; 10492 if (parseMemProfs(MIBs)) 10493 return true; 10494 10495 Allocs.push_back({Versions, MIBs}); 10496 10497 if (parseToken(lltok::rparen, "expected ')' in alloc")) 10498 return true; 10499 } while (EatIfPresent(lltok::comma)); 10500 10501 if (parseToken(lltok::rparen, "expected ')' in allocs")) 10502 return true; 10503 10504 return false; 10505 } 10506 10507 /// MemProfs 10508 /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')' 10509 /// MemProf ::= '(' 'type' ':' AllocType 10510 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')' 10511 /// StackId ::= UInt64 10512 bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) { 10513 assert(Lex.getKind() == lltok::kw_memProf); 10514 Lex.Lex(); 10515 10516 if (parseToken(lltok::colon, "expected ':' in memprof") || 10517 parseToken(lltok::lparen, "expected '(' in memprof")) 10518 return true; 10519 10520 // parse each MIB 10521 do { 10522 if (parseToken(lltok::lparen, "expected '(' in memprof") || 10523 parseToken(lltok::kw_type, "expected 'type' in memprof") || 10524 parseToken(lltok::colon, "expected ':'")) 10525 return true; 10526 10527 uint8_t AllocType; 10528 if (parseAllocType(AllocType)) 10529 return true; 10530 10531 if (parseToken(lltok::comma, "expected ',' in memprof") || 10532 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") || 10533 parseToken(lltok::colon, "expected ':'") || 10534 parseToken(lltok::lparen, "expected '(' in stackIds")) 10535 return true; 10536 10537 SmallVector<unsigned> StackIdIndices; 10538 do { 10539 uint64_t StackId = 0; 10540 if (parseUInt64(StackId)) 10541 return true; 10542 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId)); 10543 } while (EatIfPresent(lltok::comma)); 10544 10545 if (parseToken(lltok::rparen, "expected ')' in stackIds")) 10546 return true; 10547 10548 MIBs.push_back({(AllocationType)AllocType, StackIdIndices}); 10549 10550 if (parseToken(lltok::rparen, "expected ')' in memprof")) 10551 return true; 10552 } while (EatIfPresent(lltok::comma)); 10553 10554 if (parseToken(lltok::rparen, "expected ')' in memprof")) 10555 return true; 10556 10557 return false; 10558 } 10559 10560 /// AllocType 10561 /// := ('none'|'notcold'|'cold'|'hot') 10562 bool LLParser::parseAllocType(uint8_t &AllocType) { 10563 switch (Lex.getKind()) { 10564 case lltok::kw_none: 10565 AllocType = (uint8_t)AllocationType::None; 10566 break; 10567 case lltok::kw_notcold: 10568 AllocType = (uint8_t)AllocationType::NotCold; 10569 break; 10570 case lltok::kw_cold: 10571 AllocType = (uint8_t)AllocationType::Cold; 10572 break; 10573 case lltok::kw_hot: 10574 AllocType = (uint8_t)AllocationType::Hot; 10575 break; 10576 default: 10577 return error(Lex.getLoc(), "invalid alloc type"); 10578 } 10579 Lex.Lex(); 10580 return false; 10581 } 10582 10583 /// OptionalCallsites 10584 /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')' 10585 /// Callsite ::= '(' 'callee' ':' GVReference 10586 /// ',' 'clones' ':' '(' Version [',' Version]* ')' 10587 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')' 10588 /// Version ::= UInt32 10589 /// StackId ::= UInt64 10590 bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) { 10591 assert(Lex.getKind() == lltok::kw_callsites); 10592 Lex.Lex(); 10593 10594 if (parseToken(lltok::colon, "expected ':' in callsites") || 10595 parseToken(lltok::lparen, "expected '(' in callsites")) 10596 return true; 10597 10598 IdToIndexMapType IdToIndexMap; 10599 // parse each callsite 10600 do { 10601 if (parseToken(lltok::lparen, "expected '(' in callsite") || 10602 parseToken(lltok::kw_callee, "expected 'callee' in callsite") || 10603 parseToken(lltok::colon, "expected ':'")) 10604 return true; 10605 10606 ValueInfo VI; 10607 unsigned GVId = 0; 10608 LocTy Loc = Lex.getLoc(); 10609 if (!EatIfPresent(lltok::kw_null)) { 10610 if (parseGVReference(VI, GVId)) 10611 return true; 10612 } 10613 10614 if (parseToken(lltok::comma, "expected ',' in callsite") || 10615 parseToken(lltok::kw_clones, "expected 'clones' in callsite") || 10616 parseToken(lltok::colon, "expected ':'") || 10617 parseToken(lltok::lparen, "expected '(' in clones")) 10618 return true; 10619 10620 SmallVector<unsigned> Clones; 10621 do { 10622 unsigned V = 0; 10623 if (parseUInt32(V)) 10624 return true; 10625 Clones.push_back(V); 10626 } while (EatIfPresent(lltok::comma)); 10627 10628 if (parseToken(lltok::rparen, "expected ')' in clones") || 10629 parseToken(lltok::comma, "expected ',' in callsite") || 10630 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") || 10631 parseToken(lltok::colon, "expected ':'") || 10632 parseToken(lltok::lparen, "expected '(' in stackIds")) 10633 return true; 10634 10635 SmallVector<unsigned> StackIdIndices; 10636 do { 10637 uint64_t StackId = 0; 10638 if (parseUInt64(StackId)) 10639 return true; 10640 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId)); 10641 } while (EatIfPresent(lltok::comma)); 10642 10643 if (parseToken(lltok::rparen, "expected ')' in stackIds")) 10644 return true; 10645 10646 // Keep track of the Callsites array index needing a forward reference. 10647 // We will save the location of the ValueInfo needing an update, but 10648 // can only do so once the SmallVector is finalized. 10649 if (VI.getRef() == FwdVIRef) 10650 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc)); 10651 Callsites.push_back({VI, Clones, StackIdIndices}); 10652 10653 if (parseToken(lltok::rparen, "expected ')' in callsite")) 10654 return true; 10655 } while (EatIfPresent(lltok::comma)); 10656 10657 // Now that the Callsites vector is finalized, it is safe to save the 10658 // locations of any forward GV references that need updating later. 10659 for (auto I : IdToIndexMap) { 10660 auto &Infos = ForwardRefValueInfos[I.first]; 10661 for (auto P : I.second) { 10662 assert(Callsites[P.first].Callee.getRef() == FwdVIRef && 10663 "Forward referenced ValueInfo expected to be empty"); 10664 Infos.emplace_back(&Callsites[P.first].Callee, P.second); 10665 } 10666 } 10667 10668 if (parseToken(lltok::rparen, "expected ')' in callsites")) 10669 return true; 10670 10671 return false; 10672 } 10673