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