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_Poison: 6265 case ValID::t_Zero: 6266 case ValID::t_Constant: 6267 case ValID::t_ConstantSplat: 6268 case ValID::t_ConstantStruct: 6269 case ValID::t_PackedConstantStruct: { 6270 Value *V; 6271 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr)) 6272 return true; 6273 assert(isa<Constant>(V) && "Expected a constant value"); 6274 C = cast<Constant>(V); 6275 return false; 6276 } 6277 case ValID::t_Null: 6278 C = Constant::getNullValue(Ty); 6279 return false; 6280 default: 6281 return error(Loc, "expected a constant value"); 6282 } 6283 } 6284 6285 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) { 6286 V = nullptr; 6287 ValID ID; 6288 return parseValID(ID, PFS, Ty) || 6289 convertValIDToValue(Ty, ID, V, PFS); 6290 } 6291 6292 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) { 6293 Type *Ty = nullptr; 6294 return parseType(Ty) || parseValue(Ty, V, PFS); 6295 } 6296 6297 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc, 6298 PerFunctionState &PFS) { 6299 Value *V; 6300 Loc = Lex.getLoc(); 6301 if (parseTypeAndValue(V, PFS)) 6302 return true; 6303 if (!isa<BasicBlock>(V)) 6304 return error(Loc, "expected a basic block"); 6305 BB = cast<BasicBlock>(V); 6306 return false; 6307 } 6308 6309 bool isOldDbgFormatIntrinsic(StringRef Name) { 6310 // Exit early for the common (non-debug-intrinsic) case. 6311 // We can make this the only check when we begin supporting all "llvm.dbg" 6312 // intrinsics in the new debug info format. 6313 if (!Name.starts_with("llvm.dbg.")) 6314 return false; 6315 Intrinsic::ID FnID = Intrinsic::lookupIntrinsicID(Name); 6316 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value || 6317 FnID == Intrinsic::dbg_assign; 6318 } 6319 6320 /// FunctionHeader 6321 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility 6322 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName 6323 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign 6324 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn 6325 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine, 6326 unsigned &FunctionNumber, 6327 SmallVectorImpl<unsigned> &UnnamedArgNums) { 6328 // parse the linkage. 6329 LocTy LinkageLoc = Lex.getLoc(); 6330 unsigned Linkage; 6331 unsigned Visibility; 6332 unsigned DLLStorageClass; 6333 bool DSOLocal; 6334 AttrBuilder RetAttrs(M->getContext()); 6335 unsigned CC; 6336 bool HasLinkage; 6337 Type *RetType = nullptr; 6338 LocTy RetTypeLoc = Lex.getLoc(); 6339 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass, 6340 DSOLocal) || 6341 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 6342 parseType(RetType, RetTypeLoc, true /*void allowed*/)) 6343 return true; 6344 6345 // Verify that the linkage is ok. 6346 switch ((GlobalValue::LinkageTypes)Linkage) { 6347 case GlobalValue::ExternalLinkage: 6348 break; // always ok. 6349 case GlobalValue::ExternalWeakLinkage: 6350 if (IsDefine) 6351 return error(LinkageLoc, "invalid linkage for function definition"); 6352 break; 6353 case GlobalValue::PrivateLinkage: 6354 case GlobalValue::InternalLinkage: 6355 case GlobalValue::AvailableExternallyLinkage: 6356 case GlobalValue::LinkOnceAnyLinkage: 6357 case GlobalValue::LinkOnceODRLinkage: 6358 case GlobalValue::WeakAnyLinkage: 6359 case GlobalValue::WeakODRLinkage: 6360 if (!IsDefine) 6361 return error(LinkageLoc, "invalid linkage for function declaration"); 6362 break; 6363 case GlobalValue::AppendingLinkage: 6364 case GlobalValue::CommonLinkage: 6365 return error(LinkageLoc, "invalid function linkage type"); 6366 } 6367 6368 if (!isValidVisibilityForLinkage(Visibility, Linkage)) 6369 return error(LinkageLoc, 6370 "symbol with local linkage must have default visibility"); 6371 6372 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage)) 6373 return error(LinkageLoc, 6374 "symbol with local linkage cannot have a DLL storage class"); 6375 6376 if (!FunctionType::isValidReturnType(RetType)) 6377 return error(RetTypeLoc, "invalid function return type"); 6378 6379 LocTy NameLoc = Lex.getLoc(); 6380 6381 std::string FunctionName; 6382 if (Lex.getKind() == lltok::GlobalVar) { 6383 FunctionName = Lex.getStrVal(); 6384 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok. 6385 FunctionNumber = Lex.getUIntVal(); 6386 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(), 6387 FunctionNumber)) 6388 return true; 6389 } else { 6390 return tokError("expected function name"); 6391 } 6392 6393 Lex.Lex(); 6394 6395 if (Lex.getKind() != lltok::lparen) 6396 return tokError("expected '(' in function argument list"); 6397 6398 SmallVector<ArgInfo, 8> ArgList; 6399 bool IsVarArg; 6400 AttrBuilder FuncAttrs(M->getContext()); 6401 std::vector<unsigned> FwdRefAttrGrps; 6402 LocTy BuiltinLoc; 6403 std::string Section; 6404 std::string Partition; 6405 MaybeAlign Alignment; 6406 std::string GC; 6407 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 6408 unsigned AddrSpace = 0; 6409 Constant *Prefix = nullptr; 6410 Constant *Prologue = nullptr; 6411 Constant *PersonalityFn = nullptr; 6412 Comdat *C; 6413 6414 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) || 6415 parseOptionalUnnamedAddr(UnnamedAddr) || 6416 parseOptionalProgramAddrSpace(AddrSpace) || 6417 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false, 6418 BuiltinLoc) || 6419 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) || 6420 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) || 6421 parseOptionalComdat(FunctionName, C) || 6422 parseOptionalAlignment(Alignment) || 6423 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) || 6424 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) || 6425 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) || 6426 (EatIfPresent(lltok::kw_personality) && 6427 parseGlobalTypeAndValue(PersonalityFn))) 6428 return true; 6429 6430 if (FuncAttrs.contains(Attribute::Builtin)) 6431 return error(BuiltinLoc, "'builtin' attribute not valid on function"); 6432 6433 // If the alignment was parsed as an attribute, move to the alignment field. 6434 if (MaybeAlign A = FuncAttrs.getAlignment()) { 6435 Alignment = A; 6436 FuncAttrs.removeAttribute(Attribute::Alignment); 6437 } 6438 6439 // Okay, if we got here, the function is syntactically valid. Convert types 6440 // and do semantic checks. 6441 std::vector<Type*> ParamTypeList; 6442 SmallVector<AttributeSet, 8> Attrs; 6443 6444 for (const ArgInfo &Arg : ArgList) { 6445 ParamTypeList.push_back(Arg.Ty); 6446 Attrs.push_back(Arg.Attrs); 6447 } 6448 6449 AttributeList PAL = 6450 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs), 6451 AttributeSet::get(Context, RetAttrs), Attrs); 6452 6453 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy()) 6454 return error(RetTypeLoc, "functions with 'sret' argument must return void"); 6455 6456 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg); 6457 PointerType *PFT = PointerType::get(FT, AddrSpace); 6458 6459 Fn = nullptr; 6460 GlobalValue *FwdFn = nullptr; 6461 if (!FunctionName.empty()) { 6462 // If this was a definition of a forward reference, remove the definition 6463 // from the forward reference table and fill in the forward ref. 6464 auto FRVI = ForwardRefVals.find(FunctionName); 6465 if (FRVI != ForwardRefVals.end()) { 6466 FwdFn = FRVI->second.first; 6467 if (FwdFn->getType() != PFT) 6468 return error(FRVI->second.second, 6469 "invalid forward reference to " 6470 "function '" + 6471 FunctionName + 6472 "' with wrong type: " 6473 "expected '" + 6474 getTypeString(PFT) + "' but was '" + 6475 getTypeString(FwdFn->getType()) + "'"); 6476 ForwardRefVals.erase(FRVI); 6477 } else if ((Fn = M->getFunction(FunctionName))) { 6478 // Reject redefinitions. 6479 return error(NameLoc, 6480 "invalid redefinition of function '" + FunctionName + "'"); 6481 } else if (M->getNamedValue(FunctionName)) { 6482 return error(NameLoc, "redefinition of function '@" + FunctionName + "'"); 6483 } 6484 6485 } else { 6486 // Handle @"", where a name is syntactically specified, but semantically 6487 // missing. 6488 if (FunctionNumber == (unsigned)-1) 6489 FunctionNumber = NumberedVals.getNext(); 6490 6491 // If this is a definition of a forward referenced function, make sure the 6492 // types agree. 6493 auto I = ForwardRefValIDs.find(FunctionNumber); 6494 if (I != ForwardRefValIDs.end()) { 6495 FwdFn = I->second.first; 6496 if (FwdFn->getType() != PFT) 6497 return error(NameLoc, "type of definition and forward reference of '@" + 6498 Twine(FunctionNumber) + 6499 "' disagree: " 6500 "expected '" + 6501 getTypeString(PFT) + "' but was '" + 6502 getTypeString(FwdFn->getType()) + "'"); 6503 ForwardRefValIDs.erase(I); 6504 } 6505 } 6506 6507 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace, 6508 FunctionName, M); 6509 6510 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS"); 6511 6512 if (FunctionName.empty()) 6513 NumberedVals.add(FunctionNumber, Fn); 6514 6515 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage); 6516 maybeSetDSOLocal(DSOLocal, *Fn); 6517 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility); 6518 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass); 6519 Fn->setCallingConv(CC); 6520 Fn->setAttributes(PAL); 6521 Fn->setUnnamedAddr(UnnamedAddr); 6522 if (Alignment) 6523 Fn->setAlignment(*Alignment); 6524 Fn->setSection(Section); 6525 Fn->setPartition(Partition); 6526 Fn->setComdat(C); 6527 Fn->setPersonalityFn(PersonalityFn); 6528 if (!GC.empty()) Fn->setGC(GC); 6529 Fn->setPrefixData(Prefix); 6530 Fn->setPrologueData(Prologue); 6531 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps; 6532 6533 // Add all of the arguments we parsed to the function. 6534 Function::arg_iterator ArgIt = Fn->arg_begin(); 6535 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) { 6536 // If the argument has a name, insert it into the argument symbol table. 6537 if (ArgList[i].Name.empty()) continue; 6538 6539 // Set the name, if it conflicted, it will be auto-renamed. 6540 ArgIt->setName(ArgList[i].Name); 6541 6542 if (ArgIt->getName() != ArgList[i].Name) 6543 return error(ArgList[i].Loc, 6544 "redefinition of argument '%" + ArgList[i].Name + "'"); 6545 } 6546 6547 if (FwdFn) { 6548 FwdFn->replaceAllUsesWith(Fn); 6549 FwdFn->eraseFromParent(); 6550 } 6551 6552 if (IsDefine) 6553 return false; 6554 6555 // Check the declaration has no block address forward references. 6556 ValID ID; 6557 if (FunctionName.empty()) { 6558 ID.Kind = ValID::t_GlobalID; 6559 ID.UIntVal = FunctionNumber; 6560 } else { 6561 ID.Kind = ValID::t_GlobalName; 6562 ID.StrVal = FunctionName; 6563 } 6564 auto Blocks = ForwardRefBlockAddresses.find(ID); 6565 if (Blocks != ForwardRefBlockAddresses.end()) 6566 return error(Blocks->first.Loc, 6567 "cannot take blockaddress inside a declaration"); 6568 return false; 6569 } 6570 6571 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() { 6572 ValID ID; 6573 if (FunctionNumber == -1) { 6574 ID.Kind = ValID::t_GlobalName; 6575 ID.StrVal = std::string(F.getName()); 6576 } else { 6577 ID.Kind = ValID::t_GlobalID; 6578 ID.UIntVal = FunctionNumber; 6579 } 6580 6581 auto Blocks = P.ForwardRefBlockAddresses.find(ID); 6582 if (Blocks == P.ForwardRefBlockAddresses.end()) 6583 return false; 6584 6585 for (const auto &I : Blocks->second) { 6586 const ValID &BBID = I.first; 6587 GlobalValue *GV = I.second; 6588 6589 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) && 6590 "Expected local id or name"); 6591 BasicBlock *BB; 6592 if (BBID.Kind == ValID::t_LocalName) 6593 BB = getBB(BBID.StrVal, BBID.Loc); 6594 else 6595 BB = getBB(BBID.UIntVal, BBID.Loc); 6596 if (!BB) 6597 return P.error(BBID.Loc, "referenced value is not a basic block"); 6598 6599 Value *ResolvedVal = BlockAddress::get(&F, BB); 6600 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(), 6601 ResolvedVal); 6602 if (!ResolvedVal) 6603 return true; 6604 GV->replaceAllUsesWith(ResolvedVal); 6605 GV->eraseFromParent(); 6606 } 6607 6608 P.ForwardRefBlockAddresses.erase(Blocks); 6609 return false; 6610 } 6611 6612 /// parseFunctionBody 6613 /// ::= '{' BasicBlock+ UseListOrderDirective* '}' 6614 bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber, 6615 ArrayRef<unsigned> UnnamedArgNums) { 6616 if (Lex.getKind() != lltok::lbrace) 6617 return tokError("expected '{' in function body"); 6618 Lex.Lex(); // eat the {. 6619 6620 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums); 6621 6622 // Resolve block addresses and allow basic blocks to be forward-declared 6623 // within this function. 6624 if (PFS.resolveForwardRefBlockAddresses()) 6625 return true; 6626 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS); 6627 6628 // We need at least one basic block. 6629 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder) 6630 return tokError("function body requires at least one basic block"); 6631 6632 while (Lex.getKind() != lltok::rbrace && 6633 Lex.getKind() != lltok::kw_uselistorder) 6634 if (parseBasicBlock(PFS)) 6635 return true; 6636 6637 while (Lex.getKind() != lltok::rbrace) 6638 if (parseUseListOrder(&PFS)) 6639 return true; 6640 6641 // Eat the }. 6642 Lex.Lex(); 6643 6644 // Verify function is ok. 6645 return PFS.finishFunction(); 6646 } 6647 6648 /// parseBasicBlock 6649 /// ::= (LabelStr|LabelID)? Instruction* 6650 bool LLParser::parseBasicBlock(PerFunctionState &PFS) { 6651 // If this basic block starts out with a name, remember it. 6652 std::string Name; 6653 int NameID = -1; 6654 LocTy NameLoc = Lex.getLoc(); 6655 if (Lex.getKind() == lltok::LabelStr) { 6656 Name = Lex.getStrVal(); 6657 Lex.Lex(); 6658 } else if (Lex.getKind() == lltok::LabelID) { 6659 NameID = Lex.getUIntVal(); 6660 Lex.Lex(); 6661 } 6662 6663 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc); 6664 if (!BB) 6665 return true; 6666 6667 std::string NameStr; 6668 6669 // Parse the instructions and debug values in this block until we get a 6670 // terminator. 6671 Instruction *Inst; 6672 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); }; 6673 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>; 6674 SmallVector<DbgRecordPtr> TrailingDbgRecord; 6675 do { 6676 // Handle debug records first - there should always be an instruction 6677 // following the debug records, i.e. they cannot appear after the block 6678 // terminator. 6679 while (Lex.getKind() == lltok::hash) { 6680 if (SeenOldDbgInfoFormat) 6681 return error(Lex.getLoc(), "debug record should not appear in a module " 6682 "containing debug info intrinsics"); 6683 if (!SeenNewDbgInfoFormat) 6684 M->setNewDbgInfoFormatFlag(true); 6685 SeenNewDbgInfoFormat = true; 6686 Lex.Lex(); 6687 6688 DbgRecord *DR; 6689 if (parseDebugRecord(DR, PFS)) 6690 return true; 6691 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord); 6692 } 6693 6694 // This instruction may have three possibilities for a name: a) none 6695 // specified, b) name specified "%foo =", c) number specified: "%4 =". 6696 LocTy NameLoc = Lex.getLoc(); 6697 int NameID = -1; 6698 NameStr = ""; 6699 6700 if (Lex.getKind() == lltok::LocalVarID) { 6701 NameID = Lex.getUIntVal(); 6702 Lex.Lex(); 6703 if (parseToken(lltok::equal, "expected '=' after instruction id")) 6704 return true; 6705 } else if (Lex.getKind() == lltok::LocalVar) { 6706 NameStr = Lex.getStrVal(); 6707 Lex.Lex(); 6708 if (parseToken(lltok::equal, "expected '=' after instruction name")) 6709 return true; 6710 } 6711 6712 switch (parseInstruction(Inst, BB, PFS)) { 6713 default: 6714 llvm_unreachable("Unknown parseInstruction result!"); 6715 case InstError: return true; 6716 case InstNormal: 6717 Inst->insertInto(BB, BB->end()); 6718 6719 // With a normal result, we check to see if the instruction is followed by 6720 // a comma and metadata. 6721 if (EatIfPresent(lltok::comma)) 6722 if (parseInstructionMetadata(*Inst)) 6723 return true; 6724 break; 6725 case InstExtraComma: 6726 Inst->insertInto(BB, BB->end()); 6727 6728 // If the instruction parser ate an extra comma at the end of it, it 6729 // *must* be followed by metadata. 6730 if (parseInstructionMetadata(*Inst)) 6731 return true; 6732 break; 6733 } 6734 6735 // Set the name on the instruction. 6736 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst)) 6737 return true; 6738 6739 // Attach any preceding debug values to this instruction. 6740 for (DbgRecordPtr &DR : TrailingDbgRecord) 6741 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator()); 6742 TrailingDbgRecord.clear(); 6743 } while (!Inst->isTerminator()); 6744 6745 assert(TrailingDbgRecord.empty() && 6746 "All debug values should have been attached to an instruction."); 6747 6748 return false; 6749 } 6750 6751 /// parseDebugRecord 6752 /// ::= #dbg_label '(' MDNode ')' 6753 /// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ',' 6754 /// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')' 6755 bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) { 6756 using RecordKind = DbgRecord::Kind; 6757 using LocType = DbgVariableRecord::LocationType; 6758 LocTy DVRLoc = Lex.getLoc(); 6759 if (Lex.getKind() != lltok::DbgRecordType) 6760 return error(DVRLoc, "expected debug record type here"); 6761 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal()) 6762 .Case("declare", RecordKind::ValueKind) 6763 .Case("value", RecordKind::ValueKind) 6764 .Case("assign", RecordKind::ValueKind) 6765 .Case("label", RecordKind::LabelKind); 6766 6767 // Parsing labels is trivial; parse here and early exit, otherwise go into the 6768 // full DbgVariableRecord processing stage. 6769 if (RecordType == RecordKind::LabelKind) { 6770 Lex.Lex(); 6771 if (parseToken(lltok::lparen, "Expected '(' here")) 6772 return true; 6773 MDNode *Label; 6774 if (parseMDNode(Label)) 6775 return true; 6776 if (parseToken(lltok::comma, "Expected ',' here")) 6777 return true; 6778 MDNode *DbgLoc; 6779 if (parseMDNode(DbgLoc)) 6780 return true; 6781 if (parseToken(lltok::rparen, "Expected ')' here")) 6782 return true; 6783 DR = DbgLabelRecord::createUnresolvedDbgLabelRecord(Label, DbgLoc); 6784 return false; 6785 } 6786 6787 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal()) 6788 .Case("declare", LocType::Declare) 6789 .Case("value", LocType::Value) 6790 .Case("assign", LocType::Assign); 6791 6792 Lex.Lex(); 6793 if (parseToken(lltok::lparen, "Expected '(' here")) 6794 return true; 6795 6796 // Parse Value field. 6797 Metadata *ValLocMD; 6798 if (parseMetadata(ValLocMD, &PFS)) 6799 return true; 6800 if (parseToken(lltok::comma, "Expected ',' here")) 6801 return true; 6802 6803 // Parse Variable field. 6804 MDNode *Variable; 6805 if (parseMDNode(Variable)) 6806 return true; 6807 if (parseToken(lltok::comma, "Expected ',' here")) 6808 return true; 6809 6810 // Parse Expression field. 6811 MDNode *Expression; 6812 if (parseMDNode(Expression)) 6813 return true; 6814 if (parseToken(lltok::comma, "Expected ',' here")) 6815 return true; 6816 6817 // Parse additional fields for #dbg_assign. 6818 MDNode *AssignID = nullptr; 6819 Metadata *AddressLocation = nullptr; 6820 MDNode *AddressExpression = nullptr; 6821 if (ValueType == LocType::Assign) { 6822 // Parse DIAssignID. 6823 if (parseMDNode(AssignID)) 6824 return true; 6825 if (parseToken(lltok::comma, "Expected ',' here")) 6826 return true; 6827 6828 // Parse address ValueAsMetadata. 6829 if (parseMetadata(AddressLocation, &PFS)) 6830 return true; 6831 if (parseToken(lltok::comma, "Expected ',' here")) 6832 return true; 6833 6834 // Parse address DIExpression. 6835 if (parseMDNode(AddressExpression)) 6836 return true; 6837 if (parseToken(lltok::comma, "Expected ',' here")) 6838 return true; 6839 } 6840 6841 /// Parse DILocation. 6842 MDNode *DebugLoc; 6843 if (parseMDNode(DebugLoc)) 6844 return true; 6845 6846 if (parseToken(lltok::rparen, "Expected ')' here")) 6847 return true; 6848 DR = DbgVariableRecord::createUnresolvedDbgVariableRecord( 6849 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation, 6850 AddressExpression, DebugLoc); 6851 return false; 6852 } 6853 //===----------------------------------------------------------------------===// 6854 // Instruction Parsing. 6855 //===----------------------------------------------------------------------===// 6856 6857 /// parseInstruction - parse one of the many different instructions. 6858 /// 6859 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB, 6860 PerFunctionState &PFS) { 6861 lltok::Kind Token = Lex.getKind(); 6862 if (Token == lltok::Eof) 6863 return tokError("found end of file when expecting more instructions"); 6864 LocTy Loc = Lex.getLoc(); 6865 unsigned KeywordVal = Lex.getUIntVal(); 6866 Lex.Lex(); // Eat the keyword. 6867 6868 switch (Token) { 6869 default: 6870 return error(Loc, "expected instruction opcode"); 6871 // Terminator Instructions. 6872 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false; 6873 case lltok::kw_ret: 6874 return parseRet(Inst, BB, PFS); 6875 case lltok::kw_br: 6876 return parseBr(Inst, PFS); 6877 case lltok::kw_switch: 6878 return parseSwitch(Inst, PFS); 6879 case lltok::kw_indirectbr: 6880 return parseIndirectBr(Inst, PFS); 6881 case lltok::kw_invoke: 6882 return parseInvoke(Inst, PFS); 6883 case lltok::kw_resume: 6884 return parseResume(Inst, PFS); 6885 case lltok::kw_cleanupret: 6886 return parseCleanupRet(Inst, PFS); 6887 case lltok::kw_catchret: 6888 return parseCatchRet(Inst, PFS); 6889 case lltok::kw_catchswitch: 6890 return parseCatchSwitch(Inst, PFS); 6891 case lltok::kw_catchpad: 6892 return parseCatchPad(Inst, PFS); 6893 case lltok::kw_cleanuppad: 6894 return parseCleanupPad(Inst, PFS); 6895 case lltok::kw_callbr: 6896 return parseCallBr(Inst, PFS); 6897 // Unary Operators. 6898 case lltok::kw_fneg: { 6899 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6900 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true); 6901 if (Res != 0) 6902 return Res; 6903 if (FMF.any()) 6904 Inst->setFastMathFlags(FMF); 6905 return false; 6906 } 6907 // Binary Operators. 6908 case lltok::kw_add: 6909 case lltok::kw_sub: 6910 case lltok::kw_mul: 6911 case lltok::kw_shl: { 6912 bool NUW = EatIfPresent(lltok::kw_nuw); 6913 bool NSW = EatIfPresent(lltok::kw_nsw); 6914 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw); 6915 6916 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6917 return true; 6918 6919 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true); 6920 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true); 6921 return false; 6922 } 6923 case lltok::kw_fadd: 6924 case lltok::kw_fsub: 6925 case lltok::kw_fmul: 6926 case lltok::kw_fdiv: 6927 case lltok::kw_frem: { 6928 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6929 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true); 6930 if (Res != 0) 6931 return Res; 6932 if (FMF.any()) 6933 Inst->setFastMathFlags(FMF); 6934 return 0; 6935 } 6936 6937 case lltok::kw_sdiv: 6938 case lltok::kw_udiv: 6939 case lltok::kw_lshr: 6940 case lltok::kw_ashr: { 6941 bool Exact = EatIfPresent(lltok::kw_exact); 6942 6943 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false)) 6944 return true; 6945 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true); 6946 return false; 6947 } 6948 6949 case lltok::kw_urem: 6950 case lltok::kw_srem: 6951 return parseArithmetic(Inst, PFS, KeywordVal, 6952 /*IsFP*/ false); 6953 case lltok::kw_or: { 6954 bool Disjoint = EatIfPresent(lltok::kw_disjoint); 6955 if (parseLogical(Inst, PFS, KeywordVal)) 6956 return true; 6957 if (Disjoint) 6958 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true); 6959 return false; 6960 } 6961 case lltok::kw_and: 6962 case lltok::kw_xor: 6963 return parseLogical(Inst, PFS, KeywordVal); 6964 case lltok::kw_icmp: { 6965 bool SameSign = EatIfPresent(lltok::kw_samesign); 6966 if (parseCompare(Inst, PFS, KeywordVal)) 6967 return true; 6968 if (SameSign) 6969 cast<ICmpInst>(Inst)->setSameSign(); 6970 return false; 6971 } 6972 case lltok::kw_fcmp: { 6973 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 6974 int Res = parseCompare(Inst, PFS, KeywordVal); 6975 if (Res != 0) 6976 return Res; 6977 if (FMF.any()) 6978 Inst->setFastMathFlags(FMF); 6979 return 0; 6980 } 6981 6982 // Casts. 6983 case lltok::kw_uitofp: 6984 case lltok::kw_zext: { 6985 bool NonNeg = EatIfPresent(lltok::kw_nneg); 6986 bool Res = parseCast(Inst, PFS, KeywordVal); 6987 if (Res != 0) 6988 return Res; 6989 if (NonNeg) 6990 Inst->setNonNeg(); 6991 return 0; 6992 } 6993 case lltok::kw_trunc: { 6994 bool NUW = EatIfPresent(lltok::kw_nuw); 6995 bool NSW = EatIfPresent(lltok::kw_nsw); 6996 if (!NUW) 6997 NUW = EatIfPresent(lltok::kw_nuw); 6998 if (parseCast(Inst, PFS, KeywordVal)) 6999 return true; 7000 if (NUW) 7001 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true); 7002 if (NSW) 7003 cast<TruncInst>(Inst)->setHasNoSignedWrap(true); 7004 return false; 7005 } 7006 case lltok::kw_sext: 7007 case lltok::kw_fptrunc: 7008 case lltok::kw_fpext: 7009 case lltok::kw_bitcast: 7010 case lltok::kw_addrspacecast: 7011 case lltok::kw_sitofp: 7012 case lltok::kw_fptoui: 7013 case lltok::kw_fptosi: 7014 case lltok::kw_inttoptr: 7015 case lltok::kw_ptrtoint: 7016 return parseCast(Inst, PFS, KeywordVal); 7017 // Other. 7018 case lltok::kw_select: { 7019 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7020 int Res = parseSelect(Inst, PFS); 7021 if (Res != 0) 7022 return Res; 7023 if (FMF.any()) { 7024 if (!isa<FPMathOperator>(Inst)) 7025 return error(Loc, "fast-math-flags specified for select without " 7026 "floating-point scalar or vector return type"); 7027 Inst->setFastMathFlags(FMF); 7028 } 7029 return 0; 7030 } 7031 case lltok::kw_va_arg: 7032 return parseVAArg(Inst, PFS); 7033 case lltok::kw_extractelement: 7034 return parseExtractElement(Inst, PFS); 7035 case lltok::kw_insertelement: 7036 return parseInsertElement(Inst, PFS); 7037 case lltok::kw_shufflevector: 7038 return parseShuffleVector(Inst, PFS); 7039 case lltok::kw_phi: { 7040 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 7041 int Res = parsePHI(Inst, PFS); 7042 if (Res != 0) 7043 return Res; 7044 if (FMF.any()) { 7045 if (!isa<FPMathOperator>(Inst)) 7046 return error(Loc, "fast-math-flags specified for phi without " 7047 "floating-point scalar or vector return type"); 7048 Inst->setFastMathFlags(FMF); 7049 } 7050 return 0; 7051 } 7052 case lltok::kw_landingpad: 7053 return parseLandingPad(Inst, PFS); 7054 case lltok::kw_freeze: 7055 return parseFreeze(Inst, PFS); 7056 // Call. 7057 case lltok::kw_call: 7058 return parseCall(Inst, PFS, CallInst::TCK_None); 7059 case lltok::kw_tail: 7060 return parseCall(Inst, PFS, CallInst::TCK_Tail); 7061 case lltok::kw_musttail: 7062 return parseCall(Inst, PFS, CallInst::TCK_MustTail); 7063 case lltok::kw_notail: 7064 return parseCall(Inst, PFS, CallInst::TCK_NoTail); 7065 // Memory. 7066 case lltok::kw_alloca: 7067 return parseAlloc(Inst, PFS); 7068 case lltok::kw_load: 7069 return parseLoad(Inst, PFS); 7070 case lltok::kw_store: 7071 return parseStore(Inst, PFS); 7072 case lltok::kw_cmpxchg: 7073 return parseCmpXchg(Inst, PFS); 7074 case lltok::kw_atomicrmw: 7075 return parseAtomicRMW(Inst, PFS); 7076 case lltok::kw_fence: 7077 return parseFence(Inst, PFS); 7078 case lltok::kw_getelementptr: 7079 return parseGetElementPtr(Inst, PFS); 7080 case lltok::kw_extractvalue: 7081 return parseExtractValue(Inst, PFS); 7082 case lltok::kw_insertvalue: 7083 return parseInsertValue(Inst, PFS); 7084 } 7085 } 7086 7087 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind. 7088 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) { 7089 if (Opc == Instruction::FCmp) { 7090 switch (Lex.getKind()) { 7091 default: 7092 return tokError("expected fcmp predicate (e.g. 'oeq')"); 7093 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break; 7094 case lltok::kw_one: P = CmpInst::FCMP_ONE; break; 7095 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break; 7096 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break; 7097 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break; 7098 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break; 7099 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break; 7100 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break; 7101 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break; 7102 case lltok::kw_une: P = CmpInst::FCMP_UNE; break; 7103 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break; 7104 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break; 7105 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break; 7106 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break; 7107 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break; 7108 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break; 7109 } 7110 } else { 7111 switch (Lex.getKind()) { 7112 default: 7113 return tokError("expected icmp predicate (e.g. 'eq')"); 7114 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break; 7115 case lltok::kw_ne: P = CmpInst::ICMP_NE; break; 7116 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break; 7117 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break; 7118 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break; 7119 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break; 7120 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break; 7121 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break; 7122 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break; 7123 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break; 7124 } 7125 } 7126 Lex.Lex(); 7127 return false; 7128 } 7129 7130 //===----------------------------------------------------------------------===// 7131 // Terminator Instructions. 7132 //===----------------------------------------------------------------------===// 7133 7134 /// parseRet - parse a return instruction. 7135 /// ::= 'ret' void (',' !dbg, !1)* 7136 /// ::= 'ret' TypeAndValue (',' !dbg, !1)* 7137 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB, 7138 PerFunctionState &PFS) { 7139 SMLoc TypeLoc = Lex.getLoc(); 7140 Type *Ty = nullptr; 7141 if (parseType(Ty, true /*void allowed*/)) 7142 return true; 7143 7144 Type *ResType = PFS.getFunction().getReturnType(); 7145 7146 if (Ty->isVoidTy()) { 7147 if (!ResType->isVoidTy()) 7148 return error(TypeLoc, "value doesn't match function result type '" + 7149 getTypeString(ResType) + "'"); 7150 7151 Inst = ReturnInst::Create(Context); 7152 return false; 7153 } 7154 7155 Value *RV; 7156 if (parseValue(Ty, RV, PFS)) 7157 return true; 7158 7159 if (ResType != RV->getType()) 7160 return error(TypeLoc, "value doesn't match function result type '" + 7161 getTypeString(ResType) + "'"); 7162 7163 Inst = ReturnInst::Create(Context, RV); 7164 return false; 7165 } 7166 7167 /// parseBr 7168 /// ::= 'br' TypeAndValue 7169 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7170 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) { 7171 LocTy Loc, Loc2; 7172 Value *Op0; 7173 BasicBlock *Op1, *Op2; 7174 if (parseTypeAndValue(Op0, Loc, PFS)) 7175 return true; 7176 7177 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) { 7178 Inst = BranchInst::Create(BB); 7179 return false; 7180 } 7181 7182 if (Op0->getType() != Type::getInt1Ty(Context)) 7183 return error(Loc, "branch condition must have 'i1' type"); 7184 7185 if (parseToken(lltok::comma, "expected ',' after branch condition") || 7186 parseTypeAndBasicBlock(Op1, Loc, PFS) || 7187 parseToken(lltok::comma, "expected ',' after true destination") || 7188 parseTypeAndBasicBlock(Op2, Loc2, PFS)) 7189 return true; 7190 7191 Inst = BranchInst::Create(Op1, Op2, Op0); 7192 return false; 7193 } 7194 7195 /// parseSwitch 7196 /// Instruction 7197 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']' 7198 /// JumpTable 7199 /// ::= (TypeAndValue ',' TypeAndValue)* 7200 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) { 7201 LocTy CondLoc, BBLoc; 7202 Value *Cond; 7203 BasicBlock *DefaultBB; 7204 if (parseTypeAndValue(Cond, CondLoc, PFS) || 7205 parseToken(lltok::comma, "expected ',' after switch condition") || 7206 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) || 7207 parseToken(lltok::lsquare, "expected '[' with switch table")) 7208 return true; 7209 7210 if (!Cond->getType()->isIntegerTy()) 7211 return error(CondLoc, "switch condition must have integer type"); 7212 7213 // parse the jump table pairs. 7214 SmallPtrSet<Value*, 32> SeenCases; 7215 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table; 7216 while (Lex.getKind() != lltok::rsquare) { 7217 Value *Constant; 7218 BasicBlock *DestBB; 7219 7220 if (parseTypeAndValue(Constant, CondLoc, PFS) || 7221 parseToken(lltok::comma, "expected ',' after case value") || 7222 parseTypeAndBasicBlock(DestBB, PFS)) 7223 return true; 7224 7225 if (!SeenCases.insert(Constant).second) 7226 return error(CondLoc, "duplicate case value in switch"); 7227 if (!isa<ConstantInt>(Constant)) 7228 return error(CondLoc, "case value is not a constant integer"); 7229 7230 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB)); 7231 } 7232 7233 Lex.Lex(); // Eat the ']'. 7234 7235 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size()); 7236 for (unsigned i = 0, e = Table.size(); i != e; ++i) 7237 SI->addCase(Table[i].first, Table[i].second); 7238 Inst = SI; 7239 return false; 7240 } 7241 7242 /// parseIndirectBr 7243 /// Instruction 7244 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']' 7245 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) { 7246 LocTy AddrLoc; 7247 Value *Address; 7248 if (parseTypeAndValue(Address, AddrLoc, PFS) || 7249 parseToken(lltok::comma, "expected ',' after indirectbr address") || 7250 parseToken(lltok::lsquare, "expected '[' with indirectbr")) 7251 return true; 7252 7253 if (!Address->getType()->isPointerTy()) 7254 return error(AddrLoc, "indirectbr address must have pointer type"); 7255 7256 // parse the destination list. 7257 SmallVector<BasicBlock*, 16> DestList; 7258 7259 if (Lex.getKind() != lltok::rsquare) { 7260 BasicBlock *DestBB; 7261 if (parseTypeAndBasicBlock(DestBB, PFS)) 7262 return true; 7263 DestList.push_back(DestBB); 7264 7265 while (EatIfPresent(lltok::comma)) { 7266 if (parseTypeAndBasicBlock(DestBB, PFS)) 7267 return true; 7268 DestList.push_back(DestBB); 7269 } 7270 } 7271 7272 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 7273 return true; 7274 7275 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size()); 7276 for (BasicBlock *Dest : DestList) 7277 IBI->addDestination(Dest); 7278 Inst = IBI; 7279 return false; 7280 } 7281 7282 // If RetType is a non-function pointer type, then this is the short syntax 7283 // for the call, which means that RetType is just the return type. Infer the 7284 // rest of the function argument types from the arguments that are present. 7285 bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList, 7286 FunctionType *&FuncTy) { 7287 FuncTy = dyn_cast<FunctionType>(RetType); 7288 if (!FuncTy) { 7289 // Pull out the types of all of the arguments... 7290 SmallVector<Type *, 8> ParamTypes; 7291 ParamTypes.reserve(ArgList.size()); 7292 for (const ParamInfo &Arg : ArgList) 7293 ParamTypes.push_back(Arg.V->getType()); 7294 7295 if (!FunctionType::isValidReturnType(RetType)) 7296 return true; 7297 7298 FuncTy = FunctionType::get(RetType, ParamTypes, false); 7299 } 7300 return false; 7301 } 7302 7303 /// parseInvoke 7304 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList 7305 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue 7306 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) { 7307 LocTy CallLoc = Lex.getLoc(); 7308 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 7309 std::vector<unsigned> FwdRefAttrGrps; 7310 LocTy NoBuiltinLoc; 7311 unsigned CC; 7312 unsigned InvokeAddrSpace; 7313 Type *RetType = nullptr; 7314 LocTy RetTypeLoc; 7315 ValID CalleeID; 7316 SmallVector<ParamInfo, 16> ArgList; 7317 SmallVector<OperandBundleDef, 2> BundleList; 7318 7319 BasicBlock *NormalBB, *UnwindBB; 7320 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7321 parseOptionalProgramAddrSpace(InvokeAddrSpace) || 7322 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7323 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 7324 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 7325 NoBuiltinLoc) || 7326 parseOptionalOperandBundles(BundleList, PFS) || 7327 parseToken(lltok::kw_to, "expected 'to' in invoke") || 7328 parseTypeAndBasicBlock(NormalBB, PFS) || 7329 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") || 7330 parseTypeAndBasicBlock(UnwindBB, PFS)) 7331 return true; 7332 7333 // If RetType is a non-function pointer type, then this is the short syntax 7334 // for the call, which means that RetType is just the return type. Infer the 7335 // rest of the function argument types from the arguments that are present. 7336 FunctionType *Ty; 7337 if (resolveFunctionType(RetType, ArgList, Ty)) 7338 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7339 7340 CalleeID.FTy = Ty; 7341 7342 // Look up the callee. 7343 Value *Callee; 7344 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID, 7345 Callee, &PFS)) 7346 return true; 7347 7348 // Set up the Attribute for the function. 7349 SmallVector<Value *, 8> Args; 7350 SmallVector<AttributeSet, 8> ArgAttrs; 7351 7352 // Loop through FunctionType's arguments and ensure they are specified 7353 // correctly. Also, gather any parameter attributes. 7354 FunctionType::param_iterator I = Ty->param_begin(); 7355 FunctionType::param_iterator E = Ty->param_end(); 7356 for (const ParamInfo &Arg : ArgList) { 7357 Type *ExpectedTy = nullptr; 7358 if (I != E) { 7359 ExpectedTy = *I++; 7360 } else if (!Ty->isVarArg()) { 7361 return error(Arg.Loc, "too many arguments specified"); 7362 } 7363 7364 if (ExpectedTy && ExpectedTy != Arg.V->getType()) 7365 return error(Arg.Loc, "argument is not of expected type '" + 7366 getTypeString(ExpectedTy) + "'"); 7367 Args.push_back(Arg.V); 7368 ArgAttrs.push_back(Arg.Attrs); 7369 } 7370 7371 if (I != E) 7372 return error(CallLoc, "not enough parameters specified for call"); 7373 7374 // Finish off the Attribute and check them 7375 AttributeList PAL = 7376 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7377 AttributeSet::get(Context, RetAttrs), ArgAttrs); 7378 7379 InvokeInst *II = 7380 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList); 7381 II->setCallingConv(CC); 7382 II->setAttributes(PAL); 7383 ForwardRefAttrGroups[II] = FwdRefAttrGrps; 7384 Inst = II; 7385 return false; 7386 } 7387 7388 /// parseResume 7389 /// ::= 'resume' TypeAndValue 7390 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) { 7391 Value *Exn; LocTy ExnLoc; 7392 if (parseTypeAndValue(Exn, ExnLoc, PFS)) 7393 return true; 7394 7395 ResumeInst *RI = ResumeInst::Create(Exn); 7396 Inst = RI; 7397 return false; 7398 } 7399 7400 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args, 7401 PerFunctionState &PFS) { 7402 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad")) 7403 return true; 7404 7405 while (Lex.getKind() != lltok::rsquare) { 7406 // If this isn't the first argument, we need a comma. 7407 if (!Args.empty() && 7408 parseToken(lltok::comma, "expected ',' in argument list")) 7409 return true; 7410 7411 // parse the argument. 7412 LocTy ArgLoc; 7413 Type *ArgTy = nullptr; 7414 if (parseType(ArgTy, ArgLoc)) 7415 return true; 7416 7417 Value *V; 7418 if (ArgTy->isMetadataTy()) { 7419 if (parseMetadataAsValue(V, PFS)) 7420 return true; 7421 } else { 7422 if (parseValue(ArgTy, V, PFS)) 7423 return true; 7424 } 7425 Args.push_back(V); 7426 } 7427 7428 Lex.Lex(); // Lex the ']'. 7429 return false; 7430 } 7431 7432 /// parseCleanupRet 7433 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue) 7434 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) { 7435 Value *CleanupPad = nullptr; 7436 7437 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret")) 7438 return true; 7439 7440 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS)) 7441 return true; 7442 7443 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret")) 7444 return true; 7445 7446 BasicBlock *UnwindBB = nullptr; 7447 if (Lex.getKind() == lltok::kw_to) { 7448 Lex.Lex(); 7449 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret")) 7450 return true; 7451 } else { 7452 if (parseTypeAndBasicBlock(UnwindBB, PFS)) { 7453 return true; 7454 } 7455 } 7456 7457 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB); 7458 return false; 7459 } 7460 7461 /// parseCatchRet 7462 /// ::= 'catchret' from Parent Value 'to' TypeAndValue 7463 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) { 7464 Value *CatchPad = nullptr; 7465 7466 if (parseToken(lltok::kw_from, "expected 'from' after catchret")) 7467 return true; 7468 7469 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS)) 7470 return true; 7471 7472 BasicBlock *BB; 7473 if (parseToken(lltok::kw_to, "expected 'to' in catchret") || 7474 parseTypeAndBasicBlock(BB, PFS)) 7475 return true; 7476 7477 Inst = CatchReturnInst::Create(CatchPad, BB); 7478 return false; 7479 } 7480 7481 /// parseCatchSwitch 7482 /// ::= 'catchswitch' within Parent 7483 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) { 7484 Value *ParentPad; 7485 7486 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch")) 7487 return true; 7488 7489 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 7490 Lex.getKind() != lltok::LocalVarID) 7491 return tokError("expected scope value for catchswitch"); 7492 7493 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 7494 return true; 7495 7496 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels")) 7497 return true; 7498 7499 SmallVector<BasicBlock *, 32> Table; 7500 do { 7501 BasicBlock *DestBB; 7502 if (parseTypeAndBasicBlock(DestBB, PFS)) 7503 return true; 7504 Table.push_back(DestBB); 7505 } while (EatIfPresent(lltok::comma)); 7506 7507 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels")) 7508 return true; 7509 7510 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope")) 7511 return true; 7512 7513 BasicBlock *UnwindBB = nullptr; 7514 if (EatIfPresent(lltok::kw_to)) { 7515 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch")) 7516 return true; 7517 } else { 7518 if (parseTypeAndBasicBlock(UnwindBB, PFS)) 7519 return true; 7520 } 7521 7522 auto *CatchSwitch = 7523 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size()); 7524 for (BasicBlock *DestBB : Table) 7525 CatchSwitch->addHandler(DestBB); 7526 Inst = CatchSwitch; 7527 return false; 7528 } 7529 7530 /// parseCatchPad 7531 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue 7532 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) { 7533 Value *CatchSwitch = nullptr; 7534 7535 if (parseToken(lltok::kw_within, "expected 'within' after catchpad")) 7536 return true; 7537 7538 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID) 7539 return tokError("expected scope value for catchpad"); 7540 7541 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS)) 7542 return true; 7543 7544 SmallVector<Value *, 8> Args; 7545 if (parseExceptionArgs(Args, PFS)) 7546 return true; 7547 7548 Inst = CatchPadInst::Create(CatchSwitch, Args); 7549 return false; 7550 } 7551 7552 /// parseCleanupPad 7553 /// ::= 'cleanuppad' within Parent ParamList 7554 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) { 7555 Value *ParentPad = nullptr; 7556 7557 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad")) 7558 return true; 7559 7560 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar && 7561 Lex.getKind() != lltok::LocalVarID) 7562 return tokError("expected scope value for cleanuppad"); 7563 7564 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS)) 7565 return true; 7566 7567 SmallVector<Value *, 8> Args; 7568 if (parseExceptionArgs(Args, PFS)) 7569 return true; 7570 7571 Inst = CleanupPadInst::Create(ParentPad, Args); 7572 return false; 7573 } 7574 7575 //===----------------------------------------------------------------------===// 7576 // Unary Operators. 7577 //===----------------------------------------------------------------------===// 7578 7579 /// parseUnaryOp 7580 /// ::= UnaryOp TypeAndValue ',' Value 7581 /// 7582 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 7583 /// operand is allowed. 7584 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, 7585 unsigned Opc, bool IsFP) { 7586 LocTy Loc; Value *LHS; 7587 if (parseTypeAndValue(LHS, Loc, PFS)) 7588 return true; 7589 7590 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 7591 : LHS->getType()->isIntOrIntVectorTy(); 7592 7593 if (!Valid) 7594 return error(Loc, "invalid operand type for instruction"); 7595 7596 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 7597 return false; 7598 } 7599 7600 /// parseCallBr 7601 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList 7602 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue 7603 /// '[' LabelList ']' 7604 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) { 7605 LocTy CallLoc = Lex.getLoc(); 7606 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 7607 std::vector<unsigned> FwdRefAttrGrps; 7608 LocTy NoBuiltinLoc; 7609 unsigned CC; 7610 Type *RetType = nullptr; 7611 LocTy RetTypeLoc; 7612 ValID CalleeID; 7613 SmallVector<ParamInfo, 16> ArgList; 7614 SmallVector<OperandBundleDef, 2> BundleList; 7615 7616 BasicBlock *DefaultDest; 7617 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 7618 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 7619 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) || 7620 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, 7621 NoBuiltinLoc) || 7622 parseOptionalOperandBundles(BundleList, PFS) || 7623 parseToken(lltok::kw_to, "expected 'to' in callbr") || 7624 parseTypeAndBasicBlock(DefaultDest, PFS) || 7625 parseToken(lltok::lsquare, "expected '[' in callbr")) 7626 return true; 7627 7628 // parse the destination list. 7629 SmallVector<BasicBlock *, 16> IndirectDests; 7630 7631 if (Lex.getKind() != lltok::rsquare) { 7632 BasicBlock *DestBB; 7633 if (parseTypeAndBasicBlock(DestBB, PFS)) 7634 return true; 7635 IndirectDests.push_back(DestBB); 7636 7637 while (EatIfPresent(lltok::comma)) { 7638 if (parseTypeAndBasicBlock(DestBB, PFS)) 7639 return true; 7640 IndirectDests.push_back(DestBB); 7641 } 7642 } 7643 7644 if (parseToken(lltok::rsquare, "expected ']' at end of block list")) 7645 return true; 7646 7647 // If RetType is a non-function pointer type, then this is the short syntax 7648 // for the call, which means that RetType is just the return type. Infer the 7649 // rest of the function argument types from the arguments that are present. 7650 FunctionType *Ty; 7651 if (resolveFunctionType(RetType, ArgList, Ty)) 7652 return error(RetTypeLoc, "Invalid result type for LLVM function"); 7653 7654 CalleeID.FTy = Ty; 7655 7656 // Look up the callee. 7657 Value *Callee; 7658 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS)) 7659 return true; 7660 7661 // Set up the Attribute for the function. 7662 SmallVector<Value *, 8> Args; 7663 SmallVector<AttributeSet, 8> ArgAttrs; 7664 7665 // Loop through FunctionType's arguments and ensure they are specified 7666 // correctly. Also, gather any parameter attributes. 7667 FunctionType::param_iterator I = Ty->param_begin(); 7668 FunctionType::param_iterator E = Ty->param_end(); 7669 for (const ParamInfo &Arg : ArgList) { 7670 Type *ExpectedTy = nullptr; 7671 if (I != E) { 7672 ExpectedTy = *I++; 7673 } else if (!Ty->isVarArg()) { 7674 return error(Arg.Loc, "too many arguments specified"); 7675 } 7676 7677 if (ExpectedTy && ExpectedTy != Arg.V->getType()) 7678 return error(Arg.Loc, "argument is not of expected type '" + 7679 getTypeString(ExpectedTy) + "'"); 7680 Args.push_back(Arg.V); 7681 ArgAttrs.push_back(Arg.Attrs); 7682 } 7683 7684 if (I != E) 7685 return error(CallLoc, "not enough parameters specified for call"); 7686 7687 // Finish off the Attribute and check them 7688 AttributeList PAL = 7689 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 7690 AttributeSet::get(Context, RetAttrs), ArgAttrs); 7691 7692 CallBrInst *CBI = 7693 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args, 7694 BundleList); 7695 CBI->setCallingConv(CC); 7696 CBI->setAttributes(PAL); 7697 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps; 7698 Inst = CBI; 7699 return false; 7700 } 7701 7702 //===----------------------------------------------------------------------===// 7703 // Binary Operators. 7704 //===----------------------------------------------------------------------===// 7705 7706 /// parseArithmetic 7707 /// ::= ArithmeticOps TypeAndValue ',' Value 7708 /// 7709 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp 7710 /// operand is allowed. 7711 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS, 7712 unsigned Opc, bool IsFP) { 7713 LocTy Loc; Value *LHS, *RHS; 7714 if (parseTypeAndValue(LHS, Loc, PFS) || 7715 parseToken(lltok::comma, "expected ',' in arithmetic operation") || 7716 parseValue(LHS->getType(), RHS, PFS)) 7717 return true; 7718 7719 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy() 7720 : LHS->getType()->isIntOrIntVectorTy(); 7721 7722 if (!Valid) 7723 return error(Loc, "invalid operand type for instruction"); 7724 7725 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 7726 return false; 7727 } 7728 7729 /// parseLogical 7730 /// ::= ArithmeticOps TypeAndValue ',' Value { 7731 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS, 7732 unsigned Opc) { 7733 LocTy Loc; Value *LHS, *RHS; 7734 if (parseTypeAndValue(LHS, Loc, PFS) || 7735 parseToken(lltok::comma, "expected ',' in logical operation") || 7736 parseValue(LHS->getType(), RHS, PFS)) 7737 return true; 7738 7739 if (!LHS->getType()->isIntOrIntVectorTy()) 7740 return error(Loc, 7741 "instruction requires integer or integer vector operands"); 7742 7743 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 7744 return false; 7745 } 7746 7747 /// parseCompare 7748 /// ::= 'icmp' IPredicates TypeAndValue ',' Value 7749 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value 7750 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS, 7751 unsigned Opc) { 7752 // parse the integer/fp comparison predicate. 7753 LocTy Loc; 7754 unsigned Pred; 7755 Value *LHS, *RHS; 7756 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) || 7757 parseToken(lltok::comma, "expected ',' after compare value") || 7758 parseValue(LHS->getType(), RHS, PFS)) 7759 return true; 7760 7761 if (Opc == Instruction::FCmp) { 7762 if (!LHS->getType()->isFPOrFPVectorTy()) 7763 return error(Loc, "fcmp requires floating point operands"); 7764 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS); 7765 } else { 7766 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!"); 7767 if (!LHS->getType()->isIntOrIntVectorTy() && 7768 !LHS->getType()->isPtrOrPtrVectorTy()) 7769 return error(Loc, "icmp requires integer operands"); 7770 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS); 7771 } 7772 return false; 7773 } 7774 7775 //===----------------------------------------------------------------------===// 7776 // Other Instructions. 7777 //===----------------------------------------------------------------------===// 7778 7779 /// parseCast 7780 /// ::= CastOpc TypeAndValue 'to' Type 7781 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS, 7782 unsigned Opc) { 7783 LocTy Loc; 7784 Value *Op; 7785 Type *DestTy = nullptr; 7786 if (parseTypeAndValue(Op, Loc, PFS) || 7787 parseToken(lltok::kw_to, "expected 'to' after cast value") || 7788 parseType(DestTy)) 7789 return true; 7790 7791 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) { 7792 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy); 7793 return error(Loc, "invalid cast opcode for cast from '" + 7794 getTypeString(Op->getType()) + "' to '" + 7795 getTypeString(DestTy) + "'"); 7796 } 7797 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy); 7798 return false; 7799 } 7800 7801 /// parseSelect 7802 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7803 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) { 7804 LocTy Loc; 7805 Value *Op0, *Op1, *Op2; 7806 if (parseTypeAndValue(Op0, Loc, PFS) || 7807 parseToken(lltok::comma, "expected ',' after select condition") || 7808 parseTypeAndValue(Op1, PFS) || 7809 parseToken(lltok::comma, "expected ',' after select value") || 7810 parseTypeAndValue(Op2, PFS)) 7811 return true; 7812 7813 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2)) 7814 return error(Loc, Reason); 7815 7816 Inst = SelectInst::Create(Op0, Op1, Op2); 7817 return false; 7818 } 7819 7820 /// parseVAArg 7821 /// ::= 'va_arg' TypeAndValue ',' Type 7822 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) { 7823 Value *Op; 7824 Type *EltTy = nullptr; 7825 LocTy TypeLoc; 7826 if (parseTypeAndValue(Op, PFS) || 7827 parseToken(lltok::comma, "expected ',' after vaarg operand") || 7828 parseType(EltTy, TypeLoc)) 7829 return true; 7830 7831 if (!EltTy->isFirstClassType()) 7832 return error(TypeLoc, "va_arg requires operand with first class type"); 7833 7834 Inst = new VAArgInst(Op, EltTy); 7835 return false; 7836 } 7837 7838 /// parseExtractElement 7839 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue 7840 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) { 7841 LocTy Loc; 7842 Value *Op0, *Op1; 7843 if (parseTypeAndValue(Op0, Loc, PFS) || 7844 parseToken(lltok::comma, "expected ',' after extract value") || 7845 parseTypeAndValue(Op1, PFS)) 7846 return true; 7847 7848 if (!ExtractElementInst::isValidOperands(Op0, Op1)) 7849 return error(Loc, "invalid extractelement operands"); 7850 7851 Inst = ExtractElementInst::Create(Op0, Op1); 7852 return false; 7853 } 7854 7855 /// parseInsertElement 7856 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7857 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) { 7858 LocTy Loc; 7859 Value *Op0, *Op1, *Op2; 7860 if (parseTypeAndValue(Op0, Loc, PFS) || 7861 parseToken(lltok::comma, "expected ',' after insertelement value") || 7862 parseTypeAndValue(Op1, PFS) || 7863 parseToken(lltok::comma, "expected ',' after insertelement value") || 7864 parseTypeAndValue(Op2, PFS)) 7865 return true; 7866 7867 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2)) 7868 return error(Loc, "invalid insertelement operands"); 7869 7870 Inst = InsertElementInst::Create(Op0, Op1, Op2); 7871 return false; 7872 } 7873 7874 /// parseShuffleVector 7875 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue 7876 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) { 7877 LocTy Loc; 7878 Value *Op0, *Op1, *Op2; 7879 if (parseTypeAndValue(Op0, Loc, PFS) || 7880 parseToken(lltok::comma, "expected ',' after shuffle mask") || 7881 parseTypeAndValue(Op1, PFS) || 7882 parseToken(lltok::comma, "expected ',' after shuffle value") || 7883 parseTypeAndValue(Op2, PFS)) 7884 return true; 7885 7886 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2)) 7887 return error(Loc, "invalid shufflevector operands"); 7888 7889 Inst = new ShuffleVectorInst(Op0, Op1, Op2); 7890 return false; 7891 } 7892 7893 /// parsePHI 7894 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')* 7895 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) { 7896 Type *Ty = nullptr; LocTy TypeLoc; 7897 Value *Op0, *Op1; 7898 7899 if (parseType(Ty, TypeLoc)) 7900 return true; 7901 7902 if (!Ty->isFirstClassType()) 7903 return error(TypeLoc, "phi node must have first class type"); 7904 7905 bool First = true; 7906 bool AteExtraComma = false; 7907 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals; 7908 7909 while (true) { 7910 if (First) { 7911 if (Lex.getKind() != lltok::lsquare) 7912 break; 7913 First = false; 7914 } else if (!EatIfPresent(lltok::comma)) 7915 break; 7916 7917 if (Lex.getKind() == lltok::MetadataVar) { 7918 AteExtraComma = true; 7919 break; 7920 } 7921 7922 if (parseToken(lltok::lsquare, "expected '[' in phi value list") || 7923 parseValue(Ty, Op0, PFS) || 7924 parseToken(lltok::comma, "expected ',' after insertelement value") || 7925 parseValue(Type::getLabelTy(Context), Op1, PFS) || 7926 parseToken(lltok::rsquare, "expected ']' in phi value list")) 7927 return true; 7928 7929 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1))); 7930 } 7931 7932 PHINode *PN = PHINode::Create(Ty, PHIVals.size()); 7933 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i) 7934 PN->addIncoming(PHIVals[i].first, PHIVals[i].second); 7935 Inst = PN; 7936 return AteExtraComma ? InstExtraComma : InstNormal; 7937 } 7938 7939 /// parseLandingPad 7940 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+ 7941 /// Clause 7942 /// ::= 'catch' TypeAndValue 7943 /// ::= 'filter' 7944 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )* 7945 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) { 7946 Type *Ty = nullptr; LocTy TyLoc; 7947 7948 if (parseType(Ty, TyLoc)) 7949 return true; 7950 7951 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0)); 7952 LP->setCleanup(EatIfPresent(lltok::kw_cleanup)); 7953 7954 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){ 7955 LandingPadInst::ClauseType CT; 7956 if (EatIfPresent(lltok::kw_catch)) 7957 CT = LandingPadInst::Catch; 7958 else if (EatIfPresent(lltok::kw_filter)) 7959 CT = LandingPadInst::Filter; 7960 else 7961 return tokError("expected 'catch' or 'filter' clause type"); 7962 7963 Value *V; 7964 LocTy VLoc; 7965 if (parseTypeAndValue(V, VLoc, PFS)) 7966 return true; 7967 7968 // A 'catch' type expects a non-array constant. A filter clause expects an 7969 // array constant. 7970 if (CT == LandingPadInst::Catch) { 7971 if (isa<ArrayType>(V->getType())) 7972 return error(VLoc, "'catch' clause has an invalid type"); 7973 } else { 7974 if (!isa<ArrayType>(V->getType())) 7975 return error(VLoc, "'filter' clause has an invalid type"); 7976 } 7977 7978 Constant *CV = dyn_cast<Constant>(V); 7979 if (!CV) 7980 return error(VLoc, "clause argument must be a constant"); 7981 LP->addClause(CV); 7982 } 7983 7984 Inst = LP.release(); 7985 return false; 7986 } 7987 7988 /// parseFreeze 7989 /// ::= 'freeze' Type Value 7990 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) { 7991 LocTy Loc; 7992 Value *Op; 7993 if (parseTypeAndValue(Op, Loc, PFS)) 7994 return true; 7995 7996 Inst = new FreezeInst(Op); 7997 return false; 7998 } 7999 8000 /// parseCall 8001 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv 8002 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8003 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv 8004 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8005 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv 8006 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8007 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv 8008 /// OptionalAttrs Type Value ParameterList OptionalAttrs 8009 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS, 8010 CallInst::TailCallKind TCK) { 8011 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext()); 8012 std::vector<unsigned> FwdRefAttrGrps; 8013 LocTy BuiltinLoc; 8014 unsigned CallAddrSpace; 8015 unsigned CC; 8016 Type *RetType = nullptr; 8017 LocTy RetTypeLoc; 8018 ValID CalleeID; 8019 SmallVector<ParamInfo, 16> ArgList; 8020 SmallVector<OperandBundleDef, 2> BundleList; 8021 LocTy CallLoc = Lex.getLoc(); 8022 8023 if (TCK != CallInst::TCK_None && 8024 parseToken(lltok::kw_call, 8025 "expected 'tail call', 'musttail call', or 'notail call'")) 8026 return true; 8027 8028 FastMathFlags FMF = EatFastMathFlagsIfPresent(); 8029 8030 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) || 8031 parseOptionalProgramAddrSpace(CallAddrSpace) || 8032 parseType(RetType, RetTypeLoc, true /*void allowed*/) || 8033 parseValID(CalleeID, &PFS) || 8034 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail, 8035 PFS.getFunction().isVarArg()) || 8036 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) || 8037 parseOptionalOperandBundles(BundleList, PFS)) 8038 return true; 8039 8040 // If RetType is a non-function pointer type, then this is the short syntax 8041 // for the call, which means that RetType is just the return type. Infer the 8042 // rest of the function argument types from the arguments that are present. 8043 FunctionType *Ty; 8044 if (resolveFunctionType(RetType, ArgList, Ty)) 8045 return error(RetTypeLoc, "Invalid result type for LLVM function"); 8046 8047 CalleeID.FTy = Ty; 8048 8049 // Look up the callee. 8050 Value *Callee; 8051 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee, 8052 &PFS)) 8053 return true; 8054 8055 // Set up the Attribute for the function. 8056 SmallVector<AttributeSet, 8> Attrs; 8057 8058 SmallVector<Value*, 8> Args; 8059 8060 // Loop through FunctionType's arguments and ensure they are specified 8061 // correctly. Also, gather any parameter attributes. 8062 FunctionType::param_iterator I = Ty->param_begin(); 8063 FunctionType::param_iterator E = Ty->param_end(); 8064 for (const ParamInfo &Arg : ArgList) { 8065 Type *ExpectedTy = nullptr; 8066 if (I != E) { 8067 ExpectedTy = *I++; 8068 } else if (!Ty->isVarArg()) { 8069 return error(Arg.Loc, "too many arguments specified"); 8070 } 8071 8072 if (ExpectedTy && ExpectedTy != Arg.V->getType()) 8073 return error(Arg.Loc, "argument is not of expected type '" + 8074 getTypeString(ExpectedTy) + "'"); 8075 Args.push_back(Arg.V); 8076 Attrs.push_back(Arg.Attrs); 8077 } 8078 8079 if (I != E) 8080 return error(CallLoc, "not enough parameters specified for call"); 8081 8082 // Finish off the Attribute and check them 8083 AttributeList PAL = 8084 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs), 8085 AttributeSet::get(Context, RetAttrs), Attrs); 8086 8087 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList); 8088 CI->setTailCallKind(TCK); 8089 CI->setCallingConv(CC); 8090 if (FMF.any()) { 8091 if (!isa<FPMathOperator>(CI)) { 8092 CI->deleteValue(); 8093 return error(CallLoc, "fast-math-flags specified for call without " 8094 "floating-point scalar or vector return type"); 8095 } 8096 CI->setFastMathFlags(FMF); 8097 } 8098 8099 if (CalleeID.Kind == ValID::t_GlobalName && 8100 isOldDbgFormatIntrinsic(CalleeID.StrVal)) { 8101 if (SeenNewDbgInfoFormat) { 8102 CI->deleteValue(); 8103 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module " 8104 "using non-intrinsic debug info"); 8105 } 8106 if (!SeenOldDbgInfoFormat) 8107 M->setNewDbgInfoFormatFlag(false); 8108 SeenOldDbgInfoFormat = true; 8109 } 8110 CI->setAttributes(PAL); 8111 ForwardRefAttrGroups[CI] = FwdRefAttrGrps; 8112 Inst = CI; 8113 return false; 8114 } 8115 8116 //===----------------------------------------------------------------------===// 8117 // Memory Instructions. 8118 //===----------------------------------------------------------------------===// 8119 8120 /// parseAlloc 8121 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)? 8122 /// (',' 'align' i32)? (',', 'addrspace(n))? 8123 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) { 8124 Value *Size = nullptr; 8125 LocTy SizeLoc, TyLoc, ASLoc; 8126 MaybeAlign Alignment; 8127 unsigned AddrSpace = 0; 8128 Type *Ty = nullptr; 8129 8130 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca); 8131 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror); 8132 8133 if (parseType(Ty, TyLoc)) 8134 return true; 8135 8136 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty)) 8137 return error(TyLoc, "invalid type for alloca"); 8138 8139 bool AteExtraComma = false; 8140 if (EatIfPresent(lltok::comma)) { 8141 if (Lex.getKind() == lltok::kw_align) { 8142 if (parseOptionalAlignment(Alignment)) 8143 return true; 8144 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 8145 return true; 8146 } else if (Lex.getKind() == lltok::kw_addrspace) { 8147 ASLoc = Lex.getLoc(); 8148 if (parseOptionalAddrSpace(AddrSpace)) 8149 return true; 8150 } else if (Lex.getKind() == lltok::MetadataVar) { 8151 AteExtraComma = true; 8152 } else { 8153 if (parseTypeAndValue(Size, SizeLoc, PFS)) 8154 return true; 8155 if (EatIfPresent(lltok::comma)) { 8156 if (Lex.getKind() == lltok::kw_align) { 8157 if (parseOptionalAlignment(Alignment)) 8158 return true; 8159 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma)) 8160 return true; 8161 } else if (Lex.getKind() == lltok::kw_addrspace) { 8162 ASLoc = Lex.getLoc(); 8163 if (parseOptionalAddrSpace(AddrSpace)) 8164 return true; 8165 } else if (Lex.getKind() == lltok::MetadataVar) { 8166 AteExtraComma = true; 8167 } 8168 } 8169 } 8170 } 8171 8172 if (Size && !Size->getType()->isIntegerTy()) 8173 return error(SizeLoc, "element count must have integer type"); 8174 8175 SmallPtrSet<Type *, 4> Visited; 8176 if (!Alignment && !Ty->isSized(&Visited)) 8177 return error(TyLoc, "Cannot allocate unsized type"); 8178 if (!Alignment) 8179 Alignment = M->getDataLayout().getPrefTypeAlign(Ty); 8180 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment); 8181 AI->setUsedWithInAlloca(IsInAlloca); 8182 AI->setSwiftError(IsSwiftError); 8183 Inst = AI; 8184 return AteExtraComma ? InstExtraComma : InstNormal; 8185 } 8186 8187 /// parseLoad 8188 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)? 8189 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue 8190 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 8191 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) { 8192 Value *Val; LocTy Loc; 8193 MaybeAlign Alignment; 8194 bool AteExtraComma = false; 8195 bool isAtomic = false; 8196 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8197 SyncScope::ID SSID = SyncScope::System; 8198 8199 if (Lex.getKind() == lltok::kw_atomic) { 8200 isAtomic = true; 8201 Lex.Lex(); 8202 } 8203 8204 bool isVolatile = false; 8205 if (Lex.getKind() == lltok::kw_volatile) { 8206 isVolatile = true; 8207 Lex.Lex(); 8208 } 8209 8210 Type *Ty; 8211 LocTy ExplicitTypeLoc = Lex.getLoc(); 8212 if (parseType(Ty) || 8213 parseToken(lltok::comma, "expected comma after load's type") || 8214 parseTypeAndValue(Val, Loc, PFS) || 8215 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 8216 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8217 return true; 8218 8219 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType()) 8220 return error(Loc, "load operand must be a pointer to a first class type"); 8221 if (isAtomic && !Alignment) 8222 return error(Loc, "atomic load must have explicit non-zero alignment"); 8223 if (Ordering == AtomicOrdering::Release || 8224 Ordering == AtomicOrdering::AcquireRelease) 8225 return error(Loc, "atomic load cannot use Release ordering"); 8226 8227 SmallPtrSet<Type *, 4> Visited; 8228 if (!Alignment && !Ty->isSized(&Visited)) 8229 return error(ExplicitTypeLoc, "loading unsized types is not allowed"); 8230 if (!Alignment) 8231 Alignment = M->getDataLayout().getABITypeAlign(Ty); 8232 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID); 8233 return AteExtraComma ? InstExtraComma : InstNormal; 8234 } 8235 8236 /// parseStore 8237 8238 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)? 8239 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue 8240 /// 'singlethread'? AtomicOrdering (',' 'align' i32)? 8241 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) { 8242 Value *Val, *Ptr; LocTy Loc, PtrLoc; 8243 MaybeAlign Alignment; 8244 bool AteExtraComma = false; 8245 bool isAtomic = false; 8246 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8247 SyncScope::ID SSID = SyncScope::System; 8248 8249 if (Lex.getKind() == lltok::kw_atomic) { 8250 isAtomic = true; 8251 Lex.Lex(); 8252 } 8253 8254 bool isVolatile = false; 8255 if (Lex.getKind() == lltok::kw_volatile) { 8256 isVolatile = true; 8257 Lex.Lex(); 8258 } 8259 8260 if (parseTypeAndValue(Val, Loc, PFS) || 8261 parseToken(lltok::comma, "expected ',' after store operand") || 8262 parseTypeAndValue(Ptr, PtrLoc, PFS) || 8263 parseScopeAndOrdering(isAtomic, SSID, Ordering) || 8264 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8265 return true; 8266 8267 if (!Ptr->getType()->isPointerTy()) 8268 return error(PtrLoc, "store operand must be a pointer"); 8269 if (!Val->getType()->isFirstClassType()) 8270 return error(Loc, "store operand must be a first class value"); 8271 if (isAtomic && !Alignment) 8272 return error(Loc, "atomic store must have explicit non-zero alignment"); 8273 if (Ordering == AtomicOrdering::Acquire || 8274 Ordering == AtomicOrdering::AcquireRelease) 8275 return error(Loc, "atomic store cannot use Acquire ordering"); 8276 SmallPtrSet<Type *, 4> Visited; 8277 if (!Alignment && !Val->getType()->isSized(&Visited)) 8278 return error(Loc, "storing unsized types is not allowed"); 8279 if (!Alignment) 8280 Alignment = M->getDataLayout().getABITypeAlign(Val->getType()); 8281 8282 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID); 8283 return AteExtraComma ? InstExtraComma : InstNormal; 8284 } 8285 8286 /// parseCmpXchg 8287 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ',' 8288 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ',' 8289 /// 'Align'? 8290 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) { 8291 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc; 8292 bool AteExtraComma = false; 8293 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic; 8294 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic; 8295 SyncScope::ID SSID = SyncScope::System; 8296 bool isVolatile = false; 8297 bool isWeak = false; 8298 MaybeAlign Alignment; 8299 8300 if (EatIfPresent(lltok::kw_weak)) 8301 isWeak = true; 8302 8303 if (EatIfPresent(lltok::kw_volatile)) 8304 isVolatile = true; 8305 8306 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 8307 parseToken(lltok::comma, "expected ',' after cmpxchg address") || 8308 parseTypeAndValue(Cmp, CmpLoc, PFS) || 8309 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") || 8310 parseTypeAndValue(New, NewLoc, PFS) || 8311 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) || 8312 parseOrdering(FailureOrdering) || 8313 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8314 return true; 8315 8316 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 8317 return tokError("invalid cmpxchg success ordering"); 8318 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 8319 return tokError("invalid cmpxchg failure ordering"); 8320 if (!Ptr->getType()->isPointerTy()) 8321 return error(PtrLoc, "cmpxchg operand must be a pointer"); 8322 if (Cmp->getType() != New->getType()) 8323 return error(NewLoc, "compare value and new value type do not match"); 8324 if (!New->getType()->isFirstClassType()) 8325 return error(NewLoc, "cmpxchg operand must be a first class value"); 8326 8327 const Align DefaultAlignment( 8328 PFS.getFunction().getDataLayout().getTypeStoreSize( 8329 Cmp->getType())); 8330 8331 AtomicCmpXchgInst *CXI = 8332 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment), 8333 SuccessOrdering, FailureOrdering, SSID); 8334 CXI->setVolatile(isVolatile); 8335 CXI->setWeak(isWeak); 8336 8337 Inst = CXI; 8338 return AteExtraComma ? InstExtraComma : InstNormal; 8339 } 8340 8341 /// parseAtomicRMW 8342 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue 8343 /// 'singlethread'? AtomicOrdering 8344 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) { 8345 Value *Ptr, *Val; LocTy PtrLoc, ValLoc; 8346 bool AteExtraComma = false; 8347 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8348 SyncScope::ID SSID = SyncScope::System; 8349 bool isVolatile = false; 8350 bool IsFP = false; 8351 AtomicRMWInst::BinOp Operation; 8352 MaybeAlign Alignment; 8353 8354 if (EatIfPresent(lltok::kw_volatile)) 8355 isVolatile = true; 8356 8357 switch (Lex.getKind()) { 8358 default: 8359 return tokError("expected binary operation in atomicrmw"); 8360 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break; 8361 case lltok::kw_add: Operation = AtomicRMWInst::Add; break; 8362 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break; 8363 case lltok::kw_and: Operation = AtomicRMWInst::And; break; 8364 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break; 8365 case lltok::kw_or: Operation = AtomicRMWInst::Or; break; 8366 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break; 8367 case lltok::kw_max: Operation = AtomicRMWInst::Max; break; 8368 case lltok::kw_min: Operation = AtomicRMWInst::Min; break; 8369 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break; 8370 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break; 8371 case lltok::kw_uinc_wrap: 8372 Operation = AtomicRMWInst::UIncWrap; 8373 break; 8374 case lltok::kw_udec_wrap: 8375 Operation = AtomicRMWInst::UDecWrap; 8376 break; 8377 case lltok::kw_usub_cond: 8378 Operation = AtomicRMWInst::USubCond; 8379 break; 8380 case lltok::kw_usub_sat: 8381 Operation = AtomicRMWInst::USubSat; 8382 break; 8383 case lltok::kw_fadd: 8384 Operation = AtomicRMWInst::FAdd; 8385 IsFP = true; 8386 break; 8387 case lltok::kw_fsub: 8388 Operation = AtomicRMWInst::FSub; 8389 IsFP = true; 8390 break; 8391 case lltok::kw_fmax: 8392 Operation = AtomicRMWInst::FMax; 8393 IsFP = true; 8394 break; 8395 case lltok::kw_fmin: 8396 Operation = AtomicRMWInst::FMin; 8397 IsFP = true; 8398 break; 8399 } 8400 Lex.Lex(); // Eat the operation. 8401 8402 if (parseTypeAndValue(Ptr, PtrLoc, PFS) || 8403 parseToken(lltok::comma, "expected ',' after atomicrmw address") || 8404 parseTypeAndValue(Val, ValLoc, PFS) || 8405 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) || 8406 parseOptionalCommaAlign(Alignment, AteExtraComma)) 8407 return true; 8408 8409 if (Ordering == AtomicOrdering::Unordered) 8410 return tokError("atomicrmw cannot be unordered"); 8411 if (!Ptr->getType()->isPointerTy()) 8412 return error(PtrLoc, "atomicrmw operand must be a pointer"); 8413 if (Val->getType()->isScalableTy()) 8414 return error(ValLoc, "atomicrmw operand may not be scalable"); 8415 8416 if (Operation == AtomicRMWInst::Xchg) { 8417 if (!Val->getType()->isIntegerTy() && 8418 !Val->getType()->isFloatingPointTy() && 8419 !Val->getType()->isPointerTy()) { 8420 return error( 8421 ValLoc, 8422 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) + 8423 " operand must be an integer, floating point, or pointer type"); 8424 } 8425 } else if (IsFP) { 8426 if (!Val->getType()->isFPOrFPVectorTy()) { 8427 return error(ValLoc, "atomicrmw " + 8428 AtomicRMWInst::getOperationName(Operation) + 8429 " operand must be a floating point type"); 8430 } 8431 } else { 8432 if (!Val->getType()->isIntegerTy()) { 8433 return error(ValLoc, "atomicrmw " + 8434 AtomicRMWInst::getOperationName(Operation) + 8435 " operand must be an integer"); 8436 } 8437 } 8438 8439 unsigned Size = 8440 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits( 8441 Val->getType()); 8442 if (Size < 8 || (Size & (Size - 1))) 8443 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized" 8444 " integer"); 8445 const Align DefaultAlignment( 8446 PFS.getFunction().getDataLayout().getTypeStoreSize( 8447 Val->getType())); 8448 AtomicRMWInst *RMWI = 8449 new AtomicRMWInst(Operation, Ptr, Val, 8450 Alignment.value_or(DefaultAlignment), Ordering, SSID); 8451 RMWI->setVolatile(isVolatile); 8452 Inst = RMWI; 8453 return AteExtraComma ? InstExtraComma : InstNormal; 8454 } 8455 8456 /// parseFence 8457 /// ::= 'fence' 'singlethread'? AtomicOrdering 8458 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) { 8459 AtomicOrdering Ordering = AtomicOrdering::NotAtomic; 8460 SyncScope::ID SSID = SyncScope::System; 8461 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering)) 8462 return true; 8463 8464 if (Ordering == AtomicOrdering::Unordered) 8465 return tokError("fence cannot be unordered"); 8466 if (Ordering == AtomicOrdering::Monotonic) 8467 return tokError("fence cannot be monotonic"); 8468 8469 Inst = new FenceInst(Context, Ordering, SSID); 8470 return InstNormal; 8471 } 8472 8473 /// parseGetElementPtr 8474 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)* 8475 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) { 8476 Value *Ptr = nullptr; 8477 Value *Val = nullptr; 8478 LocTy Loc, EltLoc; 8479 GEPNoWrapFlags NW; 8480 8481 while (true) { 8482 if (EatIfPresent(lltok::kw_inbounds)) 8483 NW |= GEPNoWrapFlags::inBounds(); 8484 else if (EatIfPresent(lltok::kw_nusw)) 8485 NW |= GEPNoWrapFlags::noUnsignedSignedWrap(); 8486 else if (EatIfPresent(lltok::kw_nuw)) 8487 NW |= GEPNoWrapFlags::noUnsignedWrap(); 8488 else 8489 break; 8490 } 8491 8492 Type *Ty = nullptr; 8493 if (parseType(Ty) || 8494 parseToken(lltok::comma, "expected comma after getelementptr's type") || 8495 parseTypeAndValue(Ptr, Loc, PFS)) 8496 return true; 8497 8498 Type *BaseType = Ptr->getType(); 8499 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType()); 8500 if (!BasePointerType) 8501 return error(Loc, "base of getelementptr must be a pointer"); 8502 8503 SmallVector<Value*, 16> Indices; 8504 bool AteExtraComma = false; 8505 // GEP returns a vector of pointers if at least one of parameters is a vector. 8506 // All vector parameters should have the same vector width. 8507 ElementCount GEPWidth = BaseType->isVectorTy() 8508 ? cast<VectorType>(BaseType)->getElementCount() 8509 : ElementCount::getFixed(0); 8510 8511 while (EatIfPresent(lltok::comma)) { 8512 if (Lex.getKind() == lltok::MetadataVar) { 8513 AteExtraComma = true; 8514 break; 8515 } 8516 if (parseTypeAndValue(Val, EltLoc, PFS)) 8517 return true; 8518 if (!Val->getType()->isIntOrIntVectorTy()) 8519 return error(EltLoc, "getelementptr index must be an integer"); 8520 8521 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) { 8522 ElementCount ValNumEl = ValVTy->getElementCount(); 8523 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl) 8524 return error( 8525 EltLoc, 8526 "getelementptr vector index has a wrong number of elements"); 8527 GEPWidth = ValNumEl; 8528 } 8529 Indices.push_back(Val); 8530 } 8531 8532 SmallPtrSet<Type*, 4> Visited; 8533 if (!Indices.empty() && !Ty->isSized(&Visited)) 8534 return error(Loc, "base element of getelementptr must be sized"); 8535 8536 auto *STy = dyn_cast<StructType>(Ty); 8537 if (STy && STy->isScalableTy()) 8538 return error(Loc, "getelementptr cannot target structure that contains " 8539 "scalable vector type"); 8540 8541 if (!GetElementPtrInst::getIndexedType(Ty, Indices)) 8542 return error(Loc, "invalid getelementptr indices"); 8543 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices); 8544 Inst = GEP; 8545 GEP->setNoWrapFlags(NW); 8546 return AteExtraComma ? InstExtraComma : InstNormal; 8547 } 8548 8549 /// parseExtractValue 8550 /// ::= 'extractvalue' TypeAndValue (',' uint32)+ 8551 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) { 8552 Value *Val; LocTy Loc; 8553 SmallVector<unsigned, 4> Indices; 8554 bool AteExtraComma; 8555 if (parseTypeAndValue(Val, Loc, PFS) || 8556 parseIndexList(Indices, AteExtraComma)) 8557 return true; 8558 8559 if (!Val->getType()->isAggregateType()) 8560 return error(Loc, "extractvalue operand must be aggregate type"); 8561 8562 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices)) 8563 return error(Loc, "invalid indices for extractvalue"); 8564 Inst = ExtractValueInst::Create(Val, Indices); 8565 return AteExtraComma ? InstExtraComma : InstNormal; 8566 } 8567 8568 /// parseInsertValue 8569 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+ 8570 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) { 8571 Value *Val0, *Val1; LocTy Loc0, Loc1; 8572 SmallVector<unsigned, 4> Indices; 8573 bool AteExtraComma; 8574 if (parseTypeAndValue(Val0, Loc0, PFS) || 8575 parseToken(lltok::comma, "expected comma after insertvalue operand") || 8576 parseTypeAndValue(Val1, Loc1, PFS) || 8577 parseIndexList(Indices, AteExtraComma)) 8578 return true; 8579 8580 if (!Val0->getType()->isAggregateType()) 8581 return error(Loc0, "insertvalue operand must be aggregate type"); 8582 8583 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices); 8584 if (!IndexedType) 8585 return error(Loc0, "invalid indices for insertvalue"); 8586 if (IndexedType != Val1->getType()) 8587 return error(Loc1, "insertvalue operand and field disagree in type: '" + 8588 getTypeString(Val1->getType()) + "' instead of '" + 8589 getTypeString(IndexedType) + "'"); 8590 Inst = InsertValueInst::Create(Val0, Val1, Indices); 8591 return AteExtraComma ? InstExtraComma : InstNormal; 8592 } 8593 8594 //===----------------------------------------------------------------------===// 8595 // Embedded metadata. 8596 //===----------------------------------------------------------------------===// 8597 8598 /// parseMDNodeVector 8599 /// ::= { Element (',' Element)* } 8600 /// Element 8601 /// ::= 'null' | Metadata 8602 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) { 8603 if (parseToken(lltok::lbrace, "expected '{' here")) 8604 return true; 8605 8606 // Check for an empty list. 8607 if (EatIfPresent(lltok::rbrace)) 8608 return false; 8609 8610 do { 8611 if (EatIfPresent(lltok::kw_null)) { 8612 Elts.push_back(nullptr); 8613 continue; 8614 } 8615 8616 Metadata *MD; 8617 if (parseMetadata(MD, nullptr)) 8618 return true; 8619 Elts.push_back(MD); 8620 } while (EatIfPresent(lltok::comma)); 8621 8622 return parseToken(lltok::rbrace, "expected end of metadata node"); 8623 } 8624 8625 //===----------------------------------------------------------------------===// 8626 // Use-list order directives. 8627 //===----------------------------------------------------------------------===// 8628 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, 8629 SMLoc Loc) { 8630 if (V->use_empty()) 8631 return error(Loc, "value has no uses"); 8632 8633 unsigned NumUses = 0; 8634 SmallDenseMap<const Use *, unsigned, 16> Order; 8635 for (const Use &U : V->uses()) { 8636 if (++NumUses > Indexes.size()) 8637 break; 8638 Order[&U] = Indexes[NumUses - 1]; 8639 } 8640 if (NumUses < 2) 8641 return error(Loc, "value only has one use"); 8642 if (Order.size() != Indexes.size() || NumUses > Indexes.size()) 8643 return error(Loc, 8644 "wrong number of indexes, expected " + Twine(V->getNumUses())); 8645 8646 V->sortUseList([&](const Use &L, const Use &R) { 8647 return Order.lookup(&L) < Order.lookup(&R); 8648 }); 8649 return false; 8650 } 8651 8652 /// parseUseListOrderIndexes 8653 /// ::= '{' uint32 (',' uint32)+ '}' 8654 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) { 8655 SMLoc Loc = Lex.getLoc(); 8656 if (parseToken(lltok::lbrace, "expected '{' here")) 8657 return true; 8658 if (Lex.getKind() == lltok::rbrace) 8659 return tokError("expected non-empty list of uselistorder indexes"); 8660 8661 // Use Offset, Max, and IsOrdered to check consistency of indexes. The 8662 // indexes should be distinct numbers in the range [0, size-1], and should 8663 // not be in order. 8664 unsigned Offset = 0; 8665 unsigned Max = 0; 8666 bool IsOrdered = true; 8667 assert(Indexes.empty() && "Expected empty order vector"); 8668 do { 8669 unsigned Index; 8670 if (parseUInt32(Index)) 8671 return true; 8672 8673 // Update consistency checks. 8674 Offset += Index - Indexes.size(); 8675 Max = std::max(Max, Index); 8676 IsOrdered &= Index == Indexes.size(); 8677 8678 Indexes.push_back(Index); 8679 } while (EatIfPresent(lltok::comma)); 8680 8681 if (parseToken(lltok::rbrace, "expected '}' here")) 8682 return true; 8683 8684 if (Indexes.size() < 2) 8685 return error(Loc, "expected >= 2 uselistorder indexes"); 8686 if (Offset != 0 || Max >= Indexes.size()) 8687 return error(Loc, 8688 "expected distinct uselistorder indexes in range [0, size)"); 8689 if (IsOrdered) 8690 return error(Loc, "expected uselistorder indexes to change the order"); 8691 8692 return false; 8693 } 8694 8695 /// parseUseListOrder 8696 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes 8697 bool LLParser::parseUseListOrder(PerFunctionState *PFS) { 8698 SMLoc Loc = Lex.getLoc(); 8699 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive")) 8700 return true; 8701 8702 Value *V; 8703 SmallVector<unsigned, 16> Indexes; 8704 if (parseTypeAndValue(V, PFS) || 8705 parseToken(lltok::comma, "expected comma in uselistorder directive") || 8706 parseUseListOrderIndexes(Indexes)) 8707 return true; 8708 8709 return sortUseListOrder(V, Indexes, Loc); 8710 } 8711 8712 /// parseUseListOrderBB 8713 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes 8714 bool LLParser::parseUseListOrderBB() { 8715 assert(Lex.getKind() == lltok::kw_uselistorder_bb); 8716 SMLoc Loc = Lex.getLoc(); 8717 Lex.Lex(); 8718 8719 ValID Fn, Label; 8720 SmallVector<unsigned, 16> Indexes; 8721 if (parseValID(Fn, /*PFS=*/nullptr) || 8722 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 8723 parseValID(Label, /*PFS=*/nullptr) || 8724 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") || 8725 parseUseListOrderIndexes(Indexes)) 8726 return true; 8727 8728 // Check the function. 8729 GlobalValue *GV; 8730 if (Fn.Kind == ValID::t_GlobalName) 8731 GV = M->getNamedValue(Fn.StrVal); 8732 else if (Fn.Kind == ValID::t_GlobalID) 8733 GV = NumberedVals.get(Fn.UIntVal); 8734 else 8735 return error(Fn.Loc, "expected function name in uselistorder_bb"); 8736 if (!GV) 8737 return error(Fn.Loc, 8738 "invalid function forward reference in uselistorder_bb"); 8739 auto *F = dyn_cast<Function>(GV); 8740 if (!F) 8741 return error(Fn.Loc, "expected function name in uselistorder_bb"); 8742 if (F->isDeclaration()) 8743 return error(Fn.Loc, "invalid declaration in uselistorder_bb"); 8744 8745 // Check the basic block. 8746 if (Label.Kind == ValID::t_LocalID) 8747 return error(Label.Loc, "invalid numeric label in uselistorder_bb"); 8748 if (Label.Kind != ValID::t_LocalName) 8749 return error(Label.Loc, "expected basic block name in uselistorder_bb"); 8750 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal); 8751 if (!V) 8752 return error(Label.Loc, "invalid basic block in uselistorder_bb"); 8753 if (!isa<BasicBlock>(V)) 8754 return error(Label.Loc, "expected basic block in uselistorder_bb"); 8755 8756 return sortUseListOrder(V, Indexes, Loc); 8757 } 8758 8759 /// ModuleEntry 8760 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')' 8761 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')' 8762 bool LLParser::parseModuleEntry(unsigned ID) { 8763 assert(Lex.getKind() == lltok::kw_module); 8764 Lex.Lex(); 8765 8766 std::string Path; 8767 if (parseToken(lltok::colon, "expected ':' here") || 8768 parseToken(lltok::lparen, "expected '(' here") || 8769 parseToken(lltok::kw_path, "expected 'path' here") || 8770 parseToken(lltok::colon, "expected ':' here") || 8771 parseStringConstant(Path) || 8772 parseToken(lltok::comma, "expected ',' here") || 8773 parseToken(lltok::kw_hash, "expected 'hash' here") || 8774 parseToken(lltok::colon, "expected ':' here") || 8775 parseToken(lltok::lparen, "expected '(' here")) 8776 return true; 8777 8778 ModuleHash Hash; 8779 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") || 8780 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") || 8781 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") || 8782 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") || 8783 parseUInt32(Hash[4])) 8784 return true; 8785 8786 if (parseToken(lltok::rparen, "expected ')' here") || 8787 parseToken(lltok::rparen, "expected ')' here")) 8788 return true; 8789 8790 auto ModuleEntry = Index->addModule(Path, Hash); 8791 ModuleIdMap[ID] = ModuleEntry->first(); 8792 8793 return false; 8794 } 8795 8796 /// TypeIdEntry 8797 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')' 8798 bool LLParser::parseTypeIdEntry(unsigned ID) { 8799 assert(Lex.getKind() == lltok::kw_typeid); 8800 Lex.Lex(); 8801 8802 std::string Name; 8803 if (parseToken(lltok::colon, "expected ':' here") || 8804 parseToken(lltok::lparen, "expected '(' here") || 8805 parseToken(lltok::kw_name, "expected 'name' here") || 8806 parseToken(lltok::colon, "expected ':' here") || 8807 parseStringConstant(Name)) 8808 return true; 8809 8810 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name); 8811 if (parseToken(lltok::comma, "expected ',' here") || 8812 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here")) 8813 return true; 8814 8815 // Check if this ID was forward referenced, and if so, update the 8816 // corresponding GUIDs. 8817 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 8818 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 8819 for (auto TIDRef : FwdRefTIDs->second) { 8820 assert(!*TIDRef.first && 8821 "Forward referenced type id GUID expected to be 0"); 8822 *TIDRef.first = GlobalValue::getGUID(Name); 8823 } 8824 ForwardRefTypeIds.erase(FwdRefTIDs); 8825 } 8826 8827 return false; 8828 } 8829 8830 /// TypeIdSummary 8831 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')' 8832 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) { 8833 if (parseToken(lltok::kw_summary, "expected 'summary' here") || 8834 parseToken(lltok::colon, "expected ':' here") || 8835 parseToken(lltok::lparen, "expected '(' here") || 8836 parseTypeTestResolution(TIS.TTRes)) 8837 return true; 8838 8839 if (EatIfPresent(lltok::comma)) { 8840 // Expect optional wpdResolutions field 8841 if (parseOptionalWpdResolutions(TIS.WPDRes)) 8842 return true; 8843 } 8844 8845 if (parseToken(lltok::rparen, "expected ')' here")) 8846 return true; 8847 8848 return false; 8849 } 8850 8851 static ValueInfo EmptyVI = 8852 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8); 8853 8854 /// TypeIdCompatibleVtableEntry 8855 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ',' 8856 /// TypeIdCompatibleVtableInfo 8857 /// ')' 8858 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) { 8859 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable); 8860 Lex.Lex(); 8861 8862 std::string Name; 8863 if (parseToken(lltok::colon, "expected ':' here") || 8864 parseToken(lltok::lparen, "expected '(' here") || 8865 parseToken(lltok::kw_name, "expected 'name' here") || 8866 parseToken(lltok::colon, "expected ':' here") || 8867 parseStringConstant(Name)) 8868 return true; 8869 8870 TypeIdCompatibleVtableInfo &TI = 8871 Index->getOrInsertTypeIdCompatibleVtableSummary(Name); 8872 if (parseToken(lltok::comma, "expected ',' here") || 8873 parseToken(lltok::kw_summary, "expected 'summary' here") || 8874 parseToken(lltok::colon, "expected ':' here") || 8875 parseToken(lltok::lparen, "expected '(' here")) 8876 return true; 8877 8878 IdToIndexMapType IdToIndexMap; 8879 // parse each call edge 8880 do { 8881 uint64_t Offset; 8882 if (parseToken(lltok::lparen, "expected '(' here") || 8883 parseToken(lltok::kw_offset, "expected 'offset' here") || 8884 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 8885 parseToken(lltok::comma, "expected ',' here")) 8886 return true; 8887 8888 LocTy Loc = Lex.getLoc(); 8889 unsigned GVId; 8890 ValueInfo VI; 8891 if (parseGVReference(VI, GVId)) 8892 return true; 8893 8894 // Keep track of the TypeIdCompatibleVtableInfo array index needing a 8895 // forward reference. We will save the location of the ValueInfo needing an 8896 // update, but can only do so once the std::vector is finalized. 8897 if (VI == EmptyVI) 8898 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc)); 8899 TI.push_back({Offset, VI}); 8900 8901 if (parseToken(lltok::rparen, "expected ')' in call")) 8902 return true; 8903 } while (EatIfPresent(lltok::comma)); 8904 8905 // Now that the TI vector is finalized, it is safe to save the locations 8906 // of any forward GV references that need updating later. 8907 for (auto I : IdToIndexMap) { 8908 auto &Infos = ForwardRefValueInfos[I.first]; 8909 for (auto P : I.second) { 8910 assert(TI[P.first].VTableVI == EmptyVI && 8911 "Forward referenced ValueInfo expected to be empty"); 8912 Infos.emplace_back(&TI[P.first].VTableVI, P.second); 8913 } 8914 } 8915 8916 if (parseToken(lltok::rparen, "expected ')' here") || 8917 parseToken(lltok::rparen, "expected ')' here")) 8918 return true; 8919 8920 // Check if this ID was forward referenced, and if so, update the 8921 // corresponding GUIDs. 8922 auto FwdRefTIDs = ForwardRefTypeIds.find(ID); 8923 if (FwdRefTIDs != ForwardRefTypeIds.end()) { 8924 for (auto TIDRef : FwdRefTIDs->second) { 8925 assert(!*TIDRef.first && 8926 "Forward referenced type id GUID expected to be 0"); 8927 *TIDRef.first = GlobalValue::getGUID(Name); 8928 } 8929 ForwardRefTypeIds.erase(FwdRefTIDs); 8930 } 8931 8932 return false; 8933 } 8934 8935 /// TypeTestResolution 8936 /// ::= 'typeTestRes' ':' '(' 'kind' ':' 8937 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ',' 8938 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]? 8939 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]? 8940 /// [',' 'inlinesBits' ':' UInt64]? ')' 8941 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) { 8942 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") || 8943 parseToken(lltok::colon, "expected ':' here") || 8944 parseToken(lltok::lparen, "expected '(' here") || 8945 parseToken(lltok::kw_kind, "expected 'kind' here") || 8946 parseToken(lltok::colon, "expected ':' here")) 8947 return true; 8948 8949 switch (Lex.getKind()) { 8950 case lltok::kw_unknown: 8951 TTRes.TheKind = TypeTestResolution::Unknown; 8952 break; 8953 case lltok::kw_unsat: 8954 TTRes.TheKind = TypeTestResolution::Unsat; 8955 break; 8956 case lltok::kw_byteArray: 8957 TTRes.TheKind = TypeTestResolution::ByteArray; 8958 break; 8959 case lltok::kw_inline: 8960 TTRes.TheKind = TypeTestResolution::Inline; 8961 break; 8962 case lltok::kw_single: 8963 TTRes.TheKind = TypeTestResolution::Single; 8964 break; 8965 case lltok::kw_allOnes: 8966 TTRes.TheKind = TypeTestResolution::AllOnes; 8967 break; 8968 default: 8969 return error(Lex.getLoc(), "unexpected TypeTestResolution kind"); 8970 } 8971 Lex.Lex(); 8972 8973 if (parseToken(lltok::comma, "expected ',' here") || 8974 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") || 8975 parseToken(lltok::colon, "expected ':' here") || 8976 parseUInt32(TTRes.SizeM1BitWidth)) 8977 return true; 8978 8979 // parse optional fields 8980 while (EatIfPresent(lltok::comma)) { 8981 switch (Lex.getKind()) { 8982 case lltok::kw_alignLog2: 8983 Lex.Lex(); 8984 if (parseToken(lltok::colon, "expected ':'") || 8985 parseUInt64(TTRes.AlignLog2)) 8986 return true; 8987 break; 8988 case lltok::kw_sizeM1: 8989 Lex.Lex(); 8990 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1)) 8991 return true; 8992 break; 8993 case lltok::kw_bitMask: { 8994 unsigned Val; 8995 Lex.Lex(); 8996 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val)) 8997 return true; 8998 assert(Val <= 0xff); 8999 TTRes.BitMask = (uint8_t)Val; 9000 break; 9001 } 9002 case lltok::kw_inlineBits: 9003 Lex.Lex(); 9004 if (parseToken(lltok::colon, "expected ':'") || 9005 parseUInt64(TTRes.InlineBits)) 9006 return true; 9007 break; 9008 default: 9009 return error(Lex.getLoc(), "expected optional TypeTestResolution field"); 9010 } 9011 } 9012 9013 if (parseToken(lltok::rparen, "expected ')' here")) 9014 return true; 9015 9016 return false; 9017 } 9018 9019 /// OptionalWpdResolutions 9020 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')' 9021 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')' 9022 bool LLParser::parseOptionalWpdResolutions( 9023 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) { 9024 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") || 9025 parseToken(lltok::colon, "expected ':' here") || 9026 parseToken(lltok::lparen, "expected '(' here")) 9027 return true; 9028 9029 do { 9030 uint64_t Offset; 9031 WholeProgramDevirtResolution WPDRes; 9032 if (parseToken(lltok::lparen, "expected '(' here") || 9033 parseToken(lltok::kw_offset, "expected 'offset' here") || 9034 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) || 9035 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) || 9036 parseToken(lltok::rparen, "expected ')' here")) 9037 return true; 9038 WPDResMap[Offset] = WPDRes; 9039 } while (EatIfPresent(lltok::comma)); 9040 9041 if (parseToken(lltok::rparen, "expected ')' here")) 9042 return true; 9043 9044 return false; 9045 } 9046 9047 /// WpdRes 9048 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir' 9049 /// [',' OptionalResByArg]? ')' 9050 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl' 9051 /// ',' 'singleImplName' ':' STRINGCONSTANT ',' 9052 /// [',' OptionalResByArg]? ')' 9053 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel' 9054 /// [',' OptionalResByArg]? ')' 9055 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) { 9056 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") || 9057 parseToken(lltok::colon, "expected ':' here") || 9058 parseToken(lltok::lparen, "expected '(' here") || 9059 parseToken(lltok::kw_kind, "expected 'kind' here") || 9060 parseToken(lltok::colon, "expected ':' here")) 9061 return true; 9062 9063 switch (Lex.getKind()) { 9064 case lltok::kw_indir: 9065 WPDRes.TheKind = WholeProgramDevirtResolution::Indir; 9066 break; 9067 case lltok::kw_singleImpl: 9068 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl; 9069 break; 9070 case lltok::kw_branchFunnel: 9071 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel; 9072 break; 9073 default: 9074 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind"); 9075 } 9076 Lex.Lex(); 9077 9078 // parse optional fields 9079 while (EatIfPresent(lltok::comma)) { 9080 switch (Lex.getKind()) { 9081 case lltok::kw_singleImplName: 9082 Lex.Lex(); 9083 if (parseToken(lltok::colon, "expected ':' here") || 9084 parseStringConstant(WPDRes.SingleImplName)) 9085 return true; 9086 break; 9087 case lltok::kw_resByArg: 9088 if (parseOptionalResByArg(WPDRes.ResByArg)) 9089 return true; 9090 break; 9091 default: 9092 return error(Lex.getLoc(), 9093 "expected optional WholeProgramDevirtResolution field"); 9094 } 9095 } 9096 9097 if (parseToken(lltok::rparen, "expected ')' here")) 9098 return true; 9099 9100 return false; 9101 } 9102 9103 /// OptionalResByArg 9104 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')' 9105 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':' 9106 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' | 9107 /// 'virtualConstProp' ) 9108 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]? 9109 /// [',' 'bit' ':' UInt32]? ')' 9110 bool LLParser::parseOptionalResByArg( 9111 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg> 9112 &ResByArg) { 9113 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") || 9114 parseToken(lltok::colon, "expected ':' here") || 9115 parseToken(lltok::lparen, "expected '(' here")) 9116 return true; 9117 9118 do { 9119 std::vector<uint64_t> Args; 9120 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") || 9121 parseToken(lltok::kw_byArg, "expected 'byArg here") || 9122 parseToken(lltok::colon, "expected ':' here") || 9123 parseToken(lltok::lparen, "expected '(' here") || 9124 parseToken(lltok::kw_kind, "expected 'kind' here") || 9125 parseToken(lltok::colon, "expected ':' here")) 9126 return true; 9127 9128 WholeProgramDevirtResolution::ByArg ByArg; 9129 switch (Lex.getKind()) { 9130 case lltok::kw_indir: 9131 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir; 9132 break; 9133 case lltok::kw_uniformRetVal: 9134 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 9135 break; 9136 case lltok::kw_uniqueRetVal: 9137 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 9138 break; 9139 case lltok::kw_virtualConstProp: 9140 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 9141 break; 9142 default: 9143 return error(Lex.getLoc(), 9144 "unexpected WholeProgramDevirtResolution::ByArg kind"); 9145 } 9146 Lex.Lex(); 9147 9148 // parse optional fields 9149 while (EatIfPresent(lltok::comma)) { 9150 switch (Lex.getKind()) { 9151 case lltok::kw_info: 9152 Lex.Lex(); 9153 if (parseToken(lltok::colon, "expected ':' here") || 9154 parseUInt64(ByArg.Info)) 9155 return true; 9156 break; 9157 case lltok::kw_byte: 9158 Lex.Lex(); 9159 if (parseToken(lltok::colon, "expected ':' here") || 9160 parseUInt32(ByArg.Byte)) 9161 return true; 9162 break; 9163 case lltok::kw_bit: 9164 Lex.Lex(); 9165 if (parseToken(lltok::colon, "expected ':' here") || 9166 parseUInt32(ByArg.Bit)) 9167 return true; 9168 break; 9169 default: 9170 return error(Lex.getLoc(), 9171 "expected optional whole program devirt field"); 9172 } 9173 } 9174 9175 if (parseToken(lltok::rparen, "expected ')' here")) 9176 return true; 9177 9178 ResByArg[Args] = ByArg; 9179 } while (EatIfPresent(lltok::comma)); 9180 9181 if (parseToken(lltok::rparen, "expected ')' here")) 9182 return true; 9183 9184 return false; 9185 } 9186 9187 /// OptionalResByArg 9188 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')' 9189 bool LLParser::parseArgs(std::vector<uint64_t> &Args) { 9190 if (parseToken(lltok::kw_args, "expected 'args' here") || 9191 parseToken(lltok::colon, "expected ':' here") || 9192 parseToken(lltok::lparen, "expected '(' here")) 9193 return true; 9194 9195 do { 9196 uint64_t Val; 9197 if (parseUInt64(Val)) 9198 return true; 9199 Args.push_back(Val); 9200 } while (EatIfPresent(lltok::comma)); 9201 9202 if (parseToken(lltok::rparen, "expected ')' here")) 9203 return true; 9204 9205 return false; 9206 } 9207 9208 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8; 9209 9210 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) { 9211 bool ReadOnly = Fwd->isReadOnly(); 9212 bool WriteOnly = Fwd->isWriteOnly(); 9213 assert(!(ReadOnly && WriteOnly)); 9214 *Fwd = Resolved; 9215 if (ReadOnly) 9216 Fwd->setReadOnly(); 9217 if (WriteOnly) 9218 Fwd->setWriteOnly(); 9219 } 9220 9221 /// Stores the given Name/GUID and associated summary into the Index. 9222 /// Also updates any forward references to the associated entry ID. 9223 bool LLParser::addGlobalValueToIndex( 9224 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage, 9225 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) { 9226 // First create the ValueInfo utilizing the Name or GUID. 9227 ValueInfo VI; 9228 if (GUID != 0) { 9229 assert(Name.empty()); 9230 VI = Index->getOrInsertValueInfo(GUID); 9231 } else { 9232 assert(!Name.empty()); 9233 if (M) { 9234 auto *GV = M->getNamedValue(Name); 9235 if (!GV) 9236 return error(Loc, "Reference to undefined global \"" + Name + "\""); 9237 9238 VI = Index->getOrInsertValueInfo(GV); 9239 } else { 9240 assert( 9241 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) && 9242 "Need a source_filename to compute GUID for local"); 9243 GUID = GlobalValue::getGUID( 9244 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName)); 9245 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name)); 9246 } 9247 } 9248 9249 // Resolve forward references from calls/refs 9250 auto FwdRefVIs = ForwardRefValueInfos.find(ID); 9251 if (FwdRefVIs != ForwardRefValueInfos.end()) { 9252 for (auto VIRef : FwdRefVIs->second) { 9253 assert(VIRef.first->getRef() == FwdVIRef && 9254 "Forward referenced ValueInfo expected to be empty"); 9255 resolveFwdRef(VIRef.first, VI); 9256 } 9257 ForwardRefValueInfos.erase(FwdRefVIs); 9258 } 9259 9260 // Resolve forward references from aliases 9261 auto FwdRefAliasees = ForwardRefAliasees.find(ID); 9262 if (FwdRefAliasees != ForwardRefAliasees.end()) { 9263 for (auto AliaseeRef : FwdRefAliasees->second) { 9264 assert(!AliaseeRef.first->hasAliasee() && 9265 "Forward referencing alias already has aliasee"); 9266 assert(Summary && "Aliasee must be a definition"); 9267 AliaseeRef.first->setAliasee(VI, Summary.get()); 9268 } 9269 ForwardRefAliasees.erase(FwdRefAliasees); 9270 } 9271 9272 // Add the summary if one was provided. 9273 if (Summary) 9274 Index->addGlobalValueSummary(VI, std::move(Summary)); 9275 9276 // Save the associated ValueInfo for use in later references by ID. 9277 if (ID == NumberedValueInfos.size()) 9278 NumberedValueInfos.push_back(VI); 9279 else { 9280 // Handle non-continuous numbers (to make test simplification easier). 9281 if (ID > NumberedValueInfos.size()) 9282 NumberedValueInfos.resize(ID + 1); 9283 NumberedValueInfos[ID] = VI; 9284 } 9285 9286 return false; 9287 } 9288 9289 /// parseSummaryIndexFlags 9290 /// ::= 'flags' ':' UInt64 9291 bool LLParser::parseSummaryIndexFlags() { 9292 assert(Lex.getKind() == lltok::kw_flags); 9293 Lex.Lex(); 9294 9295 if (parseToken(lltok::colon, "expected ':' here")) 9296 return true; 9297 uint64_t Flags; 9298 if (parseUInt64(Flags)) 9299 return true; 9300 if (Index) 9301 Index->setFlags(Flags); 9302 return false; 9303 } 9304 9305 /// parseBlockCount 9306 /// ::= 'blockcount' ':' UInt64 9307 bool LLParser::parseBlockCount() { 9308 assert(Lex.getKind() == lltok::kw_blockcount); 9309 Lex.Lex(); 9310 9311 if (parseToken(lltok::colon, "expected ':' here")) 9312 return true; 9313 uint64_t BlockCount; 9314 if (parseUInt64(BlockCount)) 9315 return true; 9316 if (Index) 9317 Index->setBlockCount(BlockCount); 9318 return false; 9319 } 9320 9321 /// parseGVEntry 9322 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64) 9323 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')' 9324 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')' 9325 bool LLParser::parseGVEntry(unsigned ID) { 9326 assert(Lex.getKind() == lltok::kw_gv); 9327 Lex.Lex(); 9328 9329 if (parseToken(lltok::colon, "expected ':' here") || 9330 parseToken(lltok::lparen, "expected '(' here")) 9331 return true; 9332 9333 LocTy Loc = Lex.getLoc(); 9334 std::string Name; 9335 GlobalValue::GUID GUID = 0; 9336 switch (Lex.getKind()) { 9337 case lltok::kw_name: 9338 Lex.Lex(); 9339 if (parseToken(lltok::colon, "expected ':' here") || 9340 parseStringConstant(Name)) 9341 return true; 9342 // Can't create GUID/ValueInfo until we have the linkage. 9343 break; 9344 case lltok::kw_guid: 9345 Lex.Lex(); 9346 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID)) 9347 return true; 9348 break; 9349 default: 9350 return error(Lex.getLoc(), "expected name or guid tag"); 9351 } 9352 9353 if (!EatIfPresent(lltok::comma)) { 9354 // No summaries. Wrap up. 9355 if (parseToken(lltok::rparen, "expected ')' here")) 9356 return true; 9357 // This was created for a call to an external or indirect target. 9358 // A GUID with no summary came from a VALUE_GUID record, dummy GUID 9359 // created for indirect calls with VP. A Name with no GUID came from 9360 // an external definition. We pass ExternalLinkage since that is only 9361 // used when the GUID must be computed from Name, and in that case 9362 // the symbol must have external linkage. 9363 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID, 9364 nullptr, Loc); 9365 } 9366 9367 // Have a list of summaries 9368 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") || 9369 parseToken(lltok::colon, "expected ':' here") || 9370 parseToken(lltok::lparen, "expected '(' here")) 9371 return true; 9372 do { 9373 switch (Lex.getKind()) { 9374 case lltok::kw_function: 9375 if (parseFunctionSummary(Name, GUID, ID)) 9376 return true; 9377 break; 9378 case lltok::kw_variable: 9379 if (parseVariableSummary(Name, GUID, ID)) 9380 return true; 9381 break; 9382 case lltok::kw_alias: 9383 if (parseAliasSummary(Name, GUID, ID)) 9384 return true; 9385 break; 9386 default: 9387 return error(Lex.getLoc(), "expected summary type"); 9388 } 9389 } while (EatIfPresent(lltok::comma)); 9390 9391 if (parseToken(lltok::rparen, "expected ')' here") || 9392 parseToken(lltok::rparen, "expected ')' here")) 9393 return true; 9394 9395 return false; 9396 } 9397 9398 /// FunctionSummary 9399 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags 9400 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]? 9401 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]? 9402 /// [',' OptionalRefs]? ')' 9403 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID, 9404 unsigned ID) { 9405 LocTy Loc = Lex.getLoc(); 9406 assert(Lex.getKind() == lltok::kw_function); 9407 Lex.Lex(); 9408 9409 StringRef ModulePath; 9410 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 9411 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 9412 /*NotEligibleToImport=*/false, 9413 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, 9414 GlobalValueSummary::Definition); 9415 unsigned InstCount; 9416 SmallVector<FunctionSummary::EdgeTy, 0> Calls; 9417 FunctionSummary::TypeIdInfo TypeIdInfo; 9418 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 9419 SmallVector<ValueInfo, 0> Refs; 9420 std::vector<CallsiteInfo> Callsites; 9421 std::vector<AllocInfo> Allocs; 9422 // Default is all-zeros (conservative values). 9423 FunctionSummary::FFlags FFlags = {}; 9424 if (parseToken(lltok::colon, "expected ':' here") || 9425 parseToken(lltok::lparen, "expected '(' here") || 9426 parseModuleReference(ModulePath) || 9427 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 9428 parseToken(lltok::comma, "expected ',' here") || 9429 parseToken(lltok::kw_insts, "expected 'insts' here") || 9430 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount)) 9431 return true; 9432 9433 // parse optional fields 9434 while (EatIfPresent(lltok::comma)) { 9435 switch (Lex.getKind()) { 9436 case lltok::kw_funcFlags: 9437 if (parseOptionalFFlags(FFlags)) 9438 return true; 9439 break; 9440 case lltok::kw_calls: 9441 if (parseOptionalCalls(Calls)) 9442 return true; 9443 break; 9444 case lltok::kw_typeIdInfo: 9445 if (parseOptionalTypeIdInfo(TypeIdInfo)) 9446 return true; 9447 break; 9448 case lltok::kw_refs: 9449 if (parseOptionalRefs(Refs)) 9450 return true; 9451 break; 9452 case lltok::kw_params: 9453 if (parseOptionalParamAccesses(ParamAccesses)) 9454 return true; 9455 break; 9456 case lltok::kw_allocs: 9457 if (parseOptionalAllocs(Allocs)) 9458 return true; 9459 break; 9460 case lltok::kw_callsites: 9461 if (parseOptionalCallsites(Callsites)) 9462 return true; 9463 break; 9464 default: 9465 return error(Lex.getLoc(), "expected optional function summary field"); 9466 } 9467 } 9468 9469 if (parseToken(lltok::rparen, "expected ')' here")) 9470 return true; 9471 9472 auto FS = std::make_unique<FunctionSummary>( 9473 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls), 9474 std::move(TypeIdInfo.TypeTests), 9475 std::move(TypeIdInfo.TypeTestAssumeVCalls), 9476 std::move(TypeIdInfo.TypeCheckedLoadVCalls), 9477 std::move(TypeIdInfo.TypeTestAssumeConstVCalls), 9478 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls), 9479 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs)); 9480 9481 FS->setModulePath(ModulePath); 9482 9483 return addGlobalValueToIndex(Name, GUID, 9484 (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, 9485 std::move(FS), Loc); 9486 } 9487 9488 /// VariableSummary 9489 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags 9490 /// [',' OptionalRefs]? ')' 9491 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID, 9492 unsigned ID) { 9493 LocTy Loc = Lex.getLoc(); 9494 assert(Lex.getKind() == lltok::kw_variable); 9495 Lex.Lex(); 9496 9497 StringRef ModulePath; 9498 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 9499 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 9500 /*NotEligibleToImport=*/false, 9501 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, 9502 GlobalValueSummary::Definition); 9503 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false, 9504 /* WriteOnly */ false, 9505 /* Constant */ false, 9506 GlobalObject::VCallVisibilityPublic); 9507 SmallVector<ValueInfo, 0> Refs; 9508 VTableFuncList VTableFuncs; 9509 if (parseToken(lltok::colon, "expected ':' here") || 9510 parseToken(lltok::lparen, "expected '(' here") || 9511 parseModuleReference(ModulePath) || 9512 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 9513 parseToken(lltok::comma, "expected ',' here") || 9514 parseGVarFlags(GVarFlags)) 9515 return true; 9516 9517 // parse optional fields 9518 while (EatIfPresent(lltok::comma)) { 9519 switch (Lex.getKind()) { 9520 case lltok::kw_vTableFuncs: 9521 if (parseOptionalVTableFuncs(VTableFuncs)) 9522 return true; 9523 break; 9524 case lltok::kw_refs: 9525 if (parseOptionalRefs(Refs)) 9526 return true; 9527 break; 9528 default: 9529 return error(Lex.getLoc(), "expected optional variable summary field"); 9530 } 9531 } 9532 9533 if (parseToken(lltok::rparen, "expected ')' here")) 9534 return true; 9535 9536 auto GS = 9537 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs)); 9538 9539 GS->setModulePath(ModulePath); 9540 GS->setVTableFuncs(std::move(VTableFuncs)); 9541 9542 return addGlobalValueToIndex(Name, GUID, 9543 (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, 9544 std::move(GS), Loc); 9545 } 9546 9547 /// AliasSummary 9548 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ',' 9549 /// 'aliasee' ':' GVReference ')' 9550 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID, 9551 unsigned ID) { 9552 assert(Lex.getKind() == lltok::kw_alias); 9553 LocTy Loc = Lex.getLoc(); 9554 Lex.Lex(); 9555 9556 StringRef ModulePath; 9557 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags( 9558 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility, 9559 /*NotEligibleToImport=*/false, 9560 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false, 9561 GlobalValueSummary::Definition); 9562 if (parseToken(lltok::colon, "expected ':' here") || 9563 parseToken(lltok::lparen, "expected '(' here") || 9564 parseModuleReference(ModulePath) || 9565 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) || 9566 parseToken(lltok::comma, "expected ',' here") || 9567 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") || 9568 parseToken(lltok::colon, "expected ':' here")) 9569 return true; 9570 9571 ValueInfo AliaseeVI; 9572 unsigned GVId; 9573 if (parseGVReference(AliaseeVI, GVId)) 9574 return true; 9575 9576 if (parseToken(lltok::rparen, "expected ')' here")) 9577 return true; 9578 9579 auto AS = std::make_unique<AliasSummary>(GVFlags); 9580 9581 AS->setModulePath(ModulePath); 9582 9583 // Record forward reference if the aliasee is not parsed yet. 9584 if (AliaseeVI.getRef() == FwdVIRef) { 9585 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc); 9586 } else { 9587 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath); 9588 assert(Summary && "Aliasee must be a definition"); 9589 AS->setAliasee(AliaseeVI, Summary); 9590 } 9591 9592 return addGlobalValueToIndex(Name, GUID, 9593 (GlobalValue::LinkageTypes)GVFlags.Linkage, ID, 9594 std::move(AS), Loc); 9595 } 9596 9597 /// Flag 9598 /// ::= [0|1] 9599 bool LLParser::parseFlag(unsigned &Val) { 9600 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned()) 9601 return tokError("expected integer"); 9602 Val = (unsigned)Lex.getAPSIntVal().getBoolValue(); 9603 Lex.Lex(); 9604 return false; 9605 } 9606 9607 /// OptionalFFlags 9608 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]? 9609 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]? 9610 /// [',' 'returnDoesNotAlias' ':' Flag]? ')' 9611 /// [',' 'noInline' ':' Flag]? ')' 9612 /// [',' 'alwaysInline' ':' Flag]? ')' 9613 /// [',' 'noUnwind' ':' Flag]? ')' 9614 /// [',' 'mayThrow' ':' Flag]? ')' 9615 /// [',' 'hasUnknownCall' ':' Flag]? ')' 9616 /// [',' 'mustBeUnreachable' ':' Flag]? ')' 9617 9618 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) { 9619 assert(Lex.getKind() == lltok::kw_funcFlags); 9620 Lex.Lex(); 9621 9622 if (parseToken(lltok::colon, "expected ':' in funcFlags") || 9623 parseToken(lltok::lparen, "expected '(' in funcFlags")) 9624 return true; 9625 9626 do { 9627 unsigned Val = 0; 9628 switch (Lex.getKind()) { 9629 case lltok::kw_readNone: 9630 Lex.Lex(); 9631 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9632 return true; 9633 FFlags.ReadNone = Val; 9634 break; 9635 case lltok::kw_readOnly: 9636 Lex.Lex(); 9637 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9638 return true; 9639 FFlags.ReadOnly = Val; 9640 break; 9641 case lltok::kw_noRecurse: 9642 Lex.Lex(); 9643 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9644 return true; 9645 FFlags.NoRecurse = Val; 9646 break; 9647 case lltok::kw_returnDoesNotAlias: 9648 Lex.Lex(); 9649 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9650 return true; 9651 FFlags.ReturnDoesNotAlias = Val; 9652 break; 9653 case lltok::kw_noInline: 9654 Lex.Lex(); 9655 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9656 return true; 9657 FFlags.NoInline = Val; 9658 break; 9659 case lltok::kw_alwaysInline: 9660 Lex.Lex(); 9661 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9662 return true; 9663 FFlags.AlwaysInline = Val; 9664 break; 9665 case lltok::kw_noUnwind: 9666 Lex.Lex(); 9667 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9668 return true; 9669 FFlags.NoUnwind = Val; 9670 break; 9671 case lltok::kw_mayThrow: 9672 Lex.Lex(); 9673 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9674 return true; 9675 FFlags.MayThrow = Val; 9676 break; 9677 case lltok::kw_hasUnknownCall: 9678 Lex.Lex(); 9679 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9680 return true; 9681 FFlags.HasUnknownCall = Val; 9682 break; 9683 case lltok::kw_mustBeUnreachable: 9684 Lex.Lex(); 9685 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val)) 9686 return true; 9687 FFlags.MustBeUnreachable = Val; 9688 break; 9689 default: 9690 return error(Lex.getLoc(), "expected function flag type"); 9691 } 9692 } while (EatIfPresent(lltok::comma)); 9693 9694 if (parseToken(lltok::rparen, "expected ')' in funcFlags")) 9695 return true; 9696 9697 return false; 9698 } 9699 9700 /// OptionalCalls 9701 /// := 'calls' ':' '(' Call [',' Call]* ')' 9702 /// Call ::= '(' 'callee' ':' GVReference 9703 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? 9704 /// [ ',' 'tail' ]? ')' 9705 bool LLParser::parseOptionalCalls( 9706 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) { 9707 assert(Lex.getKind() == lltok::kw_calls); 9708 Lex.Lex(); 9709 9710 if (parseToken(lltok::colon, "expected ':' in calls") || 9711 parseToken(lltok::lparen, "expected '(' in calls")) 9712 return true; 9713 9714 IdToIndexMapType IdToIndexMap; 9715 // parse each call edge 9716 do { 9717 ValueInfo VI; 9718 if (parseToken(lltok::lparen, "expected '(' in call") || 9719 parseToken(lltok::kw_callee, "expected 'callee' in call") || 9720 parseToken(lltok::colon, "expected ':'")) 9721 return true; 9722 9723 LocTy Loc = Lex.getLoc(); 9724 unsigned GVId; 9725 if (parseGVReference(VI, GVId)) 9726 return true; 9727 9728 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 9729 unsigned RelBF = 0; 9730 unsigned HasTailCall = false; 9731 9732 // parse optional fields 9733 while (EatIfPresent(lltok::comma)) { 9734 switch (Lex.getKind()) { 9735 case lltok::kw_hotness: 9736 Lex.Lex(); 9737 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness)) 9738 return true; 9739 break; 9740 case lltok::kw_relbf: 9741 Lex.Lex(); 9742 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF)) 9743 return true; 9744 break; 9745 case lltok::kw_tail: 9746 Lex.Lex(); 9747 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall)) 9748 return true; 9749 break; 9750 default: 9751 return error(Lex.getLoc(), "expected hotness, relbf, or tail"); 9752 } 9753 } 9754 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0) 9755 return tokError("Expected only one of hotness or relbf"); 9756 // Keep track of the Call array index needing a forward reference. 9757 // We will save the location of the ValueInfo needing an update, but 9758 // can only do so once the std::vector is finalized. 9759 if (VI.getRef() == FwdVIRef) 9760 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc)); 9761 Calls.push_back( 9762 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)}); 9763 9764 if (parseToken(lltok::rparen, "expected ')' in call")) 9765 return true; 9766 } while (EatIfPresent(lltok::comma)); 9767 9768 // Now that the Calls vector is finalized, it is safe to save the locations 9769 // of any forward GV references that need updating later. 9770 for (auto I : IdToIndexMap) { 9771 auto &Infos = ForwardRefValueInfos[I.first]; 9772 for (auto P : I.second) { 9773 assert(Calls[P.first].first.getRef() == FwdVIRef && 9774 "Forward referenced ValueInfo expected to be empty"); 9775 Infos.emplace_back(&Calls[P.first].first, P.second); 9776 } 9777 } 9778 9779 if (parseToken(lltok::rparen, "expected ')' in calls")) 9780 return true; 9781 9782 return false; 9783 } 9784 9785 /// Hotness 9786 /// := ('unknown'|'cold'|'none'|'hot'|'critical') 9787 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) { 9788 switch (Lex.getKind()) { 9789 case lltok::kw_unknown: 9790 Hotness = CalleeInfo::HotnessType::Unknown; 9791 break; 9792 case lltok::kw_cold: 9793 Hotness = CalleeInfo::HotnessType::Cold; 9794 break; 9795 case lltok::kw_none: 9796 Hotness = CalleeInfo::HotnessType::None; 9797 break; 9798 case lltok::kw_hot: 9799 Hotness = CalleeInfo::HotnessType::Hot; 9800 break; 9801 case lltok::kw_critical: 9802 Hotness = CalleeInfo::HotnessType::Critical; 9803 break; 9804 default: 9805 return error(Lex.getLoc(), "invalid call edge hotness"); 9806 } 9807 Lex.Lex(); 9808 return false; 9809 } 9810 9811 /// OptionalVTableFuncs 9812 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')' 9813 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')' 9814 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) { 9815 assert(Lex.getKind() == lltok::kw_vTableFuncs); 9816 Lex.Lex(); 9817 9818 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") || 9819 parseToken(lltok::lparen, "expected '(' in vTableFuncs")) 9820 return true; 9821 9822 IdToIndexMapType IdToIndexMap; 9823 // parse each virtual function pair 9824 do { 9825 ValueInfo VI; 9826 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") || 9827 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") || 9828 parseToken(lltok::colon, "expected ':'")) 9829 return true; 9830 9831 LocTy Loc = Lex.getLoc(); 9832 unsigned GVId; 9833 if (parseGVReference(VI, GVId)) 9834 return true; 9835 9836 uint64_t Offset; 9837 if (parseToken(lltok::comma, "expected comma") || 9838 parseToken(lltok::kw_offset, "expected offset") || 9839 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset)) 9840 return true; 9841 9842 // Keep track of the VTableFuncs array index needing a forward reference. 9843 // We will save the location of the ValueInfo needing an update, but 9844 // can only do so once the std::vector is finalized. 9845 if (VI == EmptyVI) 9846 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc)); 9847 VTableFuncs.push_back({VI, Offset}); 9848 9849 if (parseToken(lltok::rparen, "expected ')' in vTableFunc")) 9850 return true; 9851 } while (EatIfPresent(lltok::comma)); 9852 9853 // Now that the VTableFuncs vector is finalized, it is safe to save the 9854 // locations of any forward GV references that need updating later. 9855 for (auto I : IdToIndexMap) { 9856 auto &Infos = ForwardRefValueInfos[I.first]; 9857 for (auto P : I.second) { 9858 assert(VTableFuncs[P.first].FuncVI == EmptyVI && 9859 "Forward referenced ValueInfo expected to be empty"); 9860 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second); 9861 } 9862 } 9863 9864 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs")) 9865 return true; 9866 9867 return false; 9868 } 9869 9870 /// ParamNo := 'param' ':' UInt64 9871 bool LLParser::parseParamNo(uint64_t &ParamNo) { 9872 if (parseToken(lltok::kw_param, "expected 'param' here") || 9873 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo)) 9874 return true; 9875 return false; 9876 } 9877 9878 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']' 9879 bool LLParser::parseParamAccessOffset(ConstantRange &Range) { 9880 APSInt Lower; 9881 APSInt Upper; 9882 auto ParseAPSInt = [&](APSInt &Val) { 9883 if (Lex.getKind() != lltok::APSInt) 9884 return tokError("expected integer"); 9885 Val = Lex.getAPSIntVal(); 9886 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth); 9887 Val.setIsSigned(true); 9888 Lex.Lex(); 9889 return false; 9890 }; 9891 if (parseToken(lltok::kw_offset, "expected 'offset' here") || 9892 parseToken(lltok::colon, "expected ':' here") || 9893 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) || 9894 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) || 9895 parseToken(lltok::rsquare, "expected ']' here")) 9896 return true; 9897 9898 ++Upper; 9899 Range = 9900 (Lower == Upper && !Lower.isMaxValue()) 9901 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth) 9902 : ConstantRange(Lower, Upper); 9903 9904 return false; 9905 } 9906 9907 /// ParamAccessCall 9908 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')' 9909 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call, 9910 IdLocListType &IdLocList) { 9911 if (parseToken(lltok::lparen, "expected '(' here") || 9912 parseToken(lltok::kw_callee, "expected 'callee' here") || 9913 parseToken(lltok::colon, "expected ':' here")) 9914 return true; 9915 9916 unsigned GVId; 9917 ValueInfo VI; 9918 LocTy Loc = Lex.getLoc(); 9919 if (parseGVReference(VI, GVId)) 9920 return true; 9921 9922 Call.Callee = VI; 9923 IdLocList.emplace_back(GVId, Loc); 9924 9925 if (parseToken(lltok::comma, "expected ',' here") || 9926 parseParamNo(Call.ParamNo) || 9927 parseToken(lltok::comma, "expected ',' here") || 9928 parseParamAccessOffset(Call.Offsets)) 9929 return true; 9930 9931 if (parseToken(lltok::rparen, "expected ')' here")) 9932 return true; 9933 9934 return false; 9935 } 9936 9937 /// ParamAccess 9938 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')' 9939 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')' 9940 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param, 9941 IdLocListType &IdLocList) { 9942 if (parseToken(lltok::lparen, "expected '(' here") || 9943 parseParamNo(Param.ParamNo) || 9944 parseToken(lltok::comma, "expected ',' here") || 9945 parseParamAccessOffset(Param.Use)) 9946 return true; 9947 9948 if (EatIfPresent(lltok::comma)) { 9949 if (parseToken(lltok::kw_calls, "expected 'calls' here") || 9950 parseToken(lltok::colon, "expected ':' here") || 9951 parseToken(lltok::lparen, "expected '(' here")) 9952 return true; 9953 do { 9954 FunctionSummary::ParamAccess::Call Call; 9955 if (parseParamAccessCall(Call, IdLocList)) 9956 return true; 9957 Param.Calls.push_back(Call); 9958 } while (EatIfPresent(lltok::comma)); 9959 9960 if (parseToken(lltok::rparen, "expected ')' here")) 9961 return true; 9962 } 9963 9964 if (parseToken(lltok::rparen, "expected ')' here")) 9965 return true; 9966 9967 return false; 9968 } 9969 9970 /// OptionalParamAccesses 9971 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')' 9972 bool LLParser::parseOptionalParamAccesses( 9973 std::vector<FunctionSummary::ParamAccess> &Params) { 9974 assert(Lex.getKind() == lltok::kw_params); 9975 Lex.Lex(); 9976 9977 if (parseToken(lltok::colon, "expected ':' here") || 9978 parseToken(lltok::lparen, "expected '(' here")) 9979 return true; 9980 9981 IdLocListType VContexts; 9982 size_t CallsNum = 0; 9983 do { 9984 FunctionSummary::ParamAccess ParamAccess; 9985 if (parseParamAccess(ParamAccess, VContexts)) 9986 return true; 9987 CallsNum += ParamAccess.Calls.size(); 9988 assert(VContexts.size() == CallsNum); 9989 (void)CallsNum; 9990 Params.emplace_back(std::move(ParamAccess)); 9991 } while (EatIfPresent(lltok::comma)); 9992 9993 if (parseToken(lltok::rparen, "expected ')' here")) 9994 return true; 9995 9996 // Now that the Params is finalized, it is safe to save the locations 9997 // of any forward GV references that need updating later. 9998 IdLocListType::const_iterator ItContext = VContexts.begin(); 9999 for (auto &PA : Params) { 10000 for (auto &C : PA.Calls) { 10001 if (C.Callee.getRef() == FwdVIRef) 10002 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee, 10003 ItContext->second); 10004 ++ItContext; 10005 } 10006 } 10007 assert(ItContext == VContexts.end()); 10008 10009 return false; 10010 } 10011 10012 /// OptionalRefs 10013 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')' 10014 bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) { 10015 assert(Lex.getKind() == lltok::kw_refs); 10016 Lex.Lex(); 10017 10018 if (parseToken(lltok::colon, "expected ':' in refs") || 10019 parseToken(lltok::lparen, "expected '(' in refs")) 10020 return true; 10021 10022 struct ValueContext { 10023 ValueInfo VI; 10024 unsigned GVId; 10025 LocTy Loc; 10026 }; 10027 std::vector<ValueContext> VContexts; 10028 // parse each ref edge 10029 do { 10030 ValueContext VC; 10031 VC.Loc = Lex.getLoc(); 10032 if (parseGVReference(VC.VI, VC.GVId)) 10033 return true; 10034 VContexts.push_back(VC); 10035 } while (EatIfPresent(lltok::comma)); 10036 10037 // Sort value contexts so that ones with writeonly 10038 // and readonly ValueInfo are at the end of VContexts vector. 10039 // See FunctionSummary::specialRefCounts() 10040 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) { 10041 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier(); 10042 }); 10043 10044 IdToIndexMapType IdToIndexMap; 10045 for (auto &VC : VContexts) { 10046 // Keep track of the Refs array index needing a forward reference. 10047 // We will save the location of the ValueInfo needing an update, but 10048 // can only do so once the std::vector is finalized. 10049 if (VC.VI.getRef() == FwdVIRef) 10050 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc)); 10051 Refs.push_back(VC.VI); 10052 } 10053 10054 // Now that the Refs vector is finalized, it is safe to save the locations 10055 // of any forward GV references that need updating later. 10056 for (auto I : IdToIndexMap) { 10057 auto &Infos = ForwardRefValueInfos[I.first]; 10058 for (auto P : I.second) { 10059 assert(Refs[P.first].getRef() == FwdVIRef && 10060 "Forward referenced ValueInfo expected to be empty"); 10061 Infos.emplace_back(&Refs[P.first], P.second); 10062 } 10063 } 10064 10065 if (parseToken(lltok::rparen, "expected ')' in refs")) 10066 return true; 10067 10068 return false; 10069 } 10070 10071 /// OptionalTypeIdInfo 10072 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]? 10073 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]? 10074 /// [',' TypeCheckedLoadConstVCalls]? ')' 10075 bool LLParser::parseOptionalTypeIdInfo( 10076 FunctionSummary::TypeIdInfo &TypeIdInfo) { 10077 assert(Lex.getKind() == lltok::kw_typeIdInfo); 10078 Lex.Lex(); 10079 10080 if (parseToken(lltok::colon, "expected ':' here") || 10081 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 10082 return true; 10083 10084 do { 10085 switch (Lex.getKind()) { 10086 case lltok::kw_typeTests: 10087 if (parseTypeTests(TypeIdInfo.TypeTests)) 10088 return true; 10089 break; 10090 case lltok::kw_typeTestAssumeVCalls: 10091 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls, 10092 TypeIdInfo.TypeTestAssumeVCalls)) 10093 return true; 10094 break; 10095 case lltok::kw_typeCheckedLoadVCalls: 10096 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls, 10097 TypeIdInfo.TypeCheckedLoadVCalls)) 10098 return true; 10099 break; 10100 case lltok::kw_typeTestAssumeConstVCalls: 10101 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls, 10102 TypeIdInfo.TypeTestAssumeConstVCalls)) 10103 return true; 10104 break; 10105 case lltok::kw_typeCheckedLoadConstVCalls: 10106 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls, 10107 TypeIdInfo.TypeCheckedLoadConstVCalls)) 10108 return true; 10109 break; 10110 default: 10111 return error(Lex.getLoc(), "invalid typeIdInfo list type"); 10112 } 10113 } while (EatIfPresent(lltok::comma)); 10114 10115 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 10116 return true; 10117 10118 return false; 10119 } 10120 10121 /// TypeTests 10122 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64) 10123 /// [',' (SummaryID | UInt64)]* ')' 10124 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) { 10125 assert(Lex.getKind() == lltok::kw_typeTests); 10126 Lex.Lex(); 10127 10128 if (parseToken(lltok::colon, "expected ':' here") || 10129 parseToken(lltok::lparen, "expected '(' in typeIdInfo")) 10130 return true; 10131 10132 IdToIndexMapType IdToIndexMap; 10133 do { 10134 GlobalValue::GUID GUID = 0; 10135 if (Lex.getKind() == lltok::SummaryID) { 10136 unsigned ID = Lex.getUIntVal(); 10137 LocTy Loc = Lex.getLoc(); 10138 // Keep track of the TypeTests array index needing a forward reference. 10139 // We will save the location of the GUID needing an update, but 10140 // can only do so once the std::vector is finalized. 10141 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc)); 10142 Lex.Lex(); 10143 } else if (parseUInt64(GUID)) 10144 return true; 10145 TypeTests.push_back(GUID); 10146 } while (EatIfPresent(lltok::comma)); 10147 10148 // Now that the TypeTests vector is finalized, it is safe to save the 10149 // locations of any forward GV references that need updating later. 10150 for (auto I : IdToIndexMap) { 10151 auto &Ids = ForwardRefTypeIds[I.first]; 10152 for (auto P : I.second) { 10153 assert(TypeTests[P.first] == 0 && 10154 "Forward referenced type id GUID expected to be 0"); 10155 Ids.emplace_back(&TypeTests[P.first], P.second); 10156 } 10157 } 10158 10159 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo")) 10160 return true; 10161 10162 return false; 10163 } 10164 10165 /// VFuncIdList 10166 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')' 10167 bool LLParser::parseVFuncIdList( 10168 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) { 10169 assert(Lex.getKind() == Kind); 10170 Lex.Lex(); 10171 10172 if (parseToken(lltok::colon, "expected ':' here") || 10173 parseToken(lltok::lparen, "expected '(' here")) 10174 return true; 10175 10176 IdToIndexMapType IdToIndexMap; 10177 do { 10178 FunctionSummary::VFuncId VFuncId; 10179 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size())) 10180 return true; 10181 VFuncIdList.push_back(VFuncId); 10182 } while (EatIfPresent(lltok::comma)); 10183 10184 if (parseToken(lltok::rparen, "expected ')' here")) 10185 return true; 10186 10187 // Now that the VFuncIdList vector is finalized, it is safe to save the 10188 // locations of any forward GV references that need updating later. 10189 for (auto I : IdToIndexMap) { 10190 auto &Ids = ForwardRefTypeIds[I.first]; 10191 for (auto P : I.second) { 10192 assert(VFuncIdList[P.first].GUID == 0 && 10193 "Forward referenced type id GUID expected to be 0"); 10194 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second); 10195 } 10196 } 10197 10198 return false; 10199 } 10200 10201 /// ConstVCallList 10202 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')' 10203 bool LLParser::parseConstVCallList( 10204 lltok::Kind Kind, 10205 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) { 10206 assert(Lex.getKind() == Kind); 10207 Lex.Lex(); 10208 10209 if (parseToken(lltok::colon, "expected ':' here") || 10210 parseToken(lltok::lparen, "expected '(' here")) 10211 return true; 10212 10213 IdToIndexMapType IdToIndexMap; 10214 do { 10215 FunctionSummary::ConstVCall ConstVCall; 10216 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size())) 10217 return true; 10218 ConstVCallList.push_back(ConstVCall); 10219 } while (EatIfPresent(lltok::comma)); 10220 10221 if (parseToken(lltok::rparen, "expected ')' here")) 10222 return true; 10223 10224 // Now that the ConstVCallList vector is finalized, it is safe to save the 10225 // locations of any forward GV references that need updating later. 10226 for (auto I : IdToIndexMap) { 10227 auto &Ids = ForwardRefTypeIds[I.first]; 10228 for (auto P : I.second) { 10229 assert(ConstVCallList[P.first].VFunc.GUID == 0 && 10230 "Forward referenced type id GUID expected to be 0"); 10231 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second); 10232 } 10233 } 10234 10235 return false; 10236 } 10237 10238 /// ConstVCall 10239 /// ::= '(' VFuncId ',' Args ')' 10240 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall, 10241 IdToIndexMapType &IdToIndexMap, unsigned Index) { 10242 if (parseToken(lltok::lparen, "expected '(' here") || 10243 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index)) 10244 return true; 10245 10246 if (EatIfPresent(lltok::comma)) 10247 if (parseArgs(ConstVCall.Args)) 10248 return true; 10249 10250 if (parseToken(lltok::rparen, "expected ')' here")) 10251 return true; 10252 10253 return false; 10254 } 10255 10256 /// VFuncId 10257 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ',' 10258 /// 'offset' ':' UInt64 ')' 10259 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId, 10260 IdToIndexMapType &IdToIndexMap, unsigned Index) { 10261 assert(Lex.getKind() == lltok::kw_vFuncId); 10262 Lex.Lex(); 10263 10264 if (parseToken(lltok::colon, "expected ':' here") || 10265 parseToken(lltok::lparen, "expected '(' here")) 10266 return true; 10267 10268 if (Lex.getKind() == lltok::SummaryID) { 10269 VFuncId.GUID = 0; 10270 unsigned ID = Lex.getUIntVal(); 10271 LocTy Loc = Lex.getLoc(); 10272 // Keep track of the array index needing a forward reference. 10273 // We will save the location of the GUID needing an update, but 10274 // can only do so once the caller's std::vector is finalized. 10275 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc)); 10276 Lex.Lex(); 10277 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") || 10278 parseToken(lltok::colon, "expected ':' here") || 10279 parseUInt64(VFuncId.GUID)) 10280 return true; 10281 10282 if (parseToken(lltok::comma, "expected ',' here") || 10283 parseToken(lltok::kw_offset, "expected 'offset' here") || 10284 parseToken(lltok::colon, "expected ':' here") || 10285 parseUInt64(VFuncId.Offset) || 10286 parseToken(lltok::rparen, "expected ')' here")) 10287 return true; 10288 10289 return false; 10290 } 10291 10292 /// GVFlags 10293 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ',' 10294 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ',' 10295 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ',' 10296 /// 'canAutoHide' ':' Flag ',' ')' 10297 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) { 10298 assert(Lex.getKind() == lltok::kw_flags); 10299 Lex.Lex(); 10300 10301 if (parseToken(lltok::colon, "expected ':' here") || 10302 parseToken(lltok::lparen, "expected '(' here")) 10303 return true; 10304 10305 do { 10306 unsigned Flag = 0; 10307 switch (Lex.getKind()) { 10308 case lltok::kw_linkage: 10309 Lex.Lex(); 10310 if (parseToken(lltok::colon, "expected ':'")) 10311 return true; 10312 bool HasLinkage; 10313 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage); 10314 assert(HasLinkage && "Linkage not optional in summary entry"); 10315 Lex.Lex(); 10316 break; 10317 case lltok::kw_visibility: 10318 Lex.Lex(); 10319 if (parseToken(lltok::colon, "expected ':'")) 10320 return true; 10321 parseOptionalVisibility(Flag); 10322 GVFlags.Visibility = Flag; 10323 break; 10324 case lltok::kw_notEligibleToImport: 10325 Lex.Lex(); 10326 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10327 return true; 10328 GVFlags.NotEligibleToImport = Flag; 10329 break; 10330 case lltok::kw_live: 10331 Lex.Lex(); 10332 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10333 return true; 10334 GVFlags.Live = Flag; 10335 break; 10336 case lltok::kw_dsoLocal: 10337 Lex.Lex(); 10338 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10339 return true; 10340 GVFlags.DSOLocal = Flag; 10341 break; 10342 case lltok::kw_canAutoHide: 10343 Lex.Lex(); 10344 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag)) 10345 return true; 10346 GVFlags.CanAutoHide = Flag; 10347 break; 10348 case lltok::kw_importType: 10349 Lex.Lex(); 10350 if (parseToken(lltok::colon, "expected ':'")) 10351 return true; 10352 GlobalValueSummary::ImportKind IK; 10353 if (parseOptionalImportType(Lex.getKind(), IK)) 10354 return true; 10355 GVFlags.ImportType = static_cast<unsigned>(IK); 10356 Lex.Lex(); 10357 break; 10358 default: 10359 return error(Lex.getLoc(), "expected gv flag type"); 10360 } 10361 } while (EatIfPresent(lltok::comma)); 10362 10363 if (parseToken(lltok::rparen, "expected ')' here")) 10364 return true; 10365 10366 return false; 10367 } 10368 10369 /// GVarFlags 10370 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag 10371 /// ',' 'writeonly' ':' Flag 10372 /// ',' 'constant' ':' Flag ')' 10373 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) { 10374 assert(Lex.getKind() == lltok::kw_varFlags); 10375 Lex.Lex(); 10376 10377 if (parseToken(lltok::colon, "expected ':' here") || 10378 parseToken(lltok::lparen, "expected '(' here")) 10379 return true; 10380 10381 auto ParseRest = [this](unsigned int &Val) { 10382 Lex.Lex(); 10383 if (parseToken(lltok::colon, "expected ':'")) 10384 return true; 10385 return parseFlag(Val); 10386 }; 10387 10388 do { 10389 unsigned Flag = 0; 10390 switch (Lex.getKind()) { 10391 case lltok::kw_readonly: 10392 if (ParseRest(Flag)) 10393 return true; 10394 GVarFlags.MaybeReadOnly = Flag; 10395 break; 10396 case lltok::kw_writeonly: 10397 if (ParseRest(Flag)) 10398 return true; 10399 GVarFlags.MaybeWriteOnly = Flag; 10400 break; 10401 case lltok::kw_constant: 10402 if (ParseRest(Flag)) 10403 return true; 10404 GVarFlags.Constant = Flag; 10405 break; 10406 case lltok::kw_vcall_visibility: 10407 if (ParseRest(Flag)) 10408 return true; 10409 GVarFlags.VCallVisibility = Flag; 10410 break; 10411 default: 10412 return error(Lex.getLoc(), "expected gvar flag type"); 10413 } 10414 } while (EatIfPresent(lltok::comma)); 10415 return parseToken(lltok::rparen, "expected ')' here"); 10416 } 10417 10418 /// ModuleReference 10419 /// ::= 'module' ':' UInt 10420 bool LLParser::parseModuleReference(StringRef &ModulePath) { 10421 // parse module id. 10422 if (parseToken(lltok::kw_module, "expected 'module' here") || 10423 parseToken(lltok::colon, "expected ':' here") || 10424 parseToken(lltok::SummaryID, "expected module ID")) 10425 return true; 10426 10427 unsigned ModuleID = Lex.getUIntVal(); 10428 auto I = ModuleIdMap.find(ModuleID); 10429 // We should have already parsed all module IDs 10430 assert(I != ModuleIdMap.end()); 10431 ModulePath = I->second; 10432 return false; 10433 } 10434 10435 /// GVReference 10436 /// ::= SummaryID 10437 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) { 10438 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly); 10439 if (!ReadOnly) 10440 WriteOnly = EatIfPresent(lltok::kw_writeonly); 10441 if (parseToken(lltok::SummaryID, "expected GV ID")) 10442 return true; 10443 10444 GVId = Lex.getUIntVal(); 10445 // Check if we already have a VI for this GV 10446 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) { 10447 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef); 10448 VI = NumberedValueInfos[GVId]; 10449 } else 10450 // We will create a forward reference to the stored location. 10451 VI = ValueInfo(false, FwdVIRef); 10452 10453 if (ReadOnly) 10454 VI.setReadOnly(); 10455 if (WriteOnly) 10456 VI.setWriteOnly(); 10457 return false; 10458 } 10459 10460 /// OptionalAllocs 10461 /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')' 10462 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')' 10463 /// ',' MemProfs ')' 10464 /// Version ::= UInt32 10465 bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) { 10466 assert(Lex.getKind() == lltok::kw_allocs); 10467 Lex.Lex(); 10468 10469 if (parseToken(lltok::colon, "expected ':' in allocs") || 10470 parseToken(lltok::lparen, "expected '(' in allocs")) 10471 return true; 10472 10473 // parse each alloc 10474 do { 10475 if (parseToken(lltok::lparen, "expected '(' in alloc") || 10476 parseToken(lltok::kw_versions, "expected 'versions' in alloc") || 10477 parseToken(lltok::colon, "expected ':'") || 10478 parseToken(lltok::lparen, "expected '(' in versions")) 10479 return true; 10480 10481 SmallVector<uint8_t> Versions; 10482 do { 10483 uint8_t V = 0; 10484 if (parseAllocType(V)) 10485 return true; 10486 Versions.push_back(V); 10487 } while (EatIfPresent(lltok::comma)); 10488 10489 if (parseToken(lltok::rparen, "expected ')' in versions") || 10490 parseToken(lltok::comma, "expected ',' in alloc")) 10491 return true; 10492 10493 std::vector<MIBInfo> MIBs; 10494 if (parseMemProfs(MIBs)) 10495 return true; 10496 10497 Allocs.push_back({Versions, MIBs}); 10498 10499 if (parseToken(lltok::rparen, "expected ')' in alloc")) 10500 return true; 10501 } while (EatIfPresent(lltok::comma)); 10502 10503 if (parseToken(lltok::rparen, "expected ')' in allocs")) 10504 return true; 10505 10506 return false; 10507 } 10508 10509 /// MemProfs 10510 /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')' 10511 /// MemProf ::= '(' 'type' ':' AllocType 10512 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')' 10513 /// StackId ::= UInt64 10514 bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) { 10515 assert(Lex.getKind() == lltok::kw_memProf); 10516 Lex.Lex(); 10517 10518 if (parseToken(lltok::colon, "expected ':' in memprof") || 10519 parseToken(lltok::lparen, "expected '(' in memprof")) 10520 return true; 10521 10522 // parse each MIB 10523 do { 10524 if (parseToken(lltok::lparen, "expected '(' in memprof") || 10525 parseToken(lltok::kw_type, "expected 'type' in memprof") || 10526 parseToken(lltok::colon, "expected ':'")) 10527 return true; 10528 10529 uint8_t AllocType; 10530 if (parseAllocType(AllocType)) 10531 return true; 10532 10533 if (parseToken(lltok::comma, "expected ',' in memprof") || 10534 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") || 10535 parseToken(lltok::colon, "expected ':'") || 10536 parseToken(lltok::lparen, "expected '(' in stackIds")) 10537 return true; 10538 10539 SmallVector<unsigned> StackIdIndices; 10540 do { 10541 uint64_t StackId = 0; 10542 if (parseUInt64(StackId)) 10543 return true; 10544 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId)); 10545 } while (EatIfPresent(lltok::comma)); 10546 10547 if (parseToken(lltok::rparen, "expected ')' in stackIds")) 10548 return true; 10549 10550 MIBs.push_back({(AllocationType)AllocType, StackIdIndices}); 10551 10552 if (parseToken(lltok::rparen, "expected ')' in memprof")) 10553 return true; 10554 } while (EatIfPresent(lltok::comma)); 10555 10556 if (parseToken(lltok::rparen, "expected ')' in memprof")) 10557 return true; 10558 10559 return false; 10560 } 10561 10562 /// AllocType 10563 /// := ('none'|'notcold'|'cold'|'hot') 10564 bool LLParser::parseAllocType(uint8_t &AllocType) { 10565 switch (Lex.getKind()) { 10566 case lltok::kw_none: 10567 AllocType = (uint8_t)AllocationType::None; 10568 break; 10569 case lltok::kw_notcold: 10570 AllocType = (uint8_t)AllocationType::NotCold; 10571 break; 10572 case lltok::kw_cold: 10573 AllocType = (uint8_t)AllocationType::Cold; 10574 break; 10575 case lltok::kw_hot: 10576 AllocType = (uint8_t)AllocationType::Hot; 10577 break; 10578 default: 10579 return error(Lex.getLoc(), "invalid alloc type"); 10580 } 10581 Lex.Lex(); 10582 return false; 10583 } 10584 10585 /// OptionalCallsites 10586 /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')' 10587 /// Callsite ::= '(' 'callee' ':' GVReference 10588 /// ',' 'clones' ':' '(' Version [',' Version]* ')' 10589 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')' 10590 /// Version ::= UInt32 10591 /// StackId ::= UInt64 10592 bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) { 10593 assert(Lex.getKind() == lltok::kw_callsites); 10594 Lex.Lex(); 10595 10596 if (parseToken(lltok::colon, "expected ':' in callsites") || 10597 parseToken(lltok::lparen, "expected '(' in callsites")) 10598 return true; 10599 10600 IdToIndexMapType IdToIndexMap; 10601 // parse each callsite 10602 do { 10603 if (parseToken(lltok::lparen, "expected '(' in callsite") || 10604 parseToken(lltok::kw_callee, "expected 'callee' in callsite") || 10605 parseToken(lltok::colon, "expected ':'")) 10606 return true; 10607 10608 ValueInfo VI; 10609 unsigned GVId = 0; 10610 LocTy Loc = Lex.getLoc(); 10611 if (!EatIfPresent(lltok::kw_null)) { 10612 if (parseGVReference(VI, GVId)) 10613 return true; 10614 } 10615 10616 if (parseToken(lltok::comma, "expected ',' in callsite") || 10617 parseToken(lltok::kw_clones, "expected 'clones' in callsite") || 10618 parseToken(lltok::colon, "expected ':'") || 10619 parseToken(lltok::lparen, "expected '(' in clones")) 10620 return true; 10621 10622 SmallVector<unsigned> Clones; 10623 do { 10624 unsigned V = 0; 10625 if (parseUInt32(V)) 10626 return true; 10627 Clones.push_back(V); 10628 } while (EatIfPresent(lltok::comma)); 10629 10630 if (parseToken(lltok::rparen, "expected ')' in clones") || 10631 parseToken(lltok::comma, "expected ',' in callsite") || 10632 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") || 10633 parseToken(lltok::colon, "expected ':'") || 10634 parseToken(lltok::lparen, "expected '(' in stackIds")) 10635 return true; 10636 10637 SmallVector<unsigned> StackIdIndices; 10638 do { 10639 uint64_t StackId = 0; 10640 if (parseUInt64(StackId)) 10641 return true; 10642 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId)); 10643 } while (EatIfPresent(lltok::comma)); 10644 10645 if (parseToken(lltok::rparen, "expected ')' in stackIds")) 10646 return true; 10647 10648 // Keep track of the Callsites array index needing a forward reference. 10649 // We will save the location of the ValueInfo needing an update, but 10650 // can only do so once the SmallVector is finalized. 10651 if (VI.getRef() == FwdVIRef) 10652 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc)); 10653 Callsites.push_back({VI, Clones, StackIdIndices}); 10654 10655 if (parseToken(lltok::rparen, "expected ')' in callsite")) 10656 return true; 10657 } while (EatIfPresent(lltok::comma)); 10658 10659 // Now that the Callsites vector is finalized, it is safe to save the 10660 // locations of any forward GV references that need updating later. 10661 for (auto I : IdToIndexMap) { 10662 auto &Infos = ForwardRefValueInfos[I.first]; 10663 for (auto P : I.second) { 10664 assert(Callsites[P.first].Callee.getRef() == FwdVIRef && 10665 "Forward referenced ValueInfo expected to be empty"); 10666 Infos.emplace_back(&Callsites[P.first].Callee, P.second); 10667 } 10668 } 10669 10670 if (parseToken(lltok::rparen, "expected ')' in callsites")) 10671 return true; 10672 10673 return false; 10674 } 10675