Path: blob/main/contrib/llvm-project/llvm/lib/AsmParser/LLParser.cpp
35233 views
//===-- LLParser.cpp - Parser Class ---------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file defines the parser class for .ll files.9//10//===----------------------------------------------------------------------===//1112#include "llvm/AsmParser/LLParser.h"13#include "llvm/ADT/APSInt.h"14#include "llvm/ADT/DenseMap.h"15#include "llvm/ADT/STLExtras.h"16#include "llvm/ADT/ScopeExit.h"17#include "llvm/ADT/SmallPtrSet.h"18#include "llvm/AsmParser/LLToken.h"19#include "llvm/AsmParser/SlotMapping.h"20#include "llvm/BinaryFormat/Dwarf.h"21#include "llvm/IR/Argument.h"22#include "llvm/IR/AutoUpgrade.h"23#include "llvm/IR/BasicBlock.h"24#include "llvm/IR/CallingConv.h"25#include "llvm/IR/Comdat.h"26#include "llvm/IR/ConstantRange.h"27#include "llvm/IR/ConstantRangeList.h"28#include "llvm/IR/Constants.h"29#include "llvm/IR/DebugInfoMetadata.h"30#include "llvm/IR/DerivedTypes.h"31#include "llvm/IR/Function.h"32#include "llvm/IR/GlobalIFunc.h"33#include "llvm/IR/GlobalObject.h"34#include "llvm/IR/InlineAsm.h"35#include "llvm/IR/InstIterator.h"36#include "llvm/IR/Instructions.h"37#include "llvm/IR/IntrinsicInst.h"38#include "llvm/IR/Intrinsics.h"39#include "llvm/IR/LLVMContext.h"40#include "llvm/IR/Metadata.h"41#include "llvm/IR/Module.h"42#include "llvm/IR/Operator.h"43#include "llvm/IR/Value.h"44#include "llvm/IR/ValueSymbolTable.h"45#include "llvm/Support/Casting.h"46#include "llvm/Support/ErrorHandling.h"47#include "llvm/Support/MathExtras.h"48#include "llvm/Support/ModRef.h"49#include "llvm/Support/SaveAndRestore.h"50#include "llvm/Support/raw_ostream.h"51#include <algorithm>52#include <cassert>53#include <cstring>54#include <optional>55#include <vector>5657using namespace llvm;5859static cl::opt<bool> AllowIncompleteIR(60"allow-incomplete-ir", cl::init(false), cl::Hidden,61cl::desc(62"Allow incomplete IR on a best effort basis (references to unknown "63"metadata will be dropped)"));6465extern llvm::cl::opt<bool> UseNewDbgInfoFormat;66extern cl::opt<cl::boolOrDefault> PreserveInputDbgFormat;67extern bool WriteNewDbgInfoFormatToBitcode;68extern cl::opt<bool> WriteNewDbgInfoFormat;6970static std::string getTypeString(Type *T) {71std::string Result;72raw_string_ostream Tmp(Result);73Tmp << *T;74return Tmp.str();75}7677/// Run: module ::= toplevelentity*78bool LLParser::Run(bool UpgradeDebugInfo,79DataLayoutCallbackTy DataLayoutCallback) {80// Prime the lexer.81Lex.Lex();8283if (Context.shouldDiscardValueNames())84return error(85Lex.getLoc(),86"Can't read textual IR with a Context that discards named Values");8788if (M) {89if (parseTargetDefinitions(DataLayoutCallback))90return true;91}9293return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||94validateEndOfIndex();95}9697bool LLParser::parseStandaloneConstantValue(Constant *&C,98const SlotMapping *Slots) {99restoreParsingState(Slots);100Lex.Lex();101102Type *Ty = nullptr;103if (parseType(Ty) || parseConstantValue(Ty, C))104return true;105if (Lex.getKind() != lltok::Eof)106return error(Lex.getLoc(), "expected end of string");107return false;108}109110bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,111const SlotMapping *Slots) {112restoreParsingState(Slots);113Lex.Lex();114115Read = 0;116SMLoc Start = Lex.getLoc();117Ty = nullptr;118if (parseType(Ty))119return true;120SMLoc End = Lex.getLoc();121Read = End.getPointer() - Start.getPointer();122123return false;124}125126bool LLParser::parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read,127const SlotMapping *Slots) {128restoreParsingState(Slots);129Lex.Lex();130131Read = 0;132SMLoc Start = Lex.getLoc();133Result = nullptr;134bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);135SMLoc End = Lex.getLoc();136Read = End.getPointer() - Start.getPointer();137138return Status;139}140141void LLParser::restoreParsingState(const SlotMapping *Slots) {142if (!Slots)143return;144NumberedVals = Slots->GlobalValues;145NumberedMetadata = Slots->MetadataNodes;146for (const auto &I : Slots->NamedTypes)147NamedTypes.insert(148std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));149for (const auto &I : Slots->Types)150NumberedTypes.insert(151std::make_pair(I.first, std::make_pair(I.second, LocTy())));152}153154static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II) {155// White-list intrinsics that are safe to drop.156if (!isa<DbgInfoIntrinsic>(II) &&157II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)158return;159160SmallVector<MetadataAsValue *> MVs;161for (Value *V : II->args())162if (auto *MV = dyn_cast<MetadataAsValue>(V))163if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))164if (MD->isTemporary())165MVs.push_back(MV);166167if (!MVs.empty()) {168assert(II->use_empty() && "Cannot have uses");169II->eraseFromParent();170171// Also remove no longer used MetadataAsValue wrappers.172for (MetadataAsValue *MV : MVs)173if (MV->use_empty())174delete MV;175}176}177178void LLParser::dropUnknownMetadataReferences() {179auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };180for (Function &F : *M) {181F.eraseMetadataIf(Pred);182for (Instruction &I : make_early_inc_range(instructions(F))) {183I.eraseMetadataIf(Pred);184185if (auto *II = dyn_cast<IntrinsicInst>(&I))186dropIntrinsicWithUnknownMetadataArgument(II);187}188}189190for (GlobalVariable &GV : M->globals())191GV.eraseMetadataIf(Pred);192193for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {194// Check whether there is only a single use left, which would be in our195// own NumberedMetadata.196if (Info.first->getNumTemporaryUses() == 1) {197NumberedMetadata.erase(ID);198ForwardRefMDNodes.erase(ID);199}200}201}202203/// validateEndOfModule - Do final validity and basic correctness checks at the204/// end of the module.205bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {206if (!M)207return false;208209// We should have already returned an error if we observed both intrinsics and210// records in this IR.211assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&212"Mixed debug intrinsics/records seen without a parsing error?");213if (PreserveInputDbgFormat == cl::boolOrDefault::BOU_TRUE) {214UseNewDbgInfoFormat = SeenNewDbgInfoFormat;215WriteNewDbgInfoFormatToBitcode = SeenNewDbgInfoFormat;216WriteNewDbgInfoFormat = SeenNewDbgInfoFormat;217M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);218}219220// Handle any function attribute group forward references.221for (const auto &RAG : ForwardRefAttrGroups) {222Value *V = RAG.first;223const std::vector<unsigned> &Attrs = RAG.second;224AttrBuilder B(Context);225226for (const auto &Attr : Attrs) {227auto R = NumberedAttrBuilders.find(Attr);228if (R != NumberedAttrBuilders.end())229B.merge(R->second);230}231232if (Function *Fn = dyn_cast<Function>(V)) {233AttributeList AS = Fn->getAttributes();234AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());235AS = AS.removeFnAttributes(Context);236237FnAttrs.merge(B);238239// If the alignment was parsed as an attribute, move to the alignment240// field.241if (MaybeAlign A = FnAttrs.getAlignment()) {242Fn->setAlignment(*A);243FnAttrs.removeAttribute(Attribute::Alignment);244}245246AS = AS.addFnAttributes(Context, FnAttrs);247Fn->setAttributes(AS);248} else if (CallInst *CI = dyn_cast<CallInst>(V)) {249AttributeList AS = CI->getAttributes();250AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());251AS = AS.removeFnAttributes(Context);252FnAttrs.merge(B);253AS = AS.addFnAttributes(Context, FnAttrs);254CI->setAttributes(AS);255} else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {256AttributeList AS = II->getAttributes();257AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());258AS = AS.removeFnAttributes(Context);259FnAttrs.merge(B);260AS = AS.addFnAttributes(Context, FnAttrs);261II->setAttributes(AS);262} else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {263AttributeList AS = CBI->getAttributes();264AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());265AS = AS.removeFnAttributes(Context);266FnAttrs.merge(B);267AS = AS.addFnAttributes(Context, FnAttrs);268CBI->setAttributes(AS);269} else if (auto *GV = dyn_cast<GlobalVariable>(V)) {270AttrBuilder Attrs(M->getContext(), GV->getAttributes());271Attrs.merge(B);272GV->setAttributes(AttributeSet::get(Context,Attrs));273} else {274llvm_unreachable("invalid object with forward attribute group reference");275}276}277278// If there are entries in ForwardRefBlockAddresses at this point, the279// function was never defined.280if (!ForwardRefBlockAddresses.empty())281return error(ForwardRefBlockAddresses.begin()->first.Loc,282"expected function name in blockaddress");283284auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,285GlobalValue *FwdRef) {286GlobalValue *GV = nullptr;287if (GVRef.Kind == ValID::t_GlobalName) {288GV = M->getNamedValue(GVRef.StrVal);289} else {290GV = NumberedVals.get(GVRef.UIntVal);291}292293if (!GV)294return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +295"' referenced by dso_local_equivalent");296297if (!GV->getValueType()->isFunctionTy())298return error(GVRef.Loc,299"expected a function, alias to function, or ifunc "300"in dso_local_equivalent");301302auto *Equiv = DSOLocalEquivalent::get(GV);303FwdRef->replaceAllUsesWith(Equiv);304FwdRef->eraseFromParent();305return false;306};307308// If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this309// point, they are references after the function was defined. Resolve those310// now.311for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {312if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))313return true;314}315for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {316if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))317return true;318}319ForwardRefDSOLocalEquivalentIDs.clear();320ForwardRefDSOLocalEquivalentNames.clear();321322for (const auto &NT : NumberedTypes)323if (NT.second.second.isValid())324return error(NT.second.second,325"use of undefined type '%" + Twine(NT.first) + "'");326327for (StringMap<std::pair<Type*, LocTy> >::iterator I =328NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)329if (I->second.second.isValid())330return error(I->second.second,331"use of undefined type named '" + I->getKey() + "'");332333if (!ForwardRefComdats.empty())334return error(ForwardRefComdats.begin()->second,335"use of undefined comdat '$" +336ForwardRefComdats.begin()->first + "'");337338for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {339if (StringRef(Name).starts_with("llvm.")) {340Intrinsic::ID IID = Function::lookupIntrinsicID(Name);341if (IID == Intrinsic::not_intrinsic)342// Don't do anything for unknown intrinsics.343continue;344345// Automatically create declarations for intrinsics. Intrinsics can only346// be called directly, so the call function type directly determines the347// declaration function type.348//349// Additionally, automatically add the required mangling suffix to the350// intrinsic name. This means that we may replace a single forward351// declaration with multiple functions here.352for (Use &U : make_early_inc_range(Info.first->uses())) {353auto *CB = dyn_cast<CallBase>(U.getUser());354if (!CB || !CB->isCallee(&U))355return error(Info.second, "intrinsic can only be used as callee");356357SmallVector<Type *> OverloadTys;358if (!Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),359OverloadTys))360return error(Info.second, "invalid intrinsic signature");361362U.set(Intrinsic::getDeclaration(M, IID, OverloadTys));363}364365Info.first->eraseFromParent();366ForwardRefVals.erase(Name);367continue;368}369370// If incomplete IR is allowed, also add declarations for371// non-intrinsics.372if (!AllowIncompleteIR)373continue;374375auto GetCommonFunctionType = [](Value *V) -> FunctionType * {376FunctionType *FTy = nullptr;377for (Use &U : V->uses()) {378auto *CB = dyn_cast<CallBase>(U.getUser());379if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))380return nullptr;381FTy = CB->getFunctionType();382}383return FTy;384};385386// First check whether this global is only used in calls with the same387// type, in which case we'll insert a function. Otherwise, fall back to388// using a dummy i8 type.389Type *Ty = GetCommonFunctionType(Info.first);390if (!Ty)391Ty = Type::getInt8Ty(Context);392393GlobalValue *GV;394if (auto *FTy = dyn_cast<FunctionType>(Ty))395GV = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);396else397GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,398GlobalValue::ExternalLinkage,399/*Initializer*/ nullptr, Name);400Info.first->replaceAllUsesWith(GV);401Info.first->eraseFromParent();402ForwardRefVals.erase(Name);403}404405if (!ForwardRefVals.empty())406return error(ForwardRefVals.begin()->second.second,407"use of undefined value '@" + ForwardRefVals.begin()->first +408"'");409410if (!ForwardRefValIDs.empty())411return error(ForwardRefValIDs.begin()->second.second,412"use of undefined value '@" +413Twine(ForwardRefValIDs.begin()->first) + "'");414415if (AllowIncompleteIR && !ForwardRefMDNodes.empty())416dropUnknownMetadataReferences();417418if (!ForwardRefMDNodes.empty())419return error(ForwardRefMDNodes.begin()->second.second,420"use of undefined metadata '!" +421Twine(ForwardRefMDNodes.begin()->first) + "'");422423// Resolve metadata cycles.424for (auto &N : NumberedMetadata) {425if (N.second && !N.second->isResolved())426N.second->resolveCycles();427}428429for (auto *Inst : InstsWithTBAATag) {430MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);431// With incomplete IR, the tbaa metadata may have been dropped.432if (!AllowIncompleteIR)433assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");434if (MD) {435auto *UpgradedMD = UpgradeTBAANode(*MD);436if (MD != UpgradedMD)437Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);438}439}440441// Look for intrinsic functions and CallInst that need to be upgraded. We use442// make_early_inc_range here because we may remove some functions.443for (Function &F : llvm::make_early_inc_range(*M))444UpgradeCallsToIntrinsic(&F);445446if (UpgradeDebugInfo)447llvm::UpgradeDebugInfo(*M);448449UpgradeModuleFlags(*M);450UpgradeSectionAttributes(*M);451452if (PreserveInputDbgFormat != cl::boolOrDefault::BOU_TRUE)453M->setIsNewDbgInfoFormat(UseNewDbgInfoFormat);454455if (!Slots)456return 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.460Slots->GlobalValues = std::move(NumberedVals);461Slots->MetadataNodes = std::move(NumberedMetadata);462for (const auto &I : NamedTypes)463Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));464for (const auto &I : NumberedTypes)465Slots->Types.insert(std::make_pair(I.first, I.second.first));466467return false;468}469470/// Do final validity and basic correctness checks at the end of the index.471bool LLParser::validateEndOfIndex() {472if (!Index)473return false;474475if (!ForwardRefValueInfos.empty())476return error(ForwardRefValueInfos.begin()->second.front().second,477"use of undefined summary '^" +478Twine(ForwardRefValueInfos.begin()->first) + "'");479480if (!ForwardRefAliasees.empty())481return error(ForwardRefAliasees.begin()->second.front().second,482"use of undefined summary '^" +483Twine(ForwardRefAliasees.begin()->first) + "'");484485if (!ForwardRefTypeIds.empty())486return error(ForwardRefTypeIds.begin()->second.front().second,487"use of undefined type id summary '^" +488Twine(ForwardRefTypeIds.begin()->first) + "'");489490return false;491}492493//===----------------------------------------------------------------------===//494// Top-Level Entities495//===----------------------------------------------------------------------===//496497bool 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.502std::string TentativeDLStr = M->getDataLayoutStr();503LocTy DLStrLoc;504505bool Done = false;506while (!Done) {507switch (Lex.getKind()) {508case lltok::kw_target:509if (parseTargetDefinition(TentativeDLStr, DLStrLoc))510return true;511break;512case lltok::kw_source_filename:513if (parseSourceFileName())514return true;515break;516default:517Done = true;518}519}520// Run the override callback to potentially change the data layout string, and521// parse the data layout string.522if (auto LayoutOverride =523DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {524TentativeDLStr = *LayoutOverride;525DLStrLoc = {};526}527Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);528if (!MaybeDL)529return error(DLStrLoc, toString(MaybeDL.takeError()));530M->setDataLayout(MaybeDL.get());531return false;532}533534bool LLParser::parseTopLevelEntities() {535// If there is no Module, then parse just the summary index entries.536if (!M) {537while (true) {538switch (Lex.getKind()) {539case lltok::Eof:540return false;541case lltok::SummaryID:542if (parseSummaryEntry())543return true;544break;545case lltok::kw_source_filename:546if (parseSourceFileName())547return true;548break;549default:550// Skip everything else551Lex.Lex();552}553}554}555while (true) {556switch (Lex.getKind()) {557default:558return tokError("expected top-level entity");559case lltok::Eof: return false;560case lltok::kw_declare:561if (parseDeclare())562return true;563break;564case lltok::kw_define:565if (parseDefine())566return true;567break;568case lltok::kw_module:569if (parseModuleAsm())570return true;571break;572case lltok::LocalVarID:573if (parseUnnamedType())574return true;575break;576case lltok::LocalVar:577if (parseNamedType())578return true;579break;580case lltok::GlobalID:581if (parseUnnamedGlobal())582return true;583break;584case lltok::GlobalVar:585if (parseNamedGlobal())586return true;587break;588case lltok::ComdatVar: if (parseComdat()) return true; break;589case lltok::exclaim:590if (parseStandaloneMetadata())591return true;592break;593case lltok::SummaryID:594if (parseSummaryEntry())595return true;596break;597case lltok::MetadataVar:598if (parseNamedMetadata())599return true;600break;601case lltok::kw_attributes:602if (parseUnnamedAttrGrp())603return true;604break;605case lltok::kw_uselistorder:606if (parseUseListOrder())607return true;608break;609case lltok::kw_uselistorder_bb:610if (parseUseListOrderBB())611return true;612break;613}614}615}616617/// toplevelentity618/// ::= 'module' 'asm' STRINGCONSTANT619bool LLParser::parseModuleAsm() {620assert(Lex.getKind() == lltok::kw_module);621Lex.Lex();622623std::string AsmStr;624if (parseToken(lltok::kw_asm, "expected 'module asm'") ||625parseStringConstant(AsmStr))626return true;627628M->appendModuleInlineAsm(AsmStr);629return false;630}631632/// toplevelentity633/// ::= 'target' 'triple' '=' STRINGCONSTANT634/// ::= 'target' 'datalayout' '=' STRINGCONSTANT635bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,636LocTy &DLStrLoc) {637assert(Lex.getKind() == lltok::kw_target);638std::string Str;639switch (Lex.Lex()) {640default:641return tokError("unknown target property");642case lltok::kw_triple:643Lex.Lex();644if (parseToken(lltok::equal, "expected '=' after target triple") ||645parseStringConstant(Str))646return true;647M->setTargetTriple(Str);648return false;649case lltok::kw_datalayout:650Lex.Lex();651if (parseToken(lltok::equal, "expected '=' after target datalayout"))652return true;653DLStrLoc = Lex.getLoc();654if (parseStringConstant(TentativeDLStr))655return true;656return false;657}658}659660/// toplevelentity661/// ::= 'source_filename' '=' STRINGCONSTANT662bool LLParser::parseSourceFileName() {663assert(Lex.getKind() == lltok::kw_source_filename);664Lex.Lex();665if (parseToken(lltok::equal, "expected '=' after source_filename") ||666parseStringConstant(SourceFileName))667return true;668if (M)669M->setSourceFileName(SourceFileName);670return false;671}672673/// parseUnnamedType:674/// ::= LocalVarID '=' 'type' type675bool LLParser::parseUnnamedType() {676LocTy TypeLoc = Lex.getLoc();677unsigned TypeID = Lex.getUIntVal();678Lex.Lex(); // eat LocalVarID;679680if (parseToken(lltok::equal, "expected '=' after name") ||681parseToken(lltok::kw_type, "expected 'type' after '='"))682return true;683684Type *Result = nullptr;685if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))686return true;687688if (!isa<StructType>(Result)) {689std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];690if (Entry.first)691return error(TypeLoc, "non-struct types may not be recursive");692Entry.first = Result;693Entry.second = SMLoc();694}695696return false;697}698699/// toplevelentity700/// ::= LocalVar '=' 'type' type701bool LLParser::parseNamedType() {702std::string Name = Lex.getStrVal();703LocTy NameLoc = Lex.getLoc();704Lex.Lex(); // eat LocalVar.705706if (parseToken(lltok::equal, "expected '=' after name") ||707parseToken(lltok::kw_type, "expected 'type' after name"))708return true;709710Type *Result = nullptr;711if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))712return true;713714if (!isa<StructType>(Result)) {715std::pair<Type*, LocTy> &Entry = NamedTypes[Name];716if (Entry.first)717return error(NameLoc, "non-struct types may not be recursive");718Entry.first = Result;719Entry.second = SMLoc();720}721722return false;723}724725/// toplevelentity726/// ::= 'declare' FunctionHeader727bool LLParser::parseDeclare() {728assert(Lex.getKind() == lltok::kw_declare);729Lex.Lex();730731std::vector<std::pair<unsigned, MDNode *>> MDs;732while (Lex.getKind() == lltok::MetadataVar) {733unsigned MDK;734MDNode *N;735if (parseMetadataAttachment(MDK, N))736return true;737MDs.push_back({MDK, N});738}739740Function *F;741unsigned FunctionNumber = -1;742SmallVector<unsigned> UnnamedArgNums;743if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))744return true;745for (auto &MD : MDs)746F->addMetadata(MD.first, *MD.second);747return false;748}749750/// toplevelentity751/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...752bool LLParser::parseDefine() {753assert(Lex.getKind() == lltok::kw_define);754Lex.Lex();755756Function *F;757unsigned FunctionNumber = -1;758SmallVector<unsigned> UnnamedArgNums;759return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||760parseOptionalFunctionMetadata(*F) ||761parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);762}763764/// parseGlobalType765/// ::= 'constant'766/// ::= 'global'767bool LLParser::parseGlobalType(bool &IsConstant) {768if (Lex.getKind() == lltok::kw_constant)769IsConstant = true;770else if (Lex.getKind() == lltok::kw_global)771IsConstant = false;772else {773IsConstant = false;774return tokError("expected 'global' or 'constant'");775}776Lex.Lex();777return false;778}779780bool LLParser::parseOptionalUnnamedAddr(781GlobalVariable::UnnamedAddr &UnnamedAddr) {782if (EatIfPresent(lltok::kw_unnamed_addr))783UnnamedAddr = GlobalValue::UnnamedAddr::Global;784else if (EatIfPresent(lltok::kw_local_unnamed_addr))785UnnamedAddr = GlobalValue::UnnamedAddr::Local;786else787UnnamedAddr = GlobalValue::UnnamedAddr::None;788return false;789}790791/// parseUnnamedGlobal:792/// OptionalVisibility (ALIAS | IFUNC) ...793/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility794/// OptionalDLLStorageClass795/// ... -> global variable796/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...797/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier798/// OptionalVisibility799/// OptionalDLLStorageClass800/// ... -> global variable801bool LLParser::parseUnnamedGlobal() {802unsigned VarID;803std::string Name;804LocTy NameLoc = Lex.getLoc();805806// Handle the GlobalID form.807if (Lex.getKind() == lltok::GlobalID) {808VarID = Lex.getUIntVal();809if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))810return true;811812Lex.Lex(); // eat GlobalID;813if (parseToken(lltok::equal, "expected '=' after name"))814return true;815} else {816VarID = NumberedVals.getNext();817}818819bool HasLinkage;820unsigned Linkage, Visibility, DLLStorageClass;821bool DSOLocal;822GlobalVariable::ThreadLocalMode TLM;823GlobalVariable::UnnamedAddr UnnamedAddr;824if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,825DSOLocal) ||826parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))827return true;828829switch (Lex.getKind()) {830default:831return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,832DLLStorageClass, DSOLocal, TLM, UnnamedAddr);833case lltok::kw_alias:834case lltok::kw_ifunc:835return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,836DLLStorageClass, DSOLocal, TLM, UnnamedAddr);837}838}839840/// parseNamedGlobal:841/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...842/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier843/// OptionalVisibility OptionalDLLStorageClass844/// ... -> global variable845bool LLParser::parseNamedGlobal() {846assert(Lex.getKind() == lltok::GlobalVar);847LocTy NameLoc = Lex.getLoc();848std::string Name = Lex.getStrVal();849Lex.Lex();850851bool HasLinkage;852unsigned Linkage, Visibility, DLLStorageClass;853bool DSOLocal;854GlobalVariable::ThreadLocalMode TLM;855GlobalVariable::UnnamedAddr UnnamedAddr;856if (parseToken(lltok::equal, "expected '=' in global variable") ||857parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,858DSOLocal) ||859parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))860return true;861862switch (Lex.getKind()) {863default:864return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,865DLLStorageClass, DSOLocal, TLM, UnnamedAddr);866case lltok::kw_alias:867case lltok::kw_ifunc:868return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,869DLLStorageClass, DSOLocal, TLM, UnnamedAddr);870}871}872873bool LLParser::parseComdat() {874assert(Lex.getKind() == lltok::ComdatVar);875std::string Name = Lex.getStrVal();876LocTy NameLoc = Lex.getLoc();877Lex.Lex();878879if (parseToken(lltok::equal, "expected '=' here"))880return true;881882if (parseToken(lltok::kw_comdat, "expected comdat keyword"))883return tokError("expected comdat type");884885Comdat::SelectionKind SK;886switch (Lex.getKind()) {887default:888return tokError("unknown selection kind");889case lltok::kw_any:890SK = Comdat::Any;891break;892case lltok::kw_exactmatch:893SK = Comdat::ExactMatch;894break;895case lltok::kw_largest:896SK = Comdat::Largest;897break;898case lltok::kw_nodeduplicate:899SK = Comdat::NoDeduplicate;900break;901case lltok::kw_samesize:902SK = Comdat::SameSize;903break;904}905Lex.Lex();906907// See if the comdat was forward referenced, if so, use the comdat.908Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();909Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);910if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))911return error(NameLoc, "redefinition of comdat '$" + Name + "'");912913Comdat *C;914if (I != ComdatSymTab.end())915C = &I->second;916else917C = M->getOrInsertComdat(Name);918C->setSelectionKind(SK);919920return false;921}922923// MDString:924// ::= '!' STRINGCONSTANT925bool LLParser::parseMDString(MDString *&Result) {926std::string Str;927if (parseStringConstant(Str))928return true;929Result = MDString::get(Context, Str);930return false;931}932933// MDNode:934// ::= '!' MDNodeNumber935bool LLParser::parseMDNodeID(MDNode *&Result) {936// !{ ..., !42, ... }937LocTy IDLoc = Lex.getLoc();938unsigned MID = 0;939if (parseUInt32(MID))940return true;941942// If not a forward reference, just return it now.943if (NumberedMetadata.count(MID)) {944Result = NumberedMetadata[MID];945return false;946}947948// Otherwise, create MDNode forward reference.949auto &FwdRef = ForwardRefMDNodes[MID];950FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);951952Result = FwdRef.first.get();953NumberedMetadata[MID].reset(Result);954return false;955}956957/// parseNamedMetadata:958/// !foo = !{ !1, !2 }959bool LLParser::parseNamedMetadata() {960assert(Lex.getKind() == lltok::MetadataVar);961std::string Name = Lex.getStrVal();962Lex.Lex();963964if (parseToken(lltok::equal, "expected '=' here") ||965parseToken(lltok::exclaim, "Expected '!' here") ||966parseToken(lltok::lbrace, "Expected '{' here"))967return true;968969NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);970if (Lex.getKind() != lltok::rbrace)971do {972MDNode *N = nullptr;973// parse DIExpressions inline as a special case. They are still MDNodes,974// so they can still appear in named metadata. Remove this logic if they975// become plain Metadata.976if (Lex.getKind() == lltok::MetadataVar &&977Lex.getStrVal() == "DIExpression") {978if (parseDIExpression(N, /*IsDistinct=*/false))979return true;980// DIArgLists should only appear inline in a function, as they may981// contain LocalAsMetadata arguments which require a function context.982} else if (Lex.getKind() == lltok::MetadataVar &&983Lex.getStrVal() == "DIArgList") {984return tokError("found DIArgList outside of function");985} else if (parseToken(lltok::exclaim, "Expected '!' here") ||986parseMDNodeID(N)) {987return true;988}989NMD->addOperand(N);990} while (EatIfPresent(lltok::comma));991992return parseToken(lltok::rbrace, "expected end of metadata node");993}994995/// parseStandaloneMetadata:996/// !42 = !{...}997bool LLParser::parseStandaloneMetadata() {998assert(Lex.getKind() == lltok::exclaim);999Lex.Lex();1000unsigned MetadataID = 0;10011002MDNode *Init;1003if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))1004return true;10051006// Detect common error, from old metadata syntax.1007if (Lex.getKind() == lltok::Type)1008return tokError("unexpected type in metadata definition");10091010bool IsDistinct = EatIfPresent(lltok::kw_distinct);1011if (Lex.getKind() == lltok::MetadataVar) {1012if (parseSpecializedMDNode(Init, IsDistinct))1013return true;1014} else if (parseToken(lltok::exclaim, "Expected '!' here") ||1015parseMDTuple(Init, IsDistinct))1016return true;10171018// See if this was forward referenced, if so, handle it.1019auto FI = ForwardRefMDNodes.find(MetadataID);1020if (FI != ForwardRefMDNodes.end()) {1021auto *ToReplace = FI->second.first.get();1022// DIAssignID has its own special forward-reference "replacement" for1023// attachments (the temporary attachments are never actually attached).1024if (isa<DIAssignID>(Init)) {1025for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {1026assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&1027"Inst unexpectedly already has DIAssignID attachment");1028Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);1029}1030}10311032ToReplace->replaceAllUsesWith(Init);1033ForwardRefMDNodes.erase(FI);10341035assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");1036} else {1037if (NumberedMetadata.count(MetadataID))1038return tokError("Metadata id is already used");1039NumberedMetadata[MetadataID].reset(Init);1040}10411042return false;1043}10441045// Skips a single module summary entry.1046bool LLParser::skipModuleSummaryEntry() {1047// Each module summary entry consists of a tag for the entry1048// type, followed by a colon, then the fields which may be surrounded by1049// nested sets of parentheses. The "tag:" looks like a Label. Once parsing1050// support is in place we will look for the tokens corresponding to the1051// expected tags.1052if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&1053Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&1054Lex.getKind() != lltok::kw_blockcount)1055return tokError(1056"Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "1057"start of summary entry");1058if (Lex.getKind() == lltok::kw_flags)1059return parseSummaryIndexFlags();1060if (Lex.getKind() == lltok::kw_blockcount)1061return parseBlockCount();1062Lex.Lex();1063if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||1064parseToken(lltok::lparen, "expected '(' at start of summary entry"))1065return true;1066// Now walk through the parenthesized entry, until the number of open1067// parentheses goes back down to 0 (the first '(' was parsed above).1068unsigned NumOpenParen = 1;1069do {1070switch (Lex.getKind()) {1071case lltok::lparen:1072NumOpenParen++;1073break;1074case lltok::rparen:1075NumOpenParen--;1076break;1077case lltok::Eof:1078return tokError("found end of file while parsing summary entry");1079default:1080// Skip everything in between parentheses.1081break;1082}1083Lex.Lex();1084} while (NumOpenParen > 0);1085return false;1086}10871088/// SummaryEntry1089/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry1090bool LLParser::parseSummaryEntry() {1091assert(Lex.getKind() == lltok::SummaryID);1092unsigned SummaryID = Lex.getUIntVal();10931094// For summary entries, colons should be treated as distinct tokens,1095// not an indication of the end of a label token.1096Lex.setIgnoreColonInIdentifiers(true);10971098Lex.Lex();1099if (parseToken(lltok::equal, "expected '=' here"))1100return true;11011102// If we don't have an index object, skip the summary entry.1103if (!Index)1104return skipModuleSummaryEntry();11051106bool result = false;1107switch (Lex.getKind()) {1108case lltok::kw_gv:1109result = parseGVEntry(SummaryID);1110break;1111case lltok::kw_module:1112result = parseModuleEntry(SummaryID);1113break;1114case lltok::kw_typeid:1115result = parseTypeIdEntry(SummaryID);1116break;1117case lltok::kw_typeidCompatibleVTable:1118result = parseTypeIdCompatibleVtableEntry(SummaryID);1119break;1120case lltok::kw_flags:1121result = parseSummaryIndexFlags();1122break;1123case lltok::kw_blockcount:1124result = parseBlockCount();1125break;1126default:1127result = error(Lex.getLoc(), "unexpected summary kind");1128break;1129}1130Lex.setIgnoreColonInIdentifiers(false);1131return result;1132}11331134static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {1135return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||1136(GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;1137}1138static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {1139return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||1140(GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass;1141}11421143// If there was an explicit dso_local, update GV. In the absence of an explicit1144// dso_local we keep the default value.1145static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {1146if (DSOLocal)1147GV.setDSOLocal(true);1148}11491150/// parseAliasOrIFunc:1151/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier1152/// OptionalVisibility OptionalDLLStorageClass1153/// OptionalThreadLocal OptionalUnnamedAddr1154/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*1155///1156/// AliaseeOrResolver1157/// ::= TypeAndValue1158///1159/// SymbolAttrs1160/// ::= ',' 'partition' StringConstant1161///1162/// Everything through OptionalUnnamedAddr has already been parsed.1163///1164bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,1165LocTy NameLoc, unsigned L, unsigned Visibility,1166unsigned DLLStorageClass, bool DSOLocal,1167GlobalVariable::ThreadLocalMode TLM,1168GlobalVariable::UnnamedAddr UnnamedAddr) {1169bool IsAlias;1170if (Lex.getKind() == lltok::kw_alias)1171IsAlias = true;1172else if (Lex.getKind() == lltok::kw_ifunc)1173IsAlias = false;1174else1175llvm_unreachable("Not an alias or ifunc!");1176Lex.Lex();11771178GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;11791180if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))1181return error(NameLoc, "invalid linkage type for alias");11821183if (!isValidVisibilityForLinkage(Visibility, L))1184return error(NameLoc,1185"symbol with local linkage must have default visibility");11861187if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))1188return error(NameLoc,1189"symbol with local linkage cannot have a DLL storage class");11901191Type *Ty;1192LocTy ExplicitTypeLoc = Lex.getLoc();1193if (parseType(Ty) ||1194parseToken(lltok::comma, "expected comma after alias or ifunc's type"))1195return true;11961197Constant *Aliasee;1198LocTy AliaseeLoc = Lex.getLoc();1199if (Lex.getKind() != lltok::kw_bitcast &&1200Lex.getKind() != lltok::kw_getelementptr &&1201Lex.getKind() != lltok::kw_addrspacecast &&1202Lex.getKind() != lltok::kw_inttoptr) {1203if (parseGlobalTypeAndValue(Aliasee))1204return true;1205} else {1206// The bitcast dest type is not present, it is implied by the dest type.1207ValID ID;1208if (parseValID(ID, /*PFS=*/nullptr))1209return true;1210if (ID.Kind != ValID::t_Constant)1211return error(AliaseeLoc, "invalid aliasee");1212Aliasee = ID.ConstantVal;1213}12141215Type *AliaseeType = Aliasee->getType();1216auto *PTy = dyn_cast<PointerType>(AliaseeType);1217if (!PTy)1218return error(AliaseeLoc, "An alias or ifunc must have pointer type");1219unsigned AddrSpace = PTy->getAddressSpace();12201221GlobalValue *GVal = nullptr;12221223// See if the alias was forward referenced, if so, prepare to replace the1224// forward reference.1225if (!Name.empty()) {1226auto I = ForwardRefVals.find(Name);1227if (I != ForwardRefVals.end()) {1228GVal = I->second.first;1229ForwardRefVals.erase(Name);1230} else if (M->getNamedValue(Name)) {1231return error(NameLoc, "redefinition of global '@" + Name + "'");1232}1233} else {1234auto I = ForwardRefValIDs.find(NameID);1235if (I != ForwardRefValIDs.end()) {1236GVal = I->second.first;1237ForwardRefValIDs.erase(I);1238}1239}12401241// Okay, create the alias/ifunc but do not insert it into the module yet.1242std::unique_ptr<GlobalAlias> GA;1243std::unique_ptr<GlobalIFunc> GI;1244GlobalValue *GV;1245if (IsAlias) {1246GA.reset(GlobalAlias::create(Ty, AddrSpace,1247(GlobalValue::LinkageTypes)Linkage, Name,1248Aliasee, /*Parent*/ nullptr));1249GV = GA.get();1250} else {1251GI.reset(GlobalIFunc::create(Ty, AddrSpace,1252(GlobalValue::LinkageTypes)Linkage, Name,1253Aliasee, /*Parent*/ nullptr));1254GV = GI.get();1255}1256GV->setThreadLocalMode(TLM);1257GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);1258GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);1259GV->setUnnamedAddr(UnnamedAddr);1260maybeSetDSOLocal(DSOLocal, *GV);12611262// At this point we've parsed everything except for the IndirectSymbolAttrs.1263// Now parse them if there are any.1264while (Lex.getKind() == lltok::comma) {1265Lex.Lex();12661267if (Lex.getKind() == lltok::kw_partition) {1268Lex.Lex();1269GV->setPartition(Lex.getStrVal());1270if (parseToken(lltok::StringConstant, "expected partition string"))1271return true;1272} else {1273return tokError("unknown alias or ifunc property!");1274}1275}12761277if (Name.empty())1278NumberedVals.add(NameID, GV);12791280if (GVal) {1281// Verify that types agree.1282if (GVal->getType() != GV->getType())1283return error(1284ExplicitTypeLoc,1285"forward reference and definition of alias have different types");12861287// If they agree, just RAUW the old value with the alias and remove the1288// forward ref info.1289GVal->replaceAllUsesWith(GV);1290GVal->eraseFromParent();1291}12921293// Insert into the module, we know its name won't collide now.1294if (IsAlias)1295M->insertAlias(GA.release());1296else1297M->insertIFunc(GI.release());1298assert(GV->getName() == Name && "Should not be a name conflict!");12991300return false;1301}13021303static bool isSanitizer(lltok::Kind Kind) {1304switch (Kind) {1305case lltok::kw_no_sanitize_address:1306case lltok::kw_no_sanitize_hwaddress:1307case lltok::kw_sanitize_memtag:1308case lltok::kw_sanitize_address_dyninit:1309return true;1310default:1311return false;1312}1313}13141315bool LLParser::parseSanitizer(GlobalVariable *GV) {1316using SanitizerMetadata = GlobalValue::SanitizerMetadata;1317SanitizerMetadata Meta;1318if (GV->hasSanitizerMetadata())1319Meta = GV->getSanitizerMetadata();13201321switch (Lex.getKind()) {1322case lltok::kw_no_sanitize_address:1323Meta.NoAddress = true;1324break;1325case lltok::kw_no_sanitize_hwaddress:1326Meta.NoHWAddress = true;1327break;1328case lltok::kw_sanitize_memtag:1329Meta.Memtag = true;1330break;1331case lltok::kw_sanitize_address_dyninit:1332Meta.IsDynInit = true;1333break;1334default:1335return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");1336}1337GV->setSanitizerMetadata(Meta);1338Lex.Lex();1339return false;1340}13411342/// parseGlobal1343/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier1344/// OptionalVisibility OptionalDLLStorageClass1345/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace1346/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs1347/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility1348/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr1349/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type1350/// Const OptionalAttrs1351///1352/// Everything up to and including OptionalUnnamedAddr has been parsed1353/// already.1354///1355bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,1356LocTy NameLoc, unsigned Linkage, bool HasLinkage,1357unsigned Visibility, unsigned DLLStorageClass,1358bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,1359GlobalVariable::UnnamedAddr UnnamedAddr) {1360if (!isValidVisibilityForLinkage(Visibility, Linkage))1361return error(NameLoc,1362"symbol with local linkage must have default visibility");13631364if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))1365return error(NameLoc,1366"symbol with local linkage cannot have a DLL storage class");13671368unsigned AddrSpace;1369bool IsConstant, IsExternallyInitialized;1370LocTy IsExternallyInitializedLoc;1371LocTy TyLoc;13721373Type *Ty = nullptr;1374if (parseOptionalAddrSpace(AddrSpace) ||1375parseOptionalToken(lltok::kw_externally_initialized,1376IsExternallyInitialized,1377&IsExternallyInitializedLoc) ||1378parseGlobalType(IsConstant) || parseType(Ty, TyLoc))1379return true;13801381// If the linkage is specified and is external, then no initializer is1382// present.1383Constant *Init = nullptr;1384if (!HasLinkage ||1385!GlobalValue::isValidDeclarationLinkage(1386(GlobalValue::LinkageTypes)Linkage)) {1387if (parseGlobalValue(Ty, Init))1388return true;1389}13901391if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))1392return error(TyLoc, "invalid type for global variable");13931394GlobalValue *GVal = nullptr;13951396// See if the global was forward referenced, if so, use the global.1397if (!Name.empty()) {1398auto I = ForwardRefVals.find(Name);1399if (I != ForwardRefVals.end()) {1400GVal = I->second.first;1401ForwardRefVals.erase(I);1402} else if (M->getNamedValue(Name)) {1403return error(NameLoc, "redefinition of global '@" + Name + "'");1404}1405} else {1406// Handle @"", where a name is syntactically specified, but semantically1407// missing.1408if (NameID == (unsigned)-1)1409NameID = NumberedVals.getNext();14101411auto I = ForwardRefValIDs.find(NameID);1412if (I != ForwardRefValIDs.end()) {1413GVal = I->second.first;1414ForwardRefValIDs.erase(I);1415}1416}14171418GlobalVariable *GV = new GlobalVariable(1419*M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,1420GlobalVariable::NotThreadLocal, AddrSpace);14211422if (Name.empty())1423NumberedVals.add(NameID, GV);14241425// Set the parsed properties on the global.1426if (Init)1427GV->setInitializer(Init);1428GV->setConstant(IsConstant);1429GV->setLinkage((GlobalValue::LinkageTypes)Linkage);1430maybeSetDSOLocal(DSOLocal, *GV);1431GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);1432GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);1433GV->setExternallyInitialized(IsExternallyInitialized);1434GV->setThreadLocalMode(TLM);1435GV->setUnnamedAddr(UnnamedAddr);14361437if (GVal) {1438if (GVal->getAddressSpace() != AddrSpace)1439return error(1440TyLoc,1441"forward reference and definition of global have different types");14421443GVal->replaceAllUsesWith(GV);1444GVal->eraseFromParent();1445}14461447// parse attributes on the global.1448while (Lex.getKind() == lltok::comma) {1449Lex.Lex();14501451if (Lex.getKind() == lltok::kw_section) {1452Lex.Lex();1453GV->setSection(Lex.getStrVal());1454if (parseToken(lltok::StringConstant, "expected global section string"))1455return true;1456} else if (Lex.getKind() == lltok::kw_partition) {1457Lex.Lex();1458GV->setPartition(Lex.getStrVal());1459if (parseToken(lltok::StringConstant, "expected partition string"))1460return true;1461} else if (Lex.getKind() == lltok::kw_align) {1462MaybeAlign Alignment;1463if (parseOptionalAlignment(Alignment))1464return true;1465if (Alignment)1466GV->setAlignment(*Alignment);1467} else if (Lex.getKind() == lltok::kw_code_model) {1468CodeModel::Model CodeModel;1469if (parseOptionalCodeModel(CodeModel))1470return true;1471GV->setCodeModel(CodeModel);1472} else if (Lex.getKind() == lltok::MetadataVar) {1473if (parseGlobalObjectMetadataAttachment(*GV))1474return true;1475} else if (isSanitizer(Lex.getKind())) {1476if (parseSanitizer(GV))1477return true;1478} else {1479Comdat *C;1480if (parseOptionalComdat(Name, C))1481return true;1482if (C)1483GV->setComdat(C);1484else1485return tokError("unknown global variable property!");1486}1487}14881489AttrBuilder Attrs(M->getContext());1490LocTy BuiltinLoc;1491std::vector<unsigned> FwdRefAttrGrps;1492if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))1493return true;1494if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {1495GV->setAttributes(AttributeSet::get(Context, Attrs));1496ForwardRefAttrGroups[GV] = FwdRefAttrGrps;1497}14981499return false;1500}15011502/// parseUnnamedAttrGrp1503/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'1504bool LLParser::parseUnnamedAttrGrp() {1505assert(Lex.getKind() == lltok::kw_attributes);1506LocTy AttrGrpLoc = Lex.getLoc();1507Lex.Lex();15081509if (Lex.getKind() != lltok::AttrGrpID)1510return tokError("expected attribute group id");15111512unsigned VarID = Lex.getUIntVal();1513std::vector<unsigned> unused;1514LocTy BuiltinLoc;1515Lex.Lex();15161517if (parseToken(lltok::equal, "expected '=' here") ||1518parseToken(lltok::lbrace, "expected '{' here"))1519return true;15201521auto R = NumberedAttrBuilders.find(VarID);1522if (R == NumberedAttrBuilders.end())1523R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;15241525if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||1526parseToken(lltok::rbrace, "expected end of attribute group"))1527return true;15281529if (!R->second.hasAttributes())1530return error(AttrGrpLoc, "attribute group has no attributes");15311532return false;1533}15341535static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {1536switch (Kind) {1537#define GET_ATTR_NAMES1538#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \1539case lltok::kw_##DISPLAY_NAME: \1540return Attribute::ENUM_NAME;1541#include "llvm/IR/Attributes.inc"1542default:1543return Attribute::None;1544}1545}15461547bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,1548bool InAttrGroup) {1549if (Attribute::isTypeAttrKind(Attr))1550return parseRequiredTypeAttr(B, Lex.getKind(), Attr);15511552switch (Attr) {1553case Attribute::Alignment: {1554MaybeAlign Alignment;1555if (InAttrGroup) {1556uint32_t Value = 0;1557Lex.Lex();1558if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))1559return true;1560Alignment = Align(Value);1561} else {1562if (parseOptionalAlignment(Alignment, true))1563return true;1564}1565B.addAlignmentAttr(Alignment);1566return false;1567}1568case Attribute::StackAlignment: {1569unsigned Alignment;1570if (InAttrGroup) {1571Lex.Lex();1572if (parseToken(lltok::equal, "expected '=' here") ||1573parseUInt32(Alignment))1574return true;1575} else {1576if (parseOptionalStackAlignment(Alignment))1577return true;1578}1579B.addStackAlignmentAttr(Alignment);1580return false;1581}1582case Attribute::AllocSize: {1583unsigned ElemSizeArg;1584std::optional<unsigned> NumElemsArg;1585if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))1586return true;1587B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);1588return false;1589}1590case Attribute::VScaleRange: {1591unsigned MinValue, MaxValue;1592if (parseVScaleRangeArguments(MinValue, MaxValue))1593return true;1594B.addVScaleRangeAttr(MinValue,1595MaxValue > 0 ? MaxValue : std::optional<unsigned>());1596return false;1597}1598case Attribute::Dereferenceable: {1599uint64_t Bytes;1600if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))1601return true;1602B.addDereferenceableAttr(Bytes);1603return false;1604}1605case Attribute::DereferenceableOrNull: {1606uint64_t Bytes;1607if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))1608return true;1609B.addDereferenceableOrNullAttr(Bytes);1610return false;1611}1612case Attribute::UWTable: {1613UWTableKind Kind;1614if (parseOptionalUWTableKind(Kind))1615return true;1616B.addUWTableAttr(Kind);1617return false;1618}1619case Attribute::AllocKind: {1620AllocFnKind Kind = AllocFnKind::Unknown;1621if (parseAllocKind(Kind))1622return true;1623B.addAllocKindAttr(Kind);1624return false;1625}1626case Attribute::Memory: {1627std::optional<MemoryEffects> ME = parseMemoryAttr();1628if (!ME)1629return true;1630B.addMemoryAttr(*ME);1631return false;1632}1633case Attribute::NoFPClass: {1634if (FPClassTest NoFPClass =1635static_cast<FPClassTest>(parseNoFPClassAttr())) {1636B.addNoFPClassAttr(NoFPClass);1637return false;1638}16391640return true;1641}1642case Attribute::Range:1643return parseRangeAttr(B);1644case Attribute::Initializes:1645return parseInitializesAttr(B);1646default:1647B.addAttribute(Attr);1648Lex.Lex();1649return false;1650}1651}16521653static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) {1654switch (Kind) {1655case lltok::kw_readnone:1656ME &= MemoryEffects::none();1657return true;1658case lltok::kw_readonly:1659ME &= MemoryEffects::readOnly();1660return true;1661case lltok::kw_writeonly:1662ME &= MemoryEffects::writeOnly();1663return true;1664case lltok::kw_argmemonly:1665ME &= MemoryEffects::argMemOnly();1666return true;1667case lltok::kw_inaccessiblememonly:1668ME &= MemoryEffects::inaccessibleMemOnly();1669return true;1670case lltok::kw_inaccessiblemem_or_argmemonly:1671ME &= MemoryEffects::inaccessibleOrArgMemOnly();1672return true;1673default:1674return false;1675}1676}16771678/// parseFnAttributeValuePairs1679/// ::= <attr> | <attr> '=' <value>1680bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,1681std::vector<unsigned> &FwdRefAttrGrps,1682bool InAttrGrp, LocTy &BuiltinLoc) {1683bool HaveError = false;16841685B.clear();16861687MemoryEffects ME = MemoryEffects::unknown();1688while (true) {1689lltok::Kind Token = Lex.getKind();1690if (Token == lltok::rbrace)1691break; // Finished.16921693if (Token == lltok::StringConstant) {1694if (parseStringAttribute(B))1695return true;1696continue;1697}16981699if (Token == lltok::AttrGrpID) {1700// Allow a function to reference an attribute group:1701//1702// define void @foo() #1 { ... }1703if (InAttrGrp) {1704HaveError |= error(1705Lex.getLoc(),1706"cannot have an attribute group reference in an attribute group");1707} else {1708// Save the reference to the attribute group. We'll fill it in later.1709FwdRefAttrGrps.push_back(Lex.getUIntVal());1710}1711Lex.Lex();1712continue;1713}17141715SMLoc Loc = Lex.getLoc();1716if (Token == lltok::kw_builtin)1717BuiltinLoc = Loc;17181719if (upgradeMemoryAttr(ME, Token)) {1720Lex.Lex();1721continue;1722}17231724Attribute::AttrKind Attr = tokenToAttribute(Token);1725if (Attr == Attribute::None) {1726if (!InAttrGrp)1727break;1728return error(Lex.getLoc(), "unterminated attribute group");1729}17301731if (parseEnumAttribute(Attr, B, InAttrGrp))1732return true;17331734// As a hack, we allow function alignment to be initially parsed as an1735// attribute on a function declaration/definition or added to an attribute1736// group and later moved to the alignment field.1737if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)1738HaveError |= error(Loc, "this attribute does not apply to functions");1739}17401741if (ME != MemoryEffects::unknown())1742B.addMemoryAttr(ME);1743return HaveError;1744}17451746//===----------------------------------------------------------------------===//1747// GlobalValue Reference/Resolution Routines.1748//===----------------------------------------------------------------------===//17491750static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {1751// The used global type does not matter. We will later RAUW it with a1752// global/function of the correct type.1753return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,1754GlobalValue::ExternalWeakLinkage, nullptr, "",1755nullptr, GlobalVariable::NotThreadLocal,1756PTy->getAddressSpace());1757}17581759Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,1760Value *Val) {1761Type *ValTy = Val->getType();1762if (ValTy == Ty)1763return Val;1764if (Ty->isLabelTy())1765error(Loc, "'" + Name + "' is not a basic block");1766else1767error(Loc, "'" + Name + "' defined with type '" +1768getTypeString(Val->getType()) + "' but expected '" +1769getTypeString(Ty) + "'");1770return nullptr;1771}17721773/// getGlobalVal - Get a value with the specified name or ID, creating a1774/// forward reference record if needed. This can return null if the value1775/// exists but does not have the right type.1776GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,1777LocTy Loc) {1778PointerType *PTy = dyn_cast<PointerType>(Ty);1779if (!PTy) {1780error(Loc, "global variable reference must have pointer type");1781return nullptr;1782}17831784// Look this name up in the normal function symbol table.1785GlobalValue *Val =1786cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));17871788// If this is a forward reference for the value, see if we already created a1789// forward ref record.1790if (!Val) {1791auto I = ForwardRefVals.find(Name);1792if (I != ForwardRefVals.end())1793Val = I->second.first;1794}17951796// If we have the value in the symbol table or fwd-ref table, return it.1797if (Val)1798return cast_or_null<GlobalValue>(1799checkValidVariableType(Loc, "@" + Name, Ty, Val));18001801// Otherwise, create a new forward reference for this value and remember it.1802GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);1803ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);1804return FwdVal;1805}18061807GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {1808PointerType *PTy = dyn_cast<PointerType>(Ty);1809if (!PTy) {1810error(Loc, "global variable reference must have pointer type");1811return nullptr;1812}18131814GlobalValue *Val = NumberedVals.get(ID);18151816// If this is a forward reference for the value, see if we already created a1817// forward ref record.1818if (!Val) {1819auto I = ForwardRefValIDs.find(ID);1820if (I != ForwardRefValIDs.end())1821Val = I->second.first;1822}18231824// If we have the value in the symbol table or fwd-ref table, return it.1825if (Val)1826return cast_or_null<GlobalValue>(1827checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));18281829// Otherwise, create a new forward reference for this value and remember it.1830GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);1831ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);1832return FwdVal;1833}18341835//===----------------------------------------------------------------------===//1836// Comdat Reference/Resolution Routines.1837//===----------------------------------------------------------------------===//18381839Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {1840// Look this name up in the comdat symbol table.1841Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();1842Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);1843if (I != ComdatSymTab.end())1844return &I->second;18451846// Otherwise, create a new forward reference for this value and remember it.1847Comdat *C = M->getOrInsertComdat(Name);1848ForwardRefComdats[Name] = Loc;1849return C;1850}18511852//===----------------------------------------------------------------------===//1853// Helper Routines.1854//===----------------------------------------------------------------------===//18551856/// parseToken - If the current token has the specified kind, eat it and return1857/// success. Otherwise, emit the specified error and return failure.1858bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {1859if (Lex.getKind() != T)1860return tokError(ErrMsg);1861Lex.Lex();1862return false;1863}18641865/// parseStringConstant1866/// ::= StringConstant1867bool LLParser::parseStringConstant(std::string &Result) {1868if (Lex.getKind() != lltok::StringConstant)1869return tokError("expected string constant");1870Result = Lex.getStrVal();1871Lex.Lex();1872return false;1873}18741875/// parseUInt321876/// ::= uint321877bool LLParser::parseUInt32(uint32_t &Val) {1878if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())1879return tokError("expected integer");1880uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);1881if (Val64 != unsigned(Val64))1882return tokError("expected 32-bit integer (too large)");1883Val = Val64;1884Lex.Lex();1885return false;1886}18871888/// parseUInt641889/// ::= uint641890bool LLParser::parseUInt64(uint64_t &Val) {1891if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())1892return tokError("expected integer");1893Val = Lex.getAPSIntVal().getLimitedValue();1894Lex.Lex();1895return false;1896}18971898/// parseTLSModel1899/// := 'localdynamic'1900/// := 'initialexec'1901/// := 'localexec'1902bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {1903switch (Lex.getKind()) {1904default:1905return tokError("expected localdynamic, initialexec or localexec");1906case lltok::kw_localdynamic:1907TLM = GlobalVariable::LocalDynamicTLSModel;1908break;1909case lltok::kw_initialexec:1910TLM = GlobalVariable::InitialExecTLSModel;1911break;1912case lltok::kw_localexec:1913TLM = GlobalVariable::LocalExecTLSModel;1914break;1915}19161917Lex.Lex();1918return false;1919}19201921/// parseOptionalThreadLocal1922/// := /*empty*/1923/// := 'thread_local'1924/// := 'thread_local' '(' tlsmodel ')'1925bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {1926TLM = GlobalVariable::NotThreadLocal;1927if (!EatIfPresent(lltok::kw_thread_local))1928return false;19291930TLM = GlobalVariable::GeneralDynamicTLSModel;1931if (Lex.getKind() == lltok::lparen) {1932Lex.Lex();1933return parseTLSModel(TLM) ||1934parseToken(lltok::rparen, "expected ')' after thread local model");1935}1936return false;1937}19381939/// parseOptionalAddrSpace1940/// := /*empty*/1941/// := 'addrspace' '(' uint32 ')'1942bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {1943AddrSpace = DefaultAS;1944if (!EatIfPresent(lltok::kw_addrspace))1945return false;19461947auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {1948if (Lex.getKind() == lltok::StringConstant) {1949auto AddrSpaceStr = Lex.getStrVal();1950if (AddrSpaceStr == "A") {1951AddrSpace = M->getDataLayout().getAllocaAddrSpace();1952} else if (AddrSpaceStr == "G") {1953AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();1954} else if (AddrSpaceStr == "P") {1955AddrSpace = M->getDataLayout().getProgramAddressSpace();1956} else {1957return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");1958}1959Lex.Lex();1960return false;1961}1962if (Lex.getKind() != lltok::APSInt)1963return tokError("expected integer or string constant");1964SMLoc Loc = Lex.getLoc();1965if (parseUInt32(AddrSpace))1966return true;1967if (!isUInt<24>(AddrSpace))1968return error(Loc, "invalid address space, must be a 24-bit integer");1969return false;1970};19711972return parseToken(lltok::lparen, "expected '(' in address space") ||1973ParseAddrspaceValue(AddrSpace) ||1974parseToken(lltok::rparen, "expected ')' in address space");1975}19761977/// parseStringAttribute1978/// := StringConstant1979/// := StringConstant '=' StringConstant1980bool LLParser::parseStringAttribute(AttrBuilder &B) {1981std::string Attr = Lex.getStrVal();1982Lex.Lex();1983std::string Val;1984if (EatIfPresent(lltok::equal) && parseStringConstant(Val))1985return true;1986B.addAttribute(Attr, Val);1987return false;1988}19891990/// Parse a potentially empty list of parameter or return attributes.1991bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {1992bool HaveError = false;19931994B.clear();19951996while (true) {1997lltok::Kind Token = Lex.getKind();1998if (Token == lltok::StringConstant) {1999if (parseStringAttribute(B))2000return true;2001continue;2002}20032004SMLoc Loc = Lex.getLoc();2005Attribute::AttrKind Attr = tokenToAttribute(Token);2006if (Attr == Attribute::None)2007return HaveError;20082009if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))2010return true;20112012if (IsParam && !Attribute::canUseAsParamAttr(Attr))2013HaveError |= error(Loc, "this attribute does not apply to parameters");2014if (!IsParam && !Attribute::canUseAsRetAttr(Attr))2015HaveError |= error(Loc, "this attribute does not apply to return values");2016}2017}20182019static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {2020HasLinkage = true;2021switch (Kind) {2022default:2023HasLinkage = false;2024return GlobalValue::ExternalLinkage;2025case lltok::kw_private:2026return GlobalValue::PrivateLinkage;2027case lltok::kw_internal:2028return GlobalValue::InternalLinkage;2029case lltok::kw_weak:2030return GlobalValue::WeakAnyLinkage;2031case lltok::kw_weak_odr:2032return GlobalValue::WeakODRLinkage;2033case lltok::kw_linkonce:2034return GlobalValue::LinkOnceAnyLinkage;2035case lltok::kw_linkonce_odr:2036return GlobalValue::LinkOnceODRLinkage;2037case lltok::kw_available_externally:2038return GlobalValue::AvailableExternallyLinkage;2039case lltok::kw_appending:2040return GlobalValue::AppendingLinkage;2041case lltok::kw_common:2042return GlobalValue::CommonLinkage;2043case lltok::kw_extern_weak:2044return GlobalValue::ExternalWeakLinkage;2045case lltok::kw_external:2046return GlobalValue::ExternalLinkage;2047}2048}20492050/// parseOptionalLinkage2051/// ::= /*empty*/2052/// ::= 'private'2053/// ::= 'internal'2054/// ::= 'weak'2055/// ::= 'weak_odr'2056/// ::= 'linkonce'2057/// ::= 'linkonce_odr'2058/// ::= 'available_externally'2059/// ::= 'appending'2060/// ::= 'common'2061/// ::= 'extern_weak'2062/// ::= 'external'2063bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,2064unsigned &Visibility,2065unsigned &DLLStorageClass, bool &DSOLocal) {2066Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);2067if (HasLinkage)2068Lex.Lex();2069parseOptionalDSOLocal(DSOLocal);2070parseOptionalVisibility(Visibility);2071parseOptionalDLLStorageClass(DLLStorageClass);20722073if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {2074return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");2075}20762077return false;2078}20792080void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {2081switch (Lex.getKind()) {2082default:2083DSOLocal = false;2084break;2085case lltok::kw_dso_local:2086DSOLocal = true;2087Lex.Lex();2088break;2089case lltok::kw_dso_preemptable:2090DSOLocal = false;2091Lex.Lex();2092break;2093}2094}20952096/// parseOptionalVisibility2097/// ::= /*empty*/2098/// ::= 'default'2099/// ::= 'hidden'2100/// ::= 'protected'2101///2102void LLParser::parseOptionalVisibility(unsigned &Res) {2103switch (Lex.getKind()) {2104default:2105Res = GlobalValue::DefaultVisibility;2106return;2107case lltok::kw_default:2108Res = GlobalValue::DefaultVisibility;2109break;2110case lltok::kw_hidden:2111Res = GlobalValue::HiddenVisibility;2112break;2113case lltok::kw_protected:2114Res = GlobalValue::ProtectedVisibility;2115break;2116}2117Lex.Lex();2118}21192120bool LLParser::parseOptionalImportType(lltok::Kind Kind,2121GlobalValueSummary::ImportKind &Res) {2122switch (Kind) {2123default:2124return tokError("unknown import kind. Expect definition or declaration.");2125case lltok::kw_definition:2126Res = GlobalValueSummary::Definition;2127return false;2128case lltok::kw_declaration:2129Res = GlobalValueSummary::Declaration;2130return false;2131}2132}21332134/// parseOptionalDLLStorageClass2135/// ::= /*empty*/2136/// ::= 'dllimport'2137/// ::= 'dllexport'2138///2139void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {2140switch (Lex.getKind()) {2141default:2142Res = GlobalValue::DefaultStorageClass;2143return;2144case lltok::kw_dllimport:2145Res = GlobalValue::DLLImportStorageClass;2146break;2147case lltok::kw_dllexport:2148Res = GlobalValue::DLLExportStorageClass;2149break;2150}2151Lex.Lex();2152}21532154/// parseOptionalCallingConv2155/// ::= /*empty*/2156/// ::= 'ccc'2157/// ::= 'fastcc'2158/// ::= 'intel_ocl_bicc'2159/// ::= 'coldcc'2160/// ::= 'cfguard_checkcc'2161/// ::= 'x86_stdcallcc'2162/// ::= 'x86_fastcallcc'2163/// ::= 'x86_thiscallcc'2164/// ::= 'x86_vectorcallcc'2165/// ::= 'arm_apcscc'2166/// ::= 'arm_aapcscc'2167/// ::= 'arm_aapcs_vfpcc'2168/// ::= 'aarch64_vector_pcs'2169/// ::= 'aarch64_sve_vector_pcs'2170/// ::= 'aarch64_sme_preservemost_from_x0'2171/// ::= 'aarch64_sme_preservemost_from_x1'2172/// ::= 'aarch64_sme_preservemost_from_x2'2173/// ::= 'msp430_intrcc'2174/// ::= 'avr_intrcc'2175/// ::= 'avr_signalcc'2176/// ::= 'ptx_kernel'2177/// ::= 'ptx_device'2178/// ::= 'spir_func'2179/// ::= 'spir_kernel'2180/// ::= 'x86_64_sysvcc'2181/// ::= 'win64cc'2182/// ::= 'anyregcc'2183/// ::= 'preserve_mostcc'2184/// ::= 'preserve_allcc'2185/// ::= 'preserve_nonecc'2186/// ::= 'ghccc'2187/// ::= 'swiftcc'2188/// ::= 'swifttailcc'2189/// ::= 'x86_intrcc'2190/// ::= 'hhvmcc'2191/// ::= 'hhvm_ccc'2192/// ::= 'cxx_fast_tlscc'2193/// ::= 'amdgpu_vs'2194/// ::= 'amdgpu_ls'2195/// ::= 'amdgpu_hs'2196/// ::= 'amdgpu_es'2197/// ::= 'amdgpu_gs'2198/// ::= 'amdgpu_ps'2199/// ::= 'amdgpu_cs'2200/// ::= 'amdgpu_cs_chain'2201/// ::= 'amdgpu_cs_chain_preserve'2202/// ::= 'amdgpu_kernel'2203/// ::= 'tailcc'2204/// ::= 'm68k_rtdcc'2205/// ::= 'graalcc'2206/// ::= 'riscv_vector_cc'2207/// ::= 'cc' UINT2208///2209bool LLParser::parseOptionalCallingConv(unsigned &CC) {2210switch (Lex.getKind()) {2211default: CC = CallingConv::C; return false;2212case lltok::kw_ccc: CC = CallingConv::C; break;2213case lltok::kw_fastcc: CC = CallingConv::Fast; break;2214case lltok::kw_coldcc: CC = CallingConv::Cold; break;2215case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;2216case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;2217case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;2218case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;2219case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;2220case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;2221case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;2222case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;2223case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;2224case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;2225case lltok::kw_aarch64_sve_vector_pcs:2226CC = CallingConv::AArch64_SVE_VectorCall;2227break;2228case lltok::kw_aarch64_sme_preservemost_from_x0:2229CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0;2230break;2231case lltok::kw_aarch64_sme_preservemost_from_x1:2232CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1;2233break;2234case lltok::kw_aarch64_sme_preservemost_from_x2:2235CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2;2236break;2237case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;2238case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;2239case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;2240case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;2241case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;2242case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;2243case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;2244case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;2245case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;2246case lltok::kw_win64cc: CC = CallingConv::Win64; break;2247case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;2248case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;2249case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;2250case lltok::kw_preserve_nonecc:CC = CallingConv::PreserveNone; break;2251case lltok::kw_ghccc: CC = CallingConv::GHC; break;2252case lltok::kw_swiftcc: CC = CallingConv::Swift; break;2253case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;2254case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;2255case lltok::kw_hhvmcc:2256CC = CallingConv::DUMMY_HHVM;2257break;2258case lltok::kw_hhvm_ccc:2259CC = CallingConv::DUMMY_HHVM_C;2260break;2261case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;2262case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;2263case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;2264case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;2265case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;2266case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;2267case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;2268case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;2269case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;2270case lltok::kw_amdgpu_cs_chain:2271CC = CallingConv::AMDGPU_CS_Chain;2272break;2273case lltok::kw_amdgpu_cs_chain_preserve:2274CC = CallingConv::AMDGPU_CS_ChainPreserve;2275break;2276case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;2277case lltok::kw_tailcc: CC = CallingConv::Tail; break;2278case lltok::kw_m68k_rtdcc: CC = CallingConv::M68k_RTD; break;2279case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;2280case lltok::kw_riscv_vector_cc:2281CC = CallingConv::RISCV_VectorCall;2282break;2283case lltok::kw_cc: {2284Lex.Lex();2285return parseUInt32(CC);2286}2287}22882289Lex.Lex();2290return false;2291}22922293/// parseMetadataAttachment2294/// ::= !dbg !422295bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {2296assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");22972298std::string Name = Lex.getStrVal();2299Kind = M->getMDKindID(Name);2300Lex.Lex();23012302return parseMDNode(MD);2303}23042305/// parseInstructionMetadata2306/// ::= !dbg !42 (',' !dbg !57)*2307bool LLParser::parseInstructionMetadata(Instruction &Inst) {2308do {2309if (Lex.getKind() != lltok::MetadataVar)2310return tokError("expected metadata after comma");23112312unsigned MDK;2313MDNode *N;2314if (parseMetadataAttachment(MDK, N))2315return true;23162317if (MDK == LLVMContext::MD_DIAssignID)2318TempDIAssignIDAttachments[N].push_back(&Inst);2319else2320Inst.setMetadata(MDK, N);23212322if (MDK == LLVMContext::MD_tbaa)2323InstsWithTBAATag.push_back(&Inst);23242325// If this is the end of the list, we're done.2326} while (EatIfPresent(lltok::comma));2327return false;2328}23292330/// parseGlobalObjectMetadataAttachment2331/// ::= !dbg !572332bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {2333unsigned MDK;2334MDNode *N;2335if (parseMetadataAttachment(MDK, N))2336return true;23372338GO.addMetadata(MDK, *N);2339return false;2340}23412342/// parseOptionalFunctionMetadata2343/// ::= (!dbg !57)*2344bool LLParser::parseOptionalFunctionMetadata(Function &F) {2345while (Lex.getKind() == lltok::MetadataVar)2346if (parseGlobalObjectMetadataAttachment(F))2347return true;2348return false;2349}23502351/// parseOptionalAlignment2352/// ::= /* empty */2353/// ::= 'align' 42354bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {2355Alignment = std::nullopt;2356if (!EatIfPresent(lltok::kw_align))2357return false;2358LocTy AlignLoc = Lex.getLoc();2359uint64_t Value = 0;23602361LocTy ParenLoc = Lex.getLoc();2362bool HaveParens = false;2363if (AllowParens) {2364if (EatIfPresent(lltok::lparen))2365HaveParens = true;2366}23672368if (parseUInt64(Value))2369return true;23702371if (HaveParens && !EatIfPresent(lltok::rparen))2372return error(ParenLoc, "expected ')'");23732374if (!isPowerOf2_64(Value))2375return error(AlignLoc, "alignment is not a power of two");2376if (Value > Value::MaximumAlignment)2377return error(AlignLoc, "huge alignments are not supported yet");2378Alignment = Align(Value);2379return false;2380}23812382/// parseOptionalCodeModel2383/// ::= /* empty */2384/// ::= 'code_model' "large"2385bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {2386Lex.Lex();2387auto StrVal = Lex.getStrVal();2388auto ErrMsg = "expected global code model string";2389if (StrVal == "tiny")2390model = CodeModel::Tiny;2391else if (StrVal == "small")2392model = CodeModel::Small;2393else if (StrVal == "kernel")2394model = CodeModel::Kernel;2395else if (StrVal == "medium")2396model = CodeModel::Medium;2397else if (StrVal == "large")2398model = CodeModel::Large;2399else2400return tokError(ErrMsg);2401if (parseToken(lltok::StringConstant, ErrMsg))2402return true;2403return false;2404}24052406/// parseOptionalDerefAttrBytes2407/// ::= /* empty */2408/// ::= AttrKind '(' 4 ')'2409///2410/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.2411bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,2412uint64_t &Bytes) {2413assert((AttrKind == lltok::kw_dereferenceable ||2414AttrKind == lltok::kw_dereferenceable_or_null) &&2415"contract!");24162417Bytes = 0;2418if (!EatIfPresent(AttrKind))2419return false;2420LocTy ParenLoc = Lex.getLoc();2421if (!EatIfPresent(lltok::lparen))2422return error(ParenLoc, "expected '('");2423LocTy DerefLoc = Lex.getLoc();2424if (parseUInt64(Bytes))2425return true;2426ParenLoc = Lex.getLoc();2427if (!EatIfPresent(lltok::rparen))2428return error(ParenLoc, "expected ')'");2429if (!Bytes)2430return error(DerefLoc, "dereferenceable bytes must be non-zero");2431return false;2432}24332434bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {2435Lex.Lex();2436Kind = UWTableKind::Default;2437if (!EatIfPresent(lltok::lparen))2438return false;2439LocTy KindLoc = Lex.getLoc();2440if (Lex.getKind() == lltok::kw_sync)2441Kind = UWTableKind::Sync;2442else if (Lex.getKind() == lltok::kw_async)2443Kind = UWTableKind::Async;2444else2445return error(KindLoc, "expected unwind table kind");2446Lex.Lex();2447return parseToken(lltok::rparen, "expected ')'");2448}24492450bool LLParser::parseAllocKind(AllocFnKind &Kind) {2451Lex.Lex();2452LocTy ParenLoc = Lex.getLoc();2453if (!EatIfPresent(lltok::lparen))2454return error(ParenLoc, "expected '('");2455LocTy KindLoc = Lex.getLoc();2456std::string Arg;2457if (parseStringConstant(Arg))2458return error(KindLoc, "expected allockind value");2459for (StringRef A : llvm::split(Arg, ",")) {2460if (A == "alloc") {2461Kind |= AllocFnKind::Alloc;2462} else if (A == "realloc") {2463Kind |= AllocFnKind::Realloc;2464} else if (A == "free") {2465Kind |= AllocFnKind::Free;2466} else if (A == "uninitialized") {2467Kind |= AllocFnKind::Uninitialized;2468} else if (A == "zeroed") {2469Kind |= AllocFnKind::Zeroed;2470} else if (A == "aligned") {2471Kind |= AllocFnKind::Aligned;2472} else {2473return error(KindLoc, Twine("unknown allockind ") + A);2474}2475}2476ParenLoc = Lex.getLoc();2477if (!EatIfPresent(lltok::rparen))2478return error(ParenLoc, "expected ')'");2479if (Kind == AllocFnKind::Unknown)2480return error(KindLoc, "expected allockind value");2481return false;2482}24832484static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {2485switch (Tok) {2486case lltok::kw_argmem:2487return IRMemLocation::ArgMem;2488case lltok::kw_inaccessiblemem:2489return IRMemLocation::InaccessibleMem;2490default:2491return std::nullopt;2492}2493}24942495static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {2496switch (Tok) {2497case lltok::kw_none:2498return ModRefInfo::NoModRef;2499case lltok::kw_read:2500return ModRefInfo::Ref;2501case lltok::kw_write:2502return ModRefInfo::Mod;2503case lltok::kw_readwrite:2504return ModRefInfo::ModRef;2505default:2506return std::nullopt;2507}2508}25092510std::optional<MemoryEffects> LLParser::parseMemoryAttr() {2511MemoryEffects ME = MemoryEffects::none();25122513// We use syntax like memory(argmem: read), so the colon should not be2514// interpreted as a label terminator.2515Lex.setIgnoreColonInIdentifiers(true);2516auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });25172518Lex.Lex();2519if (!EatIfPresent(lltok::lparen)) {2520tokError("expected '('");2521return std::nullopt;2522}25232524bool SeenLoc = false;2525do {2526std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());2527if (Loc) {2528Lex.Lex();2529if (!EatIfPresent(lltok::colon)) {2530tokError("expected ':' after location");2531return std::nullopt;2532}2533}25342535std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());2536if (!MR) {2537if (!Loc)2538tokError("expected memory location (argmem, inaccessiblemem) "2539"or access kind (none, read, write, readwrite)");2540else2541tokError("expected access kind (none, read, write, readwrite)");2542return std::nullopt;2543}25442545Lex.Lex();2546if (Loc) {2547SeenLoc = true;2548ME = ME.getWithModRef(*Loc, *MR);2549} else {2550if (SeenLoc) {2551tokError("default access kind must be specified first");2552return std::nullopt;2553}2554ME = MemoryEffects(*MR);2555}25562557if (EatIfPresent(lltok::rparen))2558return ME;2559} while (EatIfPresent(lltok::comma));25602561tokError("unterminated memory attribute");2562return std::nullopt;2563}25642565static unsigned keywordToFPClassTest(lltok::Kind Tok) {2566switch (Tok) {2567case lltok::kw_all:2568return fcAllFlags;2569case lltok::kw_nan:2570return fcNan;2571case lltok::kw_snan:2572return fcSNan;2573case lltok::kw_qnan:2574return fcQNan;2575case lltok::kw_inf:2576return fcInf;2577case lltok::kw_ninf:2578return fcNegInf;2579case lltok::kw_pinf:2580return fcPosInf;2581case lltok::kw_norm:2582return fcNormal;2583case lltok::kw_nnorm:2584return fcNegNormal;2585case lltok::kw_pnorm:2586return fcPosNormal;2587case lltok::kw_sub:2588return fcSubnormal;2589case lltok::kw_nsub:2590return fcNegSubnormal;2591case lltok::kw_psub:2592return fcPosSubnormal;2593case lltok::kw_zero:2594return fcZero;2595case lltok::kw_nzero:2596return fcNegZero;2597case lltok::kw_pzero:2598return fcPosZero;2599default:2600return 0;2601}2602}26032604unsigned LLParser::parseNoFPClassAttr() {2605unsigned Mask = fcNone;26062607Lex.Lex();2608if (!EatIfPresent(lltok::lparen)) {2609tokError("expected '('");2610return 0;2611}26122613do {2614uint64_t Value = 0;2615unsigned TestMask = keywordToFPClassTest(Lex.getKind());2616if (TestMask != 0) {2617Mask |= TestMask;2618// TODO: Disallow overlapping masks to avoid copy paste errors2619} else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&2620!parseUInt64(Value)) {2621if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {2622error(Lex.getLoc(), "invalid mask value for 'nofpclass'");2623return 0;2624}26252626if (!EatIfPresent(lltok::rparen)) {2627error(Lex.getLoc(), "expected ')'");2628return 0;2629}26302631return Value;2632} else {2633error(Lex.getLoc(), "expected nofpclass test mask");2634return 0;2635}26362637Lex.Lex();2638if (EatIfPresent(lltok::rparen))2639return Mask;2640} while (1);26412642llvm_unreachable("unterminated nofpclass attribute");2643}26442645/// parseOptionalCommaAlign2646/// ::=2647/// ::= ',' align 42648///2649/// This returns with AteExtraComma set to true if it ate an excess comma at the2650/// end.2651bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,2652bool &AteExtraComma) {2653AteExtraComma = false;2654while (EatIfPresent(lltok::comma)) {2655// Metadata at the end is an early exit.2656if (Lex.getKind() == lltok::MetadataVar) {2657AteExtraComma = true;2658return false;2659}26602661if (Lex.getKind() != lltok::kw_align)2662return error(Lex.getLoc(), "expected metadata or 'align'");26632664if (parseOptionalAlignment(Alignment))2665return true;2666}26672668return false;2669}26702671/// parseOptionalCommaAddrSpace2672/// ::=2673/// ::= ',' addrspace(1)2674///2675/// This returns with AteExtraComma set to true if it ate an excess comma at the2676/// end.2677bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,2678bool &AteExtraComma) {2679AteExtraComma = false;2680while (EatIfPresent(lltok::comma)) {2681// Metadata at the end is an early exit.2682if (Lex.getKind() == lltok::MetadataVar) {2683AteExtraComma = true;2684return false;2685}26862687Loc = Lex.getLoc();2688if (Lex.getKind() != lltok::kw_addrspace)2689return error(Lex.getLoc(), "expected metadata or 'addrspace'");26902691if (parseOptionalAddrSpace(AddrSpace))2692return true;2693}26942695return false;2696}26972698bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,2699std::optional<unsigned> &HowManyArg) {2700Lex.Lex();27012702auto StartParen = Lex.getLoc();2703if (!EatIfPresent(lltok::lparen))2704return error(StartParen, "expected '('");27052706if (parseUInt32(BaseSizeArg))2707return true;27082709if (EatIfPresent(lltok::comma)) {2710auto HowManyAt = Lex.getLoc();2711unsigned HowMany;2712if (parseUInt32(HowMany))2713return true;2714if (HowMany == BaseSizeArg)2715return error(HowManyAt,2716"'allocsize' indices can't refer to the same parameter");2717HowManyArg = HowMany;2718} else2719HowManyArg = std::nullopt;27202721auto EndParen = Lex.getLoc();2722if (!EatIfPresent(lltok::rparen))2723return error(EndParen, "expected ')'");2724return false;2725}27262727bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,2728unsigned &MaxValue) {2729Lex.Lex();27302731auto StartParen = Lex.getLoc();2732if (!EatIfPresent(lltok::lparen))2733return error(StartParen, "expected '('");27342735if (parseUInt32(MinValue))2736return true;27372738if (EatIfPresent(lltok::comma)) {2739if (parseUInt32(MaxValue))2740return true;2741} else2742MaxValue = MinValue;27432744auto EndParen = Lex.getLoc();2745if (!EatIfPresent(lltok::rparen))2746return error(EndParen, "expected ')'");2747return false;2748}27492750/// parseScopeAndOrdering2751/// if isAtomic: ::= SyncScope? AtomicOrdering2752/// else: ::=2753///2754/// This sets Scope and Ordering to the parsed values.2755bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,2756AtomicOrdering &Ordering) {2757if (!IsAtomic)2758return false;27592760return parseScope(SSID) || parseOrdering(Ordering);2761}27622763/// parseScope2764/// ::= syncscope("singlethread" | "<target scope>")?2765///2766/// This sets synchronization scope ID to the ID of the parsed value.2767bool LLParser::parseScope(SyncScope::ID &SSID) {2768SSID = SyncScope::System;2769if (EatIfPresent(lltok::kw_syncscope)) {2770auto StartParenAt = Lex.getLoc();2771if (!EatIfPresent(lltok::lparen))2772return error(StartParenAt, "Expected '(' in syncscope");27732774std::string SSN;2775auto SSNAt = Lex.getLoc();2776if (parseStringConstant(SSN))2777return error(SSNAt, "Expected synchronization scope name");27782779auto EndParenAt = Lex.getLoc();2780if (!EatIfPresent(lltok::rparen))2781return error(EndParenAt, "Expected ')' in syncscope");27822783SSID = Context.getOrInsertSyncScopeID(SSN);2784}27852786return false;2787}27882789/// parseOrdering2790/// ::= AtomicOrdering2791///2792/// This sets Ordering to the parsed value.2793bool LLParser::parseOrdering(AtomicOrdering &Ordering) {2794switch (Lex.getKind()) {2795default:2796return tokError("Expected ordering on atomic instruction");2797case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;2798case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;2799// Not specified yet:2800// case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;2801case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;2802case lltok::kw_release: Ordering = AtomicOrdering::Release; break;2803case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;2804case lltok::kw_seq_cst:2805Ordering = AtomicOrdering::SequentiallyConsistent;2806break;2807}2808Lex.Lex();2809return false;2810}28112812/// parseOptionalStackAlignment2813/// ::= /* empty */2814/// ::= 'alignstack' '(' 4 ')'2815bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {2816Alignment = 0;2817if (!EatIfPresent(lltok::kw_alignstack))2818return false;2819LocTy ParenLoc = Lex.getLoc();2820if (!EatIfPresent(lltok::lparen))2821return error(ParenLoc, "expected '('");2822LocTy AlignLoc = Lex.getLoc();2823if (parseUInt32(Alignment))2824return true;2825ParenLoc = Lex.getLoc();2826if (!EatIfPresent(lltok::rparen))2827return error(ParenLoc, "expected ')'");2828if (!isPowerOf2_32(Alignment))2829return error(AlignLoc, "stack alignment is not a power of two");2830return false;2831}28322833/// parseIndexList - This parses the index list for an insert/extractvalue2834/// instruction. This sets AteExtraComma in the case where we eat an extra2835/// comma at the end of the line and find that it is followed by metadata.2836/// Clients that don't allow metadata can call the version of this function that2837/// only takes one argument.2838///2839/// parseIndexList2840/// ::= (',' uint32)+2841///2842bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,2843bool &AteExtraComma) {2844AteExtraComma = false;28452846if (Lex.getKind() != lltok::comma)2847return tokError("expected ',' as start of index list");28482849while (EatIfPresent(lltok::comma)) {2850if (Lex.getKind() == lltok::MetadataVar) {2851if (Indices.empty())2852return tokError("expected index");2853AteExtraComma = true;2854return false;2855}2856unsigned Idx = 0;2857if (parseUInt32(Idx))2858return true;2859Indices.push_back(Idx);2860}28612862return false;2863}28642865//===----------------------------------------------------------------------===//2866// Type Parsing.2867//===----------------------------------------------------------------------===//28682869/// parseType - parse a type.2870bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {2871SMLoc TypeLoc = Lex.getLoc();2872switch (Lex.getKind()) {2873default:2874return tokError(Msg);2875case lltok::Type:2876// Type ::= 'float' | 'void' (etc)2877Result = Lex.getTyVal();2878Lex.Lex();28792880// Handle "ptr" opaque pointer type.2881//2882// Type ::= ptr ('addrspace' '(' uint32 ')')?2883if (Result->isPointerTy()) {2884unsigned AddrSpace;2885if (parseOptionalAddrSpace(AddrSpace))2886return true;2887Result = PointerType::get(getContext(), AddrSpace);28882889// Give a nice error for 'ptr*'.2890if (Lex.getKind() == lltok::star)2891return tokError("ptr* is invalid - use ptr instead");28922893// Fall through to parsing the type suffixes only if this 'ptr' is a2894// function return. Otherwise, return success, implicitly rejecting other2895// suffixes.2896if (Lex.getKind() != lltok::lparen)2897return false;2898}2899break;2900case lltok::kw_target: {2901// Type ::= TargetExtType2902if (parseTargetExtType(Result))2903return true;2904break;2905}2906case lltok::lbrace:2907// Type ::= StructType2908if (parseAnonStructType(Result, false))2909return true;2910break;2911case lltok::lsquare:2912// Type ::= '[' ... ']'2913Lex.Lex(); // eat the lsquare.2914if (parseArrayVectorType(Result, false))2915return true;2916break;2917case lltok::less: // Either vector or packed struct.2918// Type ::= '<' ... '>'2919Lex.Lex();2920if (Lex.getKind() == lltok::lbrace) {2921if (parseAnonStructType(Result, true) ||2922parseToken(lltok::greater, "expected '>' at end of packed struct"))2923return true;2924} else if (parseArrayVectorType(Result, true))2925return true;2926break;2927case lltok::LocalVar: {2928// Type ::= %foo2929std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];29302931// If the type hasn't been defined yet, create a forward definition and2932// remember where that forward def'n was seen (in case it never is defined).2933if (!Entry.first) {2934Entry.first = StructType::create(Context, Lex.getStrVal());2935Entry.second = Lex.getLoc();2936}2937Result = Entry.first;2938Lex.Lex();2939break;2940}29412942case lltok::LocalVarID: {2943// Type ::= %42944std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];29452946// If the type hasn't been defined yet, create a forward definition and2947// remember where that forward def'n was seen (in case it never is defined).2948if (!Entry.first) {2949Entry.first = StructType::create(Context);2950Entry.second = Lex.getLoc();2951}2952Result = Entry.first;2953Lex.Lex();2954break;2955}2956}29572958// parse the type suffixes.2959while (true) {2960switch (Lex.getKind()) {2961// End of type.2962default:2963if (!AllowVoid && Result->isVoidTy())2964return error(TypeLoc, "void type only allowed for function results");2965return false;29662967// Type ::= Type '*'2968case lltok::star:2969if (Result->isLabelTy())2970return tokError("basic block pointers are invalid");2971if (Result->isVoidTy())2972return tokError("pointers to void are invalid - use i8* instead");2973if (!PointerType::isValidElementType(Result))2974return tokError("pointer to this type is invalid");2975Result = PointerType::getUnqual(Result);2976Lex.Lex();2977break;29782979// Type ::= Type 'addrspace' '(' uint32 ')' '*'2980case lltok::kw_addrspace: {2981if (Result->isLabelTy())2982return tokError("basic block pointers are invalid");2983if (Result->isVoidTy())2984return tokError("pointers to void are invalid; use i8* instead");2985if (!PointerType::isValidElementType(Result))2986return tokError("pointer to this type is invalid");2987unsigned AddrSpace;2988if (parseOptionalAddrSpace(AddrSpace) ||2989parseToken(lltok::star, "expected '*' in address space"))2990return true;29912992Result = PointerType::get(Result, AddrSpace);2993break;2994}29952996/// Types '(' ArgTypeListI ')' OptFuncAttrs2997case lltok::lparen:2998if (parseFunctionType(Result))2999return true;3000break;3001}3002}3003}30043005/// parseParameterList3006/// ::= '(' ')'3007/// ::= '(' Arg (',' Arg)* ')'3008/// Arg3009/// ::= Type OptionalAttributes Value OptionalAttributes3010bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,3011PerFunctionState &PFS, bool IsMustTailCall,3012bool InVarArgsFunc) {3013if (parseToken(lltok::lparen, "expected '(' in call"))3014return true;30153016while (Lex.getKind() != lltok::rparen) {3017// If this isn't the first argument, we need a comma.3018if (!ArgList.empty() &&3019parseToken(lltok::comma, "expected ',' in argument list"))3020return true;30213022// parse an ellipsis if this is a musttail call in a variadic function.3023if (Lex.getKind() == lltok::dotdotdot) {3024const char *Msg = "unexpected ellipsis in argument list for ";3025if (!IsMustTailCall)3026return tokError(Twine(Msg) + "non-musttail call");3027if (!InVarArgsFunc)3028return tokError(Twine(Msg) + "musttail call in non-varargs function");3029Lex.Lex(); // Lex the '...', it is purely for readability.3030return parseToken(lltok::rparen, "expected ')' at end of argument list");3031}30323033// parse the argument.3034LocTy ArgLoc;3035Type *ArgTy = nullptr;3036Value *V;3037if (parseType(ArgTy, ArgLoc))3038return true;30393040AttrBuilder ArgAttrs(M->getContext());30413042if (ArgTy->isMetadataTy()) {3043if (parseMetadataAsValue(V, PFS))3044return true;3045} else {3046// Otherwise, handle normal operands.3047if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))3048return true;3049}3050ArgList.push_back(ParamInfo(3051ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));3052}30533054if (IsMustTailCall && InVarArgsFunc)3055return tokError("expected '...' at end of argument list for musttail call "3056"in varargs function");30573058Lex.Lex(); // Lex the ')'.3059return false;3060}30613062/// parseRequiredTypeAttr3063/// ::= attrname(<ty>)3064bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,3065Attribute::AttrKind AttrKind) {3066Type *Ty = nullptr;3067if (!EatIfPresent(AttrToken))3068return true;3069if (!EatIfPresent(lltok::lparen))3070return error(Lex.getLoc(), "expected '('");3071if (parseType(Ty))3072return true;3073if (!EatIfPresent(lltok::rparen))3074return error(Lex.getLoc(), "expected ')'");30753076B.addTypeAttr(AttrKind, Ty);3077return false;3078}30793080/// parseRangeAttr3081/// ::= range(<ty> <n>,<n>)3082bool LLParser::parseRangeAttr(AttrBuilder &B) {3083Lex.Lex();30843085APInt Lower;3086APInt Upper;3087Type *Ty = nullptr;3088LocTy TyLoc;30893090auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {3091if (Lex.getKind() != lltok::APSInt)3092return tokError("expected integer");3093if (Lex.getAPSIntVal().getBitWidth() > BitWidth)3094return tokError(3095"integer is too large for the bit width of specified type");3096Val = Lex.getAPSIntVal().extend(BitWidth);3097Lex.Lex();3098return false;3099};31003101if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))3102return true;3103if (!Ty->isIntegerTy())3104return error(TyLoc, "the range must have integer type!");31053106unsigned BitWidth = Ty->getPrimitiveSizeInBits();31073108if (ParseAPSInt(BitWidth, Lower) ||3109parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))3110return true;3111if (Lower == Upper)3112return tokError("the range should not represent the full or empty set!");31133114if (parseToken(lltok::rparen, "expected ')'"))3115return true;31163117B.addRangeAttr(ConstantRange(Lower, Upper));3118return false;3119}31203121/// parseInitializesAttr3122/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)3123bool LLParser::parseInitializesAttr(AttrBuilder &B) {3124Lex.Lex();31253126auto ParseAPSInt = [&](APInt &Val) {3127if (Lex.getKind() != lltok::APSInt)3128return tokError("expected integer");3129Val = Lex.getAPSIntVal().extend(64);3130Lex.Lex();3131return false;3132};31333134if (parseToken(lltok::lparen, "expected '('"))3135return true;31363137SmallVector<ConstantRange, 2> RangeList;3138// Parse each constant range.3139do {3140APInt Lower, Upper;3141if (parseToken(lltok::lparen, "expected '('"))3142return true;31433144if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||3145ParseAPSInt(Upper))3146return true;31473148if (Lower == Upper)3149return tokError("the range should not represent the full or empty set!");31503151if (parseToken(lltok::rparen, "expected ')'"))3152return true;31533154RangeList.push_back(ConstantRange(Lower, Upper));3155} while (EatIfPresent(lltok::comma));31563157if (parseToken(lltok::rparen, "expected ')'"))3158return true;31593160auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);3161if (!CRLOrNull.has_value())3162return tokError("Invalid (unordered or overlapping) range list");3163B.addInitializesAttr(*CRLOrNull);3164return false;3165}31663167/// parseOptionalOperandBundles3168/// ::= /*empty*/3169/// ::= '[' OperandBundle [, OperandBundle ]* ']'3170///3171/// OperandBundle3172/// ::= bundle-tag '(' ')'3173/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'3174///3175/// bundle-tag ::= String Constant3176bool LLParser::parseOptionalOperandBundles(3177SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {3178LocTy BeginLoc = Lex.getLoc();3179if (!EatIfPresent(lltok::lsquare))3180return false;31813182while (Lex.getKind() != lltok::rsquare) {3183// If this isn't the first operand bundle, we need a comma.3184if (!BundleList.empty() &&3185parseToken(lltok::comma, "expected ',' in input list"))3186return true;31873188std::string Tag;3189if (parseStringConstant(Tag))3190return true;31913192if (parseToken(lltok::lparen, "expected '(' in operand bundle"))3193return true;31943195std::vector<Value *> Inputs;3196while (Lex.getKind() != lltok::rparen) {3197// If this isn't the first input, we need a comma.3198if (!Inputs.empty() &&3199parseToken(lltok::comma, "expected ',' in input list"))3200return true;32013202Type *Ty = nullptr;3203Value *Input = nullptr;3204if (parseType(Ty) || parseValue(Ty, Input, PFS))3205return true;3206Inputs.push_back(Input);3207}32083209BundleList.emplace_back(std::move(Tag), std::move(Inputs));32103211Lex.Lex(); // Lex the ')'.3212}32133214if (BundleList.empty())3215return error(BeginLoc, "operand bundle set must not be empty");32163217Lex.Lex(); // Lex the ']'.3218return false;3219}32203221bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,3222unsigned NextID, unsigned ID) const {3223if (ID < NextID)3224return error(Loc, Kind + " expected to be numbered '" + Prefix +3225Twine(NextID) + "' or greater");32263227return false;3228}32293230/// parseArgumentList - parse the argument list for a function type or function3231/// prototype.3232/// ::= '(' ArgTypeListI ')'3233/// ArgTypeListI3234/// ::= /*empty*/3235/// ::= '...'3236/// ::= ArgTypeList ',' '...'3237/// ::= ArgType (',' ArgType)*3238///3239bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,3240SmallVectorImpl<unsigned> &UnnamedArgNums,3241bool &IsVarArg) {3242unsigned CurValID = 0;3243IsVarArg = false;3244assert(Lex.getKind() == lltok::lparen);3245Lex.Lex(); // eat the (.32463247if (Lex.getKind() != lltok::rparen) {3248do {3249// Handle ... at end of arg list.3250if (EatIfPresent(lltok::dotdotdot)) {3251IsVarArg = true;3252break;3253}32543255// Otherwise must be an argument type.3256LocTy TypeLoc = Lex.getLoc();3257Type *ArgTy = nullptr;3258AttrBuilder Attrs(M->getContext());3259if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))3260return true;32613262if (ArgTy->isVoidTy())3263return error(TypeLoc, "argument can not have void type");32643265std::string Name;3266if (Lex.getKind() == lltok::LocalVar) {3267Name = Lex.getStrVal();3268Lex.Lex();3269} else {3270unsigned ArgID;3271if (Lex.getKind() == lltok::LocalVarID) {3272ArgID = Lex.getUIntVal();3273if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))3274return true;3275Lex.Lex();3276} else {3277ArgID = CurValID;3278}3279UnnamedArgNums.push_back(ArgID);3280CurValID = ArgID + 1;3281}32823283if (!ArgTy->isFirstClassType())3284return error(TypeLoc, "invalid type for function argument");32853286ArgList.emplace_back(TypeLoc, ArgTy,3287AttributeSet::get(ArgTy->getContext(), Attrs),3288std::move(Name));3289} while (EatIfPresent(lltok::comma));3290}32913292return parseToken(lltok::rparen, "expected ')' at end of argument list");3293}32943295/// parseFunctionType3296/// ::= Type ArgumentList OptionalAttrs3297bool LLParser::parseFunctionType(Type *&Result) {3298assert(Lex.getKind() == lltok::lparen);32993300if (!FunctionType::isValidReturnType(Result))3301return tokError("invalid function return type");33023303SmallVector<ArgInfo, 8> ArgList;3304bool IsVarArg;3305SmallVector<unsigned> UnnamedArgNums;3306if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))3307return true;33083309// Reject names on the arguments lists.3310for (const ArgInfo &Arg : ArgList) {3311if (!Arg.Name.empty())3312return error(Arg.Loc, "argument name invalid in function type");3313if (Arg.Attrs.hasAttributes())3314return error(Arg.Loc, "argument attributes invalid in function type");3315}33163317SmallVector<Type*, 16> ArgListTy;3318for (const ArgInfo &Arg : ArgList)3319ArgListTy.push_back(Arg.Ty);33203321Result = FunctionType::get(Result, ArgListTy, IsVarArg);3322return false;3323}33243325/// parseAnonStructType - parse an anonymous struct type, which is inlined into3326/// other structs.3327bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {3328SmallVector<Type*, 8> Elts;3329if (parseStructBody(Elts))3330return true;33313332Result = StructType::get(Context, Elts, Packed);3333return false;3334}33353336/// parseStructDefinition - parse a struct in a 'type' definition.3337bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,3338std::pair<Type *, LocTy> &Entry,3339Type *&ResultTy) {3340// If the type was already defined, diagnose the redefinition.3341if (Entry.first && !Entry.second.isValid())3342return error(TypeLoc, "redefinition of type");33433344// If we have opaque, just return without filling in the definition for the3345// struct. This counts as a definition as far as the .ll file goes.3346if (EatIfPresent(lltok::kw_opaque)) {3347// This type is being defined, so clear the location to indicate this.3348Entry.second = SMLoc();33493350// If this type number has never been uttered, create it.3351if (!Entry.first)3352Entry.first = StructType::create(Context, Name);3353ResultTy = Entry.first;3354return false;3355}33563357// If the type starts with '<', then it is either a packed struct or a vector.3358bool isPacked = EatIfPresent(lltok::less);33593360// If we don't have a struct, then we have a random type alias, which we3361// accept for compatibility with old files. These types are not allowed to be3362// forward referenced and not allowed to be recursive.3363if (Lex.getKind() != lltok::lbrace) {3364if (Entry.first)3365return error(TypeLoc, "forward references to non-struct type");33663367ResultTy = nullptr;3368if (isPacked)3369return parseArrayVectorType(ResultTy, true);3370return parseType(ResultTy);3371}33723373// This type is being defined, so clear the location to indicate this.3374Entry.second = SMLoc();33753376// If this type number has never been uttered, create it.3377if (!Entry.first)3378Entry.first = StructType::create(Context, Name);33793380StructType *STy = cast<StructType>(Entry.first);33813382SmallVector<Type*, 8> Body;3383if (parseStructBody(Body) ||3384(isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))3385return true;33863387STy->setBody(Body, isPacked);3388ResultTy = STy;3389return false;3390}33913392/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.3393/// StructType3394/// ::= '{' '}'3395/// ::= '{' Type (',' Type)* '}'3396/// ::= '<' '{' '}' '>'3397/// ::= '<' '{' Type (',' Type)* '}' '>'3398bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {3399assert(Lex.getKind() == lltok::lbrace);3400Lex.Lex(); // Consume the '{'34013402// Handle the empty struct.3403if (EatIfPresent(lltok::rbrace))3404return false;34053406LocTy EltTyLoc = Lex.getLoc();3407Type *Ty = nullptr;3408if (parseType(Ty))3409return true;3410Body.push_back(Ty);34113412if (!StructType::isValidElementType(Ty))3413return error(EltTyLoc, "invalid element type for struct");34143415while (EatIfPresent(lltok::comma)) {3416EltTyLoc = Lex.getLoc();3417if (parseType(Ty))3418return true;34193420if (!StructType::isValidElementType(Ty))3421return error(EltTyLoc, "invalid element type for struct");34223423Body.push_back(Ty);3424}34253426return parseToken(lltok::rbrace, "expected '}' at end of struct");3427}34283429/// parseArrayVectorType - parse an array or vector type, assuming the first3430/// token has already been consumed.3431/// Type3432/// ::= '[' APSINTVAL 'x' Types ']'3433/// ::= '<' APSINTVAL 'x' Types '>'3434/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'3435bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {3436bool Scalable = false;34373438if (IsVector && Lex.getKind() == lltok::kw_vscale) {3439Lex.Lex(); // consume the 'vscale'3440if (parseToken(lltok::kw_x, "expected 'x' after vscale"))3441return true;34423443Scalable = true;3444}34453446if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||3447Lex.getAPSIntVal().getBitWidth() > 64)3448return tokError("expected number in address space");34493450LocTy SizeLoc = Lex.getLoc();3451uint64_t Size = Lex.getAPSIntVal().getZExtValue();3452Lex.Lex();34533454if (parseToken(lltok::kw_x, "expected 'x' after element count"))3455return true;34563457LocTy TypeLoc = Lex.getLoc();3458Type *EltTy = nullptr;3459if (parseType(EltTy))3460return true;34613462if (parseToken(IsVector ? lltok::greater : lltok::rsquare,3463"expected end of sequential type"))3464return true;34653466if (IsVector) {3467if (Size == 0)3468return error(SizeLoc, "zero element vector is illegal");3469if ((unsigned)Size != Size)3470return error(SizeLoc, "size too large for vector");3471if (!VectorType::isValidElementType(EltTy))3472return error(TypeLoc, "invalid vector element type");3473Result = VectorType::get(EltTy, unsigned(Size), Scalable);3474} else {3475if (!ArrayType::isValidElementType(EltTy))3476return error(TypeLoc, "invalid array element type");3477Result = ArrayType::get(EltTy, Size);3478}3479return false;3480}34813482/// parseTargetExtType - handle target extension type syntax3483/// TargetExtType3484/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'3485///3486/// TargetExtTypeParams3487/// ::= /*empty*/3488/// ::= ',' Type TargetExtTypeParams3489///3490/// TargetExtIntParams3491/// ::= /*empty*/3492/// ::= ',' uint32 TargetExtIntParams3493bool LLParser::parseTargetExtType(Type *&Result) {3494Lex.Lex(); // Eat the 'target' keyword.34953496// Get the mandatory type name.3497std::string TypeName;3498if (parseToken(lltok::lparen, "expected '(' in target extension type") ||3499parseStringConstant(TypeName))3500return true;35013502// Parse all of the integer and type parameters at the same time; the use of3503// SeenInt will allow us to catch cases where type parameters follow integer3504// parameters.3505SmallVector<Type *> TypeParams;3506SmallVector<unsigned> IntParams;3507bool SeenInt = false;3508while (Lex.getKind() == lltok::comma) {3509Lex.Lex(); // Eat the comma.35103511if (Lex.getKind() == lltok::APSInt) {3512SeenInt = true;3513unsigned IntVal;3514if (parseUInt32(IntVal))3515return true;3516IntParams.push_back(IntVal);3517} else if (SeenInt) {3518// The only other kind of parameter we support is type parameters, which3519// must precede the integer parameters. This is therefore an error.3520return tokError("expected uint32 param");3521} else {3522Type *TypeParam;3523if (parseType(TypeParam, /*AllowVoid=*/true))3524return true;3525TypeParams.push_back(TypeParam);3526}3527}35283529if (parseToken(lltok::rparen, "expected ')' in target extension type"))3530return true;35313532Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);3533return false;3534}35353536//===----------------------------------------------------------------------===//3537// Function Semantic Analysis.3538//===----------------------------------------------------------------------===//35393540LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,3541int functionNumber,3542ArrayRef<unsigned> UnnamedArgNums)3543: P(p), F(f), FunctionNumber(functionNumber) {35443545// Insert unnamed arguments into the NumberedVals list.3546auto It = UnnamedArgNums.begin();3547for (Argument &A : F.args()) {3548if (!A.hasName()) {3549unsigned ArgNum = *It++;3550NumberedVals.add(ArgNum, &A);3551}3552}3553}35543555LLParser::PerFunctionState::~PerFunctionState() {3556// If there were any forward referenced non-basicblock values, delete them.35573558for (const auto &P : ForwardRefVals) {3559if (isa<BasicBlock>(P.second.first))3560continue;3561P.second.first->replaceAllUsesWith(3562PoisonValue::get(P.second.first->getType()));3563P.second.first->deleteValue();3564}35653566for (const auto &P : ForwardRefValIDs) {3567if (isa<BasicBlock>(P.second.first))3568continue;3569P.second.first->replaceAllUsesWith(3570PoisonValue::get(P.second.first->getType()));3571P.second.first->deleteValue();3572}3573}35743575bool LLParser::PerFunctionState::finishFunction() {3576if (!ForwardRefVals.empty())3577return P.error(ForwardRefVals.begin()->second.second,3578"use of undefined value '%" + ForwardRefVals.begin()->first +3579"'");3580if (!ForwardRefValIDs.empty())3581return P.error(ForwardRefValIDs.begin()->second.second,3582"use of undefined value '%" +3583Twine(ForwardRefValIDs.begin()->first) + "'");3584return false;3585}35863587/// getVal - Get a value with the specified name or ID, creating a3588/// forward reference record if needed. This can return null if the value3589/// exists but does not have the right type.3590Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,3591LocTy Loc) {3592// Look this name up in the normal function symbol table.3593Value *Val = F.getValueSymbolTable()->lookup(Name);35943595// If this is a forward reference for the value, see if we already created a3596// forward ref record.3597if (!Val) {3598auto I = ForwardRefVals.find(Name);3599if (I != ForwardRefVals.end())3600Val = I->second.first;3601}36023603// If we have the value in the symbol table or fwd-ref table, return it.3604if (Val)3605return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);36063607// Don't make placeholders with invalid type.3608if (!Ty->isFirstClassType()) {3609P.error(Loc, "invalid use of a non-first-class type");3610return nullptr;3611}36123613// Otherwise, create a new forward reference for this value and remember it.3614Value *FwdVal;3615if (Ty->isLabelTy()) {3616FwdVal = BasicBlock::Create(F.getContext(), Name, &F);3617} else {3618FwdVal = new Argument(Ty, Name);3619}3620if (FwdVal->getName() != Name) {3621P.error(Loc, "name is too long which can result in name collisions, "3622"consider making the name shorter or "3623"increasing -non-global-value-max-name-size");3624return nullptr;3625}36263627ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);3628return FwdVal;3629}36303631Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {3632// Look this name up in the normal function symbol table.3633Value *Val = NumberedVals.get(ID);36343635// If this is a forward reference for the value, see if we already created a3636// forward ref record.3637if (!Val) {3638auto I = ForwardRefValIDs.find(ID);3639if (I != ForwardRefValIDs.end())3640Val = I->second.first;3641}36423643// If we have the value in the symbol table or fwd-ref table, return it.3644if (Val)3645return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);36463647if (!Ty->isFirstClassType()) {3648P.error(Loc, "invalid use of a non-first-class type");3649return nullptr;3650}36513652// Otherwise, create a new forward reference for this value and remember it.3653Value *FwdVal;3654if (Ty->isLabelTy()) {3655FwdVal = BasicBlock::Create(F.getContext(), "", &F);3656} else {3657FwdVal = new Argument(Ty);3658}36593660ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);3661return FwdVal;3662}36633664/// setInstName - After an instruction is parsed and inserted into its3665/// basic block, this installs its name.3666bool LLParser::PerFunctionState::setInstName(int NameID,3667const std::string &NameStr,3668LocTy NameLoc, Instruction *Inst) {3669// If this instruction has void type, it cannot have a name or ID specified.3670if (Inst->getType()->isVoidTy()) {3671if (NameID != -1 || !NameStr.empty())3672return P.error(NameLoc, "instructions returning void cannot have a name");3673return false;3674}36753676// If this was a numbered instruction, verify that the instruction is the3677// expected value and resolve any forward references.3678if (NameStr.empty()) {3679// If neither a name nor an ID was specified, just use the next ID.3680if (NameID == -1)3681NameID = NumberedVals.getNext();36823683if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),3684NameID))3685return true;36863687auto FI = ForwardRefValIDs.find(NameID);3688if (FI != ForwardRefValIDs.end()) {3689Value *Sentinel = FI->second.first;3690if (Sentinel->getType() != Inst->getType())3691return P.error(NameLoc, "instruction forward referenced with type '" +3692getTypeString(FI->second.first->getType()) +3693"'");36943695Sentinel->replaceAllUsesWith(Inst);3696Sentinel->deleteValue();3697ForwardRefValIDs.erase(FI);3698}36993700NumberedVals.add(NameID, Inst);3701return false;3702}37033704// Otherwise, the instruction had a name. Resolve forward refs and set it.3705auto FI = ForwardRefVals.find(NameStr);3706if (FI != ForwardRefVals.end()) {3707Value *Sentinel = FI->second.first;3708if (Sentinel->getType() != Inst->getType())3709return P.error(NameLoc, "instruction forward referenced with type '" +3710getTypeString(FI->second.first->getType()) +3711"'");37123713Sentinel->replaceAllUsesWith(Inst);3714Sentinel->deleteValue();3715ForwardRefVals.erase(FI);3716}37173718// Set the name on the instruction.3719Inst->setName(NameStr);37203721if (Inst->getName() != NameStr)3722return P.error(NameLoc, "multiple definition of local value named '" +3723NameStr + "'");3724return false;3725}37263727/// getBB - Get a basic block with the specified name or ID, creating a3728/// forward reference record if needed.3729BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,3730LocTy Loc) {3731return dyn_cast_or_null<BasicBlock>(3732getVal(Name, Type::getLabelTy(F.getContext()), Loc));3733}37343735BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {3736return dyn_cast_or_null<BasicBlock>(3737getVal(ID, Type::getLabelTy(F.getContext()), Loc));3738}37393740/// defineBB - Define the specified basic block, which is either named or3741/// unnamed. If there is an error, this returns null otherwise it returns3742/// the block being defined.3743BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,3744int NameID, LocTy Loc) {3745BasicBlock *BB;3746if (Name.empty()) {3747if (NameID != -1) {3748if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))3749return nullptr;3750} else {3751NameID = NumberedVals.getNext();3752}3753BB = getBB(NameID, Loc);3754if (!BB) {3755P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");3756return nullptr;3757}3758} else {3759BB = getBB(Name, Loc);3760if (!BB) {3761P.error(Loc, "unable to create block named '" + Name + "'");3762return nullptr;3763}3764}37653766// Move the block to the end of the function. Forward ref'd blocks are3767// inserted wherever they happen to be referenced.3768F.splice(F.end(), &F, BB->getIterator());37693770// Remove the block from forward ref sets.3771if (Name.empty()) {3772ForwardRefValIDs.erase(NameID);3773NumberedVals.add(NameID, BB);3774} else {3775// BB forward references are already in the function symbol table.3776ForwardRefVals.erase(Name);3777}37783779return BB;3780}37813782//===----------------------------------------------------------------------===//3783// Constants.3784//===----------------------------------------------------------------------===//37853786/// parseValID - parse an abstract value that doesn't necessarily have a3787/// type implied. For example, if we parse "4" we don't know what integer type3788/// it has. The value will later be combined with its type and checked for3789/// basic correctness. PFS is used to convert function-local operands of3790/// metadata (since metadata operands are not just parsed here but also3791/// converted to values). PFS can be null when we are not parsing metadata3792/// values inside a function.3793bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {3794ID.Loc = Lex.getLoc();3795switch (Lex.getKind()) {3796default:3797return tokError("expected value token");3798case lltok::GlobalID: // @423799ID.UIntVal = Lex.getUIntVal();3800ID.Kind = ValID::t_GlobalID;3801break;3802case lltok::GlobalVar: // @foo3803ID.StrVal = Lex.getStrVal();3804ID.Kind = ValID::t_GlobalName;3805break;3806case lltok::LocalVarID: // %423807ID.UIntVal = Lex.getUIntVal();3808ID.Kind = ValID::t_LocalID;3809break;3810case lltok::LocalVar: // %foo3811ID.StrVal = Lex.getStrVal();3812ID.Kind = ValID::t_LocalName;3813break;3814case lltok::APSInt:3815ID.APSIntVal = Lex.getAPSIntVal();3816ID.Kind = ValID::t_APSInt;3817break;3818case lltok::APFloat:3819ID.APFloatVal = Lex.getAPFloatVal();3820ID.Kind = ValID::t_APFloat;3821break;3822case lltok::kw_true:3823ID.ConstantVal = ConstantInt::getTrue(Context);3824ID.Kind = ValID::t_Constant;3825break;3826case lltok::kw_false:3827ID.ConstantVal = ConstantInt::getFalse(Context);3828ID.Kind = ValID::t_Constant;3829break;3830case lltok::kw_null: ID.Kind = ValID::t_Null; break;3831case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;3832case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;3833case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;3834case lltok::kw_none: ID.Kind = ValID::t_None; break;38353836case lltok::lbrace: {3837// ValID ::= '{' ConstVector '}'3838Lex.Lex();3839SmallVector<Constant*, 16> Elts;3840if (parseGlobalValueVector(Elts) ||3841parseToken(lltok::rbrace, "expected end of struct constant"))3842return true;38433844ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());3845ID.UIntVal = Elts.size();3846memcpy(ID.ConstantStructElts.get(), Elts.data(),3847Elts.size() * sizeof(Elts[0]));3848ID.Kind = ValID::t_ConstantStruct;3849return false;3850}3851case lltok::less: {3852// ValID ::= '<' ConstVector '>' --> Vector.3853// ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.3854Lex.Lex();3855bool isPackedStruct = EatIfPresent(lltok::lbrace);38563857SmallVector<Constant*, 16> Elts;3858LocTy FirstEltLoc = Lex.getLoc();3859if (parseGlobalValueVector(Elts) ||3860(isPackedStruct &&3861parseToken(lltok::rbrace, "expected end of packed struct")) ||3862parseToken(lltok::greater, "expected end of constant"))3863return true;38643865if (isPackedStruct) {3866ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());3867memcpy(ID.ConstantStructElts.get(), Elts.data(),3868Elts.size() * sizeof(Elts[0]));3869ID.UIntVal = Elts.size();3870ID.Kind = ValID::t_PackedConstantStruct;3871return false;3872}38733874if (Elts.empty())3875return error(ID.Loc, "constant vector must not be empty");38763877if (!Elts[0]->getType()->isIntegerTy() &&3878!Elts[0]->getType()->isFloatingPointTy() &&3879!Elts[0]->getType()->isPointerTy())3880return error(3881FirstEltLoc,3882"vector elements must have integer, pointer or floating point type");38833884// Verify that all the vector elements have the same type.3885for (unsigned i = 1, e = Elts.size(); i != e; ++i)3886if (Elts[i]->getType() != Elts[0]->getType())3887return error(FirstEltLoc, "vector element #" + Twine(i) +3888" is not of type '" +3889getTypeString(Elts[0]->getType()));38903891ID.ConstantVal = ConstantVector::get(Elts);3892ID.Kind = ValID::t_Constant;3893return false;3894}3895case lltok::lsquare: { // Array Constant3896Lex.Lex();3897SmallVector<Constant*, 16> Elts;3898LocTy FirstEltLoc = Lex.getLoc();3899if (parseGlobalValueVector(Elts) ||3900parseToken(lltok::rsquare, "expected end of array constant"))3901return true;39023903// Handle empty element.3904if (Elts.empty()) {3905// Use undef instead of an array because it's inconvenient to determine3906// the element type at this point, there being no elements to examine.3907ID.Kind = ValID::t_EmptyArray;3908return false;3909}39103911if (!Elts[0]->getType()->isFirstClassType())3912return error(FirstEltLoc, "invalid array element type: " +3913getTypeString(Elts[0]->getType()));39143915ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());39163917// Verify all elements are correct type!3918for (unsigned i = 0, e = Elts.size(); i != e; ++i) {3919if (Elts[i]->getType() != Elts[0]->getType())3920return error(FirstEltLoc, "array element #" + Twine(i) +3921" is not of type '" +3922getTypeString(Elts[0]->getType()));3923}39243925ID.ConstantVal = ConstantArray::get(ATy, Elts);3926ID.Kind = ValID::t_Constant;3927return false;3928}3929case lltok::kw_c: // c "foo"3930Lex.Lex();3931ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),3932false);3933if (parseToken(lltok::StringConstant, "expected string"))3934return true;3935ID.Kind = ValID::t_Constant;3936return false;39373938case lltok::kw_asm: {3939// ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','3940// STRINGCONSTANT3941bool HasSideEffect, AlignStack, AsmDialect, CanThrow;3942Lex.Lex();3943if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||3944parseOptionalToken(lltok::kw_alignstack, AlignStack) ||3945parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||3946parseOptionalToken(lltok::kw_unwind, CanThrow) ||3947parseStringConstant(ID.StrVal) ||3948parseToken(lltok::comma, "expected comma in inline asm expression") ||3949parseToken(lltok::StringConstant, "expected constraint string"))3950return true;3951ID.StrVal2 = Lex.getStrVal();3952ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |3953(unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);3954ID.Kind = ValID::t_InlineAsm;3955return false;3956}39573958case lltok::kw_blockaddress: {3959// ValID ::= 'blockaddress' '(' @foo ',' %bar ')'3960Lex.Lex();39613962ValID Fn, Label;39633964if (parseToken(lltok::lparen, "expected '(' in block address expression") ||3965parseValID(Fn, PFS) ||3966parseToken(lltok::comma,3967"expected comma in block address expression") ||3968parseValID(Label, PFS) ||3969parseToken(lltok::rparen, "expected ')' in block address expression"))3970return true;39713972if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)3973return error(Fn.Loc, "expected function name in blockaddress");3974if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)3975return error(Label.Loc, "expected basic block name in blockaddress");39763977// Try to find the function (but skip it if it's forward-referenced).3978GlobalValue *GV = nullptr;3979if (Fn.Kind == ValID::t_GlobalID) {3980GV = NumberedVals.get(Fn.UIntVal);3981} else if (!ForwardRefVals.count(Fn.StrVal)) {3982GV = M->getNamedValue(Fn.StrVal);3983}3984Function *F = nullptr;3985if (GV) {3986// Confirm that it's actually a function with a definition.3987if (!isa<Function>(GV))3988return error(Fn.Loc, "expected function name in blockaddress");3989F = cast<Function>(GV);3990if (F->isDeclaration())3991return error(Fn.Loc, "cannot take blockaddress inside a declaration");3992}39933994if (!F) {3995// Make a global variable as a placeholder for this reference.3996GlobalValue *&FwdRef =3997ForwardRefBlockAddresses.insert(std::make_pair(3998std::move(Fn),3999std::map<ValID, GlobalValue *>()))4000.first->second.insert(std::make_pair(std::move(Label), nullptr))4001.first->second;4002if (!FwdRef) {4003unsigned FwdDeclAS;4004if (ExpectedTy) {4005// If we know the type that the blockaddress is being assigned to,4006// we can use the address space of that type.4007if (!ExpectedTy->isPointerTy())4008return error(ID.Loc,4009"type of blockaddress must be a pointer and not '" +4010getTypeString(ExpectedTy) + "'");4011FwdDeclAS = ExpectedTy->getPointerAddressSpace();4012} else if (PFS) {4013// Otherwise, we default the address space of the current function.4014FwdDeclAS = PFS->getFunction().getAddressSpace();4015} else {4016llvm_unreachable("Unknown address space for blockaddress");4017}4018FwdRef = new GlobalVariable(4019*M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,4020nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);4021}40224023ID.ConstantVal = FwdRef;4024ID.Kind = ValID::t_Constant;4025return false;4026}40274028// We found the function; now find the basic block. Don't use PFS, since we4029// might be inside a constant expression.4030BasicBlock *BB;4031if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {4032if (Label.Kind == ValID::t_LocalID)4033BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);4034else4035BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);4036if (!BB)4037return error(Label.Loc, "referenced value is not a basic block");4038} else {4039if (Label.Kind == ValID::t_LocalID)4040return error(Label.Loc, "cannot take address of numeric label after "4041"the function is defined");4042BB = dyn_cast_or_null<BasicBlock>(4043F->getValueSymbolTable()->lookup(Label.StrVal));4044if (!BB)4045return error(Label.Loc, "referenced value is not a basic block");4046}40474048ID.ConstantVal = BlockAddress::get(F, BB);4049ID.Kind = ValID::t_Constant;4050return false;4051}40524053case lltok::kw_dso_local_equivalent: {4054// ValID ::= 'dso_local_equivalent' @foo4055Lex.Lex();40564057ValID Fn;40584059if (parseValID(Fn, PFS))4060return true;40614062if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)4063return error(Fn.Loc,4064"expected global value name in dso_local_equivalent");40654066// Try to find the function (but skip it if it's forward-referenced).4067GlobalValue *GV = nullptr;4068if (Fn.Kind == ValID::t_GlobalID) {4069GV = NumberedVals.get(Fn.UIntVal);4070} else if (!ForwardRefVals.count(Fn.StrVal)) {4071GV = M->getNamedValue(Fn.StrVal);4072}40734074if (!GV) {4075// Make a placeholder global variable as a placeholder for this reference.4076auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)4077? ForwardRefDSOLocalEquivalentIDs4078: ForwardRefDSOLocalEquivalentNames;4079GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;4080if (!FwdRef) {4081FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,4082GlobalValue::InternalLinkage, nullptr, "",4083nullptr, GlobalValue::NotThreadLocal);4084}40854086ID.ConstantVal = FwdRef;4087ID.Kind = ValID::t_Constant;4088return false;4089}40904091if (!GV->getValueType()->isFunctionTy())4092return error(Fn.Loc, "expected a function, alias to function, or ifunc "4093"in dso_local_equivalent");40944095ID.ConstantVal = DSOLocalEquivalent::get(GV);4096ID.Kind = ValID::t_Constant;4097return false;4098}40994100case lltok::kw_no_cfi: {4101// ValID ::= 'no_cfi' @foo4102Lex.Lex();41034104if (parseValID(ID, PFS))4105return true;41064107if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)4108return error(ID.Loc, "expected global value name in no_cfi");41094110ID.NoCFI = true;4111return false;4112}4113case lltok::kw_ptrauth: {4114// ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>4115// (',' i64 <disc> (',' ptr addrdisc)? )? ')'4116Lex.Lex();41174118Constant *Ptr, *Key;4119Constant *Disc = nullptr, *AddrDisc = nullptr;41204121if (parseToken(lltok::lparen,4122"expected '(' in constant ptrauth expression") ||4123parseGlobalTypeAndValue(Ptr) ||4124parseToken(lltok::comma,4125"expected comma in constant ptrauth expression") ||4126parseGlobalTypeAndValue(Key))4127return true;4128// If present, parse the optional disc/addrdisc.4129if (EatIfPresent(lltok::comma))4130if (parseGlobalTypeAndValue(Disc) ||4131(EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))4132return true;4133if (parseToken(lltok::rparen,4134"expected ')' in constant ptrauth expression"))4135return true;41364137if (!Ptr->getType()->isPointerTy())4138return error(ID.Loc, "constant ptrauth base pointer must be a pointer");41394140auto *KeyC = dyn_cast<ConstantInt>(Key);4141if (!KeyC || KeyC->getBitWidth() != 32)4142return error(ID.Loc, "constant ptrauth key must be i32 constant");41434144ConstantInt *DiscC = nullptr;4145if (Disc) {4146DiscC = dyn_cast<ConstantInt>(Disc);4147if (!DiscC || DiscC->getBitWidth() != 64)4148return error(4149ID.Loc,4150"constant ptrauth integer discriminator must be i64 constant");4151} else {4152DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);4153}41544155if (AddrDisc) {4156if (!AddrDisc->getType()->isPointerTy())4157return error(4158ID.Loc, "constant ptrauth address discriminator must be a pointer");4159} else {4160AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));4161}41624163ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);4164ID.Kind = ValID::t_Constant;4165return false;4166}41674168case lltok::kw_trunc:4169case lltok::kw_bitcast:4170case lltok::kw_addrspacecast:4171case lltok::kw_inttoptr:4172case lltok::kw_ptrtoint: {4173unsigned Opc = Lex.getUIntVal();4174Type *DestTy = nullptr;4175Constant *SrcVal;4176Lex.Lex();4177if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||4178parseGlobalTypeAndValue(SrcVal) ||4179parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||4180parseType(DestTy) ||4181parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))4182return true;4183if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))4184return error(ID.Loc, "invalid cast opcode for cast from '" +4185getTypeString(SrcVal->getType()) + "' to '" +4186getTypeString(DestTy) + "'");4187ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,4188SrcVal, DestTy);4189ID.Kind = ValID::t_Constant;4190return false;4191}4192case lltok::kw_extractvalue:4193return error(ID.Loc, "extractvalue constexprs are no longer supported");4194case lltok::kw_insertvalue:4195return error(ID.Loc, "insertvalue constexprs are no longer supported");4196case lltok::kw_udiv:4197return error(ID.Loc, "udiv constexprs are no longer supported");4198case lltok::kw_sdiv:4199return error(ID.Loc, "sdiv constexprs are no longer supported");4200case lltok::kw_urem:4201return error(ID.Loc, "urem constexprs are no longer supported");4202case lltok::kw_srem:4203return error(ID.Loc, "srem constexprs are no longer supported");4204case lltok::kw_fadd:4205return error(ID.Loc, "fadd constexprs are no longer supported");4206case lltok::kw_fsub:4207return error(ID.Loc, "fsub constexprs are no longer supported");4208case lltok::kw_fmul:4209return error(ID.Loc, "fmul constexprs are no longer supported");4210case lltok::kw_fdiv:4211return error(ID.Loc, "fdiv constexprs are no longer supported");4212case lltok::kw_frem:4213return error(ID.Loc, "frem constexprs are no longer supported");4214case lltok::kw_and:4215return error(ID.Loc, "and constexprs are no longer supported");4216case lltok::kw_or:4217return error(ID.Loc, "or constexprs are no longer supported");4218case lltok::kw_lshr:4219return error(ID.Loc, "lshr constexprs are no longer supported");4220case lltok::kw_ashr:4221return error(ID.Loc, "ashr constexprs are no longer supported");4222case lltok::kw_shl:4223return error(ID.Loc, "shl constexprs are no longer supported");4224case lltok::kw_fneg:4225return error(ID.Loc, "fneg constexprs are no longer supported");4226case lltok::kw_select:4227return error(ID.Loc, "select constexprs are no longer supported");4228case lltok::kw_zext:4229return error(ID.Loc, "zext constexprs are no longer supported");4230case lltok::kw_sext:4231return error(ID.Loc, "sext constexprs are no longer supported");4232case lltok::kw_fptrunc:4233return error(ID.Loc, "fptrunc constexprs are no longer supported");4234case lltok::kw_fpext:4235return error(ID.Loc, "fpext constexprs are no longer supported");4236case lltok::kw_uitofp:4237return error(ID.Loc, "uitofp constexprs are no longer supported");4238case lltok::kw_sitofp:4239return error(ID.Loc, "sitofp constexprs are no longer supported");4240case lltok::kw_fptoui:4241return error(ID.Loc, "fptoui constexprs are no longer supported");4242case lltok::kw_fptosi:4243return error(ID.Loc, "fptosi constexprs are no longer supported");4244case lltok::kw_icmp:4245return error(ID.Loc, "icmp constexprs are no longer supported");4246case lltok::kw_fcmp:4247return error(ID.Loc, "fcmp constexprs are no longer supported");42484249// Binary Operators.4250case lltok::kw_add:4251case lltok::kw_sub:4252case lltok::kw_mul:4253case lltok::kw_xor: {4254bool NUW = false;4255bool NSW = false;4256unsigned Opc = Lex.getUIntVal();4257Constant *Val0, *Val1;4258Lex.Lex();4259if (Opc == Instruction::Add || Opc == Instruction::Sub ||4260Opc == Instruction::Mul) {4261if (EatIfPresent(lltok::kw_nuw))4262NUW = true;4263if (EatIfPresent(lltok::kw_nsw)) {4264NSW = true;4265if (EatIfPresent(lltok::kw_nuw))4266NUW = true;4267}4268}4269if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||4270parseGlobalTypeAndValue(Val0) ||4271parseToken(lltok::comma, "expected comma in binary constantexpr") ||4272parseGlobalTypeAndValue(Val1) ||4273parseToken(lltok::rparen, "expected ')' in binary constantexpr"))4274return true;4275if (Val0->getType() != Val1->getType())4276return error(ID.Loc, "operands of constexpr must have same type");4277// Check that the type is valid for the operator.4278if (!Val0->getType()->isIntOrIntVectorTy())4279return error(ID.Loc,4280"constexpr requires integer or integer vector operands");4281unsigned Flags = 0;4282if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;4283if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;4284ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);4285ID.Kind = ValID::t_Constant;4286return false;4287}42884289case lltok::kw_splat: {4290Lex.Lex();4291if (parseToken(lltok::lparen, "expected '(' after vector splat"))4292return true;4293Constant *C;4294if (parseGlobalTypeAndValue(C))4295return true;4296if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))4297return true;42984299ID.ConstantVal = C;4300ID.Kind = ValID::t_ConstantSplat;4301return false;4302}43034304case lltok::kw_getelementptr:4305case lltok::kw_shufflevector:4306case lltok::kw_insertelement:4307case lltok::kw_extractelement: {4308unsigned Opc = Lex.getUIntVal();4309SmallVector<Constant*, 16> Elts;4310GEPNoWrapFlags NW;4311bool HasInRange = false;4312APSInt InRangeStart;4313APSInt InRangeEnd;4314Type *Ty;4315Lex.Lex();43164317if (Opc == Instruction::GetElementPtr) {4318while (true) {4319if (EatIfPresent(lltok::kw_inbounds))4320NW |= GEPNoWrapFlags::inBounds();4321else if (EatIfPresent(lltok::kw_nusw))4322NW |= GEPNoWrapFlags::noUnsignedSignedWrap();4323else if (EatIfPresent(lltok::kw_nuw))4324NW |= GEPNoWrapFlags::noUnsignedWrap();4325else4326break;4327}43284329if (EatIfPresent(lltok::kw_inrange)) {4330if (parseToken(lltok::lparen, "expected '('"))4331return true;4332if (Lex.getKind() != lltok::APSInt)4333return tokError("expected integer");4334InRangeStart = Lex.getAPSIntVal();4335Lex.Lex();4336if (parseToken(lltok::comma, "expected ','"))4337return true;4338if (Lex.getKind() != lltok::APSInt)4339return tokError("expected integer");4340InRangeEnd = Lex.getAPSIntVal();4341Lex.Lex();4342if (parseToken(lltok::rparen, "expected ')'"))4343return true;4344HasInRange = true;4345}4346}43474348if (parseToken(lltok::lparen, "expected '(' in constantexpr"))4349return true;43504351if (Opc == Instruction::GetElementPtr) {4352if (parseType(Ty) ||4353parseToken(lltok::comma, "expected comma after getelementptr's type"))4354return true;4355}43564357if (parseGlobalValueVector(Elts) ||4358parseToken(lltok::rparen, "expected ')' in constantexpr"))4359return true;43604361if (Opc == Instruction::GetElementPtr) {4362if (Elts.size() == 0 ||4363!Elts[0]->getType()->isPtrOrPtrVectorTy())4364return error(ID.Loc, "base of getelementptr must be a pointer");43654366Type *BaseType = Elts[0]->getType();4367std::optional<ConstantRange> InRange;4368if (HasInRange) {4369unsigned IndexWidth =4370M->getDataLayout().getIndexTypeSizeInBits(BaseType);4371InRangeStart = InRangeStart.extOrTrunc(IndexWidth);4372InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);4373if (InRangeStart.sge(InRangeEnd))4374return error(ID.Loc, "expected end to be larger than start");4375InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);4376}43774378unsigned GEPWidth =4379BaseType->isVectorTy()4380? cast<FixedVectorType>(BaseType)->getNumElements()4381: 0;43824383ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());4384for (Constant *Val : Indices) {4385Type *ValTy = Val->getType();4386if (!ValTy->isIntOrIntVectorTy())4387return error(ID.Loc, "getelementptr index must be an integer");4388if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {4389unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();4390if (GEPWidth && (ValNumEl != GEPWidth))4391return error(4392ID.Loc,4393"getelementptr vector index has a wrong number of elements");4394// GEPWidth may have been unknown because the base is a scalar,4395// but it is known now.4396GEPWidth = ValNumEl;4397}4398}43994400SmallPtrSet<Type*, 4> Visited;4401if (!Indices.empty() && !Ty->isSized(&Visited))4402return error(ID.Loc, "base element of getelementptr must be sized");44034404if (!GetElementPtrInst::getIndexedType(Ty, Indices))4405return error(ID.Loc, "invalid getelementptr indices");44064407ID.ConstantVal =4408ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);4409} else if (Opc == Instruction::ShuffleVector) {4410if (Elts.size() != 3)4411return error(ID.Loc, "expected three operands to shufflevector");4412if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))4413return error(ID.Loc, "invalid operands to shufflevector");4414SmallVector<int, 16> Mask;4415ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);4416ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);4417} else if (Opc == Instruction::ExtractElement) {4418if (Elts.size() != 2)4419return error(ID.Loc, "expected two operands to extractelement");4420if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))4421return error(ID.Loc, "invalid extractelement operands");4422ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);4423} else {4424assert(Opc == Instruction::InsertElement && "Unknown opcode");4425if (Elts.size() != 3)4426return error(ID.Loc, "expected three operands to insertelement");4427if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))4428return error(ID.Loc, "invalid insertelement operands");4429ID.ConstantVal =4430ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);4431}44324433ID.Kind = ValID::t_Constant;4434return false;4435}4436}44374438Lex.Lex();4439return false;4440}44414442/// parseGlobalValue - parse a global value with the specified type.4443bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {4444C = nullptr;4445ValID ID;4446Value *V = nullptr;4447bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||4448convertValIDToValue(Ty, ID, V, nullptr);4449if (V && !(C = dyn_cast<Constant>(V)))4450return error(ID.Loc, "global values must be constants");4451return Parsed;4452}44534454bool LLParser::parseGlobalTypeAndValue(Constant *&V) {4455Type *Ty = nullptr;4456return parseType(Ty) || parseGlobalValue(Ty, V);4457}44584459bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {4460C = nullptr;44614462LocTy KwLoc = Lex.getLoc();4463if (!EatIfPresent(lltok::kw_comdat))4464return false;44654466if (EatIfPresent(lltok::lparen)) {4467if (Lex.getKind() != lltok::ComdatVar)4468return tokError("expected comdat variable");4469C = getComdat(Lex.getStrVal(), Lex.getLoc());4470Lex.Lex();4471if (parseToken(lltok::rparen, "expected ')' after comdat var"))4472return true;4473} else {4474if (GlobalName.empty())4475return tokError("comdat cannot be unnamed");4476C = getComdat(std::string(GlobalName), KwLoc);4477}44784479return false;4480}44814482/// parseGlobalValueVector4483/// ::= /*empty*/4484/// ::= TypeAndValue (',' TypeAndValue)*4485bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {4486// Empty list.4487if (Lex.getKind() == lltok::rbrace ||4488Lex.getKind() == lltok::rsquare ||4489Lex.getKind() == lltok::greater ||4490Lex.getKind() == lltok::rparen)4491return false;44924493do {4494// Let the caller deal with inrange.4495if (Lex.getKind() == lltok::kw_inrange)4496return false;44974498Constant *C;4499if (parseGlobalTypeAndValue(C))4500return true;4501Elts.push_back(C);4502} while (EatIfPresent(lltok::comma));45034504return false;4505}45064507bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {4508SmallVector<Metadata *, 16> Elts;4509if (parseMDNodeVector(Elts))4510return true;45114512MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);4513return false;4514}45154516/// MDNode:4517/// ::= !{ ... }4518/// ::= !74519/// ::= !DILocation(...)4520bool LLParser::parseMDNode(MDNode *&N) {4521if (Lex.getKind() == lltok::MetadataVar)4522return parseSpecializedMDNode(N);45234524return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);4525}45264527bool LLParser::parseMDNodeTail(MDNode *&N) {4528// !{ ... }4529if (Lex.getKind() == lltok::lbrace)4530return parseMDTuple(N);45314532// !424533return parseMDNodeID(N);4534}45354536namespace {45374538/// Structure to represent an optional metadata field.4539template <class FieldTy> struct MDFieldImpl {4540typedef MDFieldImpl ImplTy;4541FieldTy Val;4542bool Seen;45434544void assign(FieldTy Val) {4545Seen = true;4546this->Val = std::move(Val);4547}45484549explicit MDFieldImpl(FieldTy Default)4550: Val(std::move(Default)), Seen(false) {}4551};45524553/// Structure to represent an optional metadata field that4554/// can be of either type (A or B) and encapsulates the4555/// MD<typeofA>Field and MD<typeofB>Field structs, so not4556/// to reimplement the specifics for representing each Field.4557template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {4558typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;4559FieldTypeA A;4560FieldTypeB B;4561bool Seen;45624563enum {4564IsInvalid = 0,4565IsTypeA = 1,4566IsTypeB = 24567} WhatIs;45684569void assign(FieldTypeA A) {4570Seen = true;4571this->A = std::move(A);4572WhatIs = IsTypeA;4573}45744575void assign(FieldTypeB B) {4576Seen = true;4577this->B = std::move(B);4578WhatIs = IsTypeB;4579}45804581explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)4582: A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),4583WhatIs(IsInvalid) {}4584};45854586struct MDUnsignedField : public MDFieldImpl<uint64_t> {4587uint64_t Max;45884589MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)4590: ImplTy(Default), Max(Max) {}4591};45924593struct LineField : public MDUnsignedField {4594LineField() : MDUnsignedField(0, UINT32_MAX) {}4595};45964597struct ColumnField : public MDUnsignedField {4598ColumnField() : MDUnsignedField(0, UINT16_MAX) {}4599};46004601struct DwarfTagField : public MDUnsignedField {4602DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}4603DwarfTagField(dwarf::Tag DefaultTag)4604: MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}4605};46064607struct DwarfMacinfoTypeField : public MDUnsignedField {4608DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}4609DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)4610: MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}4611};46124613struct DwarfAttEncodingField : public MDUnsignedField {4614DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}4615};46164617struct DwarfVirtualityField : public MDUnsignedField {4618DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}4619};46204621struct DwarfLangField : public MDUnsignedField {4622DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}4623};46244625struct DwarfCCField : public MDUnsignedField {4626DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}4627};46284629struct EmissionKindField : public MDUnsignedField {4630EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}4631};46324633struct NameTableKindField : public MDUnsignedField {4634NameTableKindField()4635: MDUnsignedField(46360, (unsigned)4637DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}4638};46394640struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {4641DIFlagField() : MDFieldImpl(DINode::FlagZero) {}4642};46434644struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {4645DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}4646};46474648struct MDAPSIntField : public MDFieldImpl<APSInt> {4649MDAPSIntField() : ImplTy(APSInt()) {}4650};46514652struct MDSignedField : public MDFieldImpl<int64_t> {4653int64_t Min = INT64_MIN;4654int64_t Max = INT64_MAX;46554656MDSignedField(int64_t Default = 0)4657: ImplTy(Default) {}4658MDSignedField(int64_t Default, int64_t Min, int64_t Max)4659: ImplTy(Default), Min(Min), Max(Max) {}4660};46614662struct MDBoolField : public MDFieldImpl<bool> {4663MDBoolField(bool Default = false) : ImplTy(Default) {}4664};46654666struct MDField : public MDFieldImpl<Metadata *> {4667bool AllowNull;46684669MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}4670};46714672struct MDStringField : public MDFieldImpl<MDString *> {4673bool AllowEmpty;4674MDStringField(bool AllowEmpty = true)4675: ImplTy(nullptr), AllowEmpty(AllowEmpty) {}4676};46774678struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {4679MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}4680};46814682struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {4683ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}4684};46854686struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {4687MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)4688: ImplTy(MDSignedField(Default), MDField(AllowNull)) {}46894690MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,4691bool AllowNull = true)4692: ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}46934694bool isMDSignedField() const { return WhatIs == IsTypeA; }4695bool isMDField() const { return WhatIs == IsTypeB; }4696int64_t getMDSignedValue() const {4697assert(isMDSignedField() && "Wrong field type");4698return A.Val;4699}4700Metadata *getMDFieldValue() const {4701assert(isMDField() && "Wrong field type");4702return B.Val;4703}4704};47054706} // end anonymous namespace47074708namespace llvm {47094710template <>4711bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {4712if (Lex.getKind() != lltok::APSInt)4713return tokError("expected integer");47144715Result.assign(Lex.getAPSIntVal());4716Lex.Lex();4717return false;4718}47194720template <>4721bool LLParser::parseMDField(LocTy Loc, StringRef Name,4722MDUnsignedField &Result) {4723if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())4724return tokError("expected unsigned integer");47254726auto &U = Lex.getAPSIntVal();4727if (U.ugt(Result.Max))4728return tokError("value for '" + Name + "' too large, limit is " +4729Twine(Result.Max));4730Result.assign(U.getZExtValue());4731assert(Result.Val <= Result.Max && "Expected value in range");4732Lex.Lex();4733return false;4734}47354736template <>4737bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {4738return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));4739}4740template <>4741bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {4742return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));4743}47444745template <>4746bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {4747if (Lex.getKind() == lltok::APSInt)4748return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));47494750if (Lex.getKind() != lltok::DwarfTag)4751return tokError("expected DWARF tag");47524753unsigned Tag = dwarf::getTag(Lex.getStrVal());4754if (Tag == dwarf::DW_TAG_invalid)4755return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");4756assert(Tag <= Result.Max && "Expected valid DWARF tag");47574758Result.assign(Tag);4759Lex.Lex();4760return false;4761}47624763template <>4764bool LLParser::parseMDField(LocTy Loc, StringRef Name,4765DwarfMacinfoTypeField &Result) {4766if (Lex.getKind() == lltok::APSInt)4767return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));47684769if (Lex.getKind() != lltok::DwarfMacinfo)4770return tokError("expected DWARF macinfo type");47714772unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());4773if (Macinfo == dwarf::DW_MACINFO_invalid)4774return tokError("invalid DWARF macinfo type" + Twine(" '") +4775Lex.getStrVal() + "'");4776assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");47774778Result.assign(Macinfo);4779Lex.Lex();4780return false;4781}47824783template <>4784bool LLParser::parseMDField(LocTy Loc, StringRef Name,4785DwarfVirtualityField &Result) {4786if (Lex.getKind() == lltok::APSInt)4787return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));47884789if (Lex.getKind() != lltok::DwarfVirtuality)4790return tokError("expected DWARF virtuality code");47914792unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());4793if (Virtuality == dwarf::DW_VIRTUALITY_invalid)4794return tokError("invalid DWARF virtuality code" + Twine(" '") +4795Lex.getStrVal() + "'");4796assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");4797Result.assign(Virtuality);4798Lex.Lex();4799return false;4800}48014802template <>4803bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {4804if (Lex.getKind() == lltok::APSInt)4805return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));48064807if (Lex.getKind() != lltok::DwarfLang)4808return tokError("expected DWARF language");48094810unsigned Lang = dwarf::getLanguage(Lex.getStrVal());4811if (!Lang)4812return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +4813"'");4814assert(Lang <= Result.Max && "Expected valid DWARF language");4815Result.assign(Lang);4816Lex.Lex();4817return false;4818}48194820template <>4821bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {4822if (Lex.getKind() == lltok::APSInt)4823return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));48244825if (Lex.getKind() != lltok::DwarfCC)4826return tokError("expected DWARF calling convention");48274828unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());4829if (!CC)4830return tokError("invalid DWARF calling convention" + Twine(" '") +4831Lex.getStrVal() + "'");4832assert(CC <= Result.Max && "Expected valid DWARF calling convention");4833Result.assign(CC);4834Lex.Lex();4835return false;4836}48374838template <>4839bool LLParser::parseMDField(LocTy Loc, StringRef Name,4840EmissionKindField &Result) {4841if (Lex.getKind() == lltok::APSInt)4842return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));48434844if (Lex.getKind() != lltok::EmissionKind)4845return tokError("expected emission kind");48464847auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());4848if (!Kind)4849return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +4850"'");4851assert(*Kind <= Result.Max && "Expected valid emission kind");4852Result.assign(*Kind);4853Lex.Lex();4854return false;4855}48564857template <>4858bool LLParser::parseMDField(LocTy Loc, StringRef Name,4859NameTableKindField &Result) {4860if (Lex.getKind() == lltok::APSInt)4861return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));48624863if (Lex.getKind() != lltok::NameTableKind)4864return tokError("expected nameTable kind");48654866auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());4867if (!Kind)4868return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +4869"'");4870assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");4871Result.assign((unsigned)*Kind);4872Lex.Lex();4873return false;4874}48754876template <>4877bool LLParser::parseMDField(LocTy Loc, StringRef Name,4878DwarfAttEncodingField &Result) {4879if (Lex.getKind() == lltok::APSInt)4880return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));48814882if (Lex.getKind() != lltok::DwarfAttEncoding)4883return tokError("expected DWARF type attribute encoding");48844885unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());4886if (!Encoding)4887return tokError("invalid DWARF type attribute encoding" + Twine(" '") +4888Lex.getStrVal() + "'");4889assert(Encoding <= Result.Max && "Expected valid DWARF language");4890Result.assign(Encoding);4891Lex.Lex();4892return false;4893}48944895/// DIFlagField4896/// ::= uint324897/// ::= DIFlagVector4898/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic4899template <>4900bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {49014902// parser for a single flag.4903auto parseFlag = [&](DINode::DIFlags &Val) {4904if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {4905uint32_t TempVal = static_cast<uint32_t>(Val);4906bool Res = parseUInt32(TempVal);4907Val = static_cast<DINode::DIFlags>(TempVal);4908return Res;4909}49104911if (Lex.getKind() != lltok::DIFlag)4912return tokError("expected debug info flag");49134914Val = DINode::getFlag(Lex.getStrVal());4915if (!Val)4916return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +4917"'");4918Lex.Lex();4919return false;4920};49214922// parse the flags and combine them together.4923DINode::DIFlags Combined = DINode::FlagZero;4924do {4925DINode::DIFlags Val;4926if (parseFlag(Val))4927return true;4928Combined |= Val;4929} while (EatIfPresent(lltok::bar));49304931Result.assign(Combined);4932return false;4933}49344935/// DISPFlagField4936/// ::= uint324937/// ::= DISPFlagVector4938/// ::= DISPFlagVector '|' DISPFlag* '|' uint324939template <>4940bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {49414942// parser for a single flag.4943auto parseFlag = [&](DISubprogram::DISPFlags &Val) {4944if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {4945uint32_t TempVal = static_cast<uint32_t>(Val);4946bool Res = parseUInt32(TempVal);4947Val = static_cast<DISubprogram::DISPFlags>(TempVal);4948return Res;4949}49504951if (Lex.getKind() != lltok::DISPFlag)4952return tokError("expected debug info flag");49534954Val = DISubprogram::getFlag(Lex.getStrVal());4955if (!Val)4956return tokError(Twine("invalid subprogram debug info flag '") +4957Lex.getStrVal() + "'");4958Lex.Lex();4959return false;4960};49614962// parse the flags and combine them together.4963DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;4964do {4965DISubprogram::DISPFlags Val;4966if (parseFlag(Val))4967return true;4968Combined |= Val;4969} while (EatIfPresent(lltok::bar));49704971Result.assign(Combined);4972return false;4973}49744975template <>4976bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {4977if (Lex.getKind() != lltok::APSInt)4978return tokError("expected signed integer");49794980auto &S = Lex.getAPSIntVal();4981if (S < Result.Min)4982return tokError("value for '" + Name + "' too small, limit is " +4983Twine(Result.Min));4984if (S > Result.Max)4985return tokError("value for '" + Name + "' too large, limit is " +4986Twine(Result.Max));4987Result.assign(S.getExtValue());4988assert(Result.Val >= Result.Min && "Expected value in range");4989assert(Result.Val <= Result.Max && "Expected value in range");4990Lex.Lex();4991return false;4992}49934994template <>4995bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {4996switch (Lex.getKind()) {4997default:4998return tokError("expected 'true' or 'false'");4999case lltok::kw_true:5000Result.assign(true);5001break;5002case lltok::kw_false:5003Result.assign(false);5004break;5005}5006Lex.Lex();5007return false;5008}50095010template <>5011bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {5012if (Lex.getKind() == lltok::kw_null) {5013if (!Result.AllowNull)5014return tokError("'" + Name + "' cannot be null");5015Lex.Lex();5016Result.assign(nullptr);5017return false;5018}50195020Metadata *MD;5021if (parseMetadata(MD, nullptr))5022return true;50235024Result.assign(MD);5025return false;5026}50275028template <>5029bool LLParser::parseMDField(LocTy Loc, StringRef Name,5030MDSignedOrMDField &Result) {5031// Try to parse a signed int.5032if (Lex.getKind() == lltok::APSInt) {5033MDSignedField Res = Result.A;5034if (!parseMDField(Loc, Name, Res)) {5035Result.assign(Res);5036return false;5037}5038return true;5039}50405041// Otherwise, try to parse as an MDField.5042MDField Res = Result.B;5043if (!parseMDField(Loc, Name, Res)) {5044Result.assign(Res);5045return false;5046}50475048return true;5049}50505051template <>5052bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {5053LocTy ValueLoc = Lex.getLoc();5054std::string S;5055if (parseStringConstant(S))5056return true;50575058if (!Result.AllowEmpty && S.empty())5059return error(ValueLoc, "'" + Name + "' cannot be empty");50605061Result.assign(S.empty() ? nullptr : MDString::get(Context, S));5062return false;5063}50645065template <>5066bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {5067SmallVector<Metadata *, 4> MDs;5068if (parseMDNodeVector(MDs))5069return true;50705071Result.assign(std::move(MDs));5072return false;5073}50745075template <>5076bool LLParser::parseMDField(LocTy Loc, StringRef Name,5077ChecksumKindField &Result) {5078std::optional<DIFile::ChecksumKind> CSKind =5079DIFile::getChecksumKind(Lex.getStrVal());50805081if (Lex.getKind() != lltok::ChecksumKind || !CSKind)5082return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +5083"'");50845085Result.assign(*CSKind);5086Lex.Lex();5087return false;5088}50895090} // end namespace llvm50915092template <class ParserTy>5093bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {5094do {5095if (Lex.getKind() != lltok::LabelStr)5096return tokError("expected field label here");50975098if (ParseField())5099return true;5100} while (EatIfPresent(lltok::comma));51015102return false;5103}51045105template <class ParserTy>5106bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {5107assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");5108Lex.Lex();51095110if (parseToken(lltok::lparen, "expected '(' here"))5111return true;5112if (Lex.getKind() != lltok::rparen)5113if (parseMDFieldsImplBody(ParseField))5114return true;51155116ClosingLoc = Lex.getLoc();5117return parseToken(lltok::rparen, "expected ')' here");5118}51195120template <class FieldTy>5121bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {5122if (Result.Seen)5123return tokError("field '" + Name + "' cannot be specified more than once");51245125LocTy Loc = Lex.getLoc();5126Lex.Lex();5127return parseMDField(Loc, Name, Result);5128}51295130bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {5131assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");51325133#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \5134if (Lex.getStrVal() == #CLASS) \5135return parse##CLASS(N, IsDistinct);5136#include "llvm/IR/Metadata.def"51375138return tokError("expected metadata type");5139}51405141#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT5142#define NOP_FIELD(NAME, TYPE, INIT)5143#define REQUIRE_FIELD(NAME, TYPE, INIT) \5144if (!NAME.Seen) \5145return error(ClosingLoc, "missing required field '" #NAME "'");5146#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \5147if (Lex.getStrVal() == #NAME) \5148return parseMDField(#NAME, NAME);5149#define PARSE_MD_FIELDS() \5150VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \5151do { \5152LocTy ClosingLoc; \5153if (parseMDFieldsImpl( \5154[&]() -> bool { \5155VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \5156return tokError(Twine("invalid field '") + Lex.getStrVal() + \5157"'"); \5158}, \5159ClosingLoc)) \5160return true; \5161VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \5162} while (false)5163#define GET_OR_DISTINCT(CLASS, ARGS) \5164(IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)51655166/// parseDILocationFields:5167/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,5168/// isImplicitCode: true)5169bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {5170#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5171OPTIONAL(line, LineField, ); \5172OPTIONAL(column, ColumnField, ); \5173REQUIRED(scope, MDField, (/* AllowNull */ false)); \5174OPTIONAL(inlinedAt, MDField, ); \5175OPTIONAL(isImplicitCode, MDBoolField, (false));5176PARSE_MD_FIELDS();5177#undef VISIT_MD_FIELDS51785179Result =5180GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,5181inlinedAt.Val, isImplicitCode.Val));5182return false;5183}51845185/// parseDIAssignID:5186/// ::= distinct !DIAssignID()5187bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {5188if (!IsDistinct)5189return Lex.Error("missing 'distinct', required for !DIAssignID()");51905191Lex.Lex();51925193// Now eat the parens.5194if (parseToken(lltok::lparen, "expected '(' here"))5195return true;5196if (parseToken(lltok::rparen, "expected ')' here"))5197return true;51985199Result = DIAssignID::getDistinct(Context);5200return false;5201}52025203/// parseGenericDINode:5204/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})5205bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {5206#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5207REQUIRED(tag, DwarfTagField, ); \5208OPTIONAL(header, MDStringField, ); \5209OPTIONAL(operands, MDFieldList, );5210PARSE_MD_FIELDS();5211#undef VISIT_MD_FIELDS52125213Result = GET_OR_DISTINCT(GenericDINode,5214(Context, tag.Val, header.Val, operands.Val));5215return false;5216}52175218/// parseDISubrange:5219/// ::= !DISubrange(count: 30, lowerBound: 2)5220/// ::= !DISubrange(count: !node, lowerBound: 2)5221/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)5222bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {5223#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5224OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \5225OPTIONAL(lowerBound, MDSignedOrMDField, ); \5226OPTIONAL(upperBound, MDSignedOrMDField, ); \5227OPTIONAL(stride, MDSignedOrMDField, );5228PARSE_MD_FIELDS();5229#undef VISIT_MD_FIELDS52305231Metadata *Count = nullptr;5232Metadata *LowerBound = nullptr;5233Metadata *UpperBound = nullptr;5234Metadata *Stride = nullptr;52355236auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {5237if (Bound.isMDSignedField())5238return ConstantAsMetadata::get(ConstantInt::getSigned(5239Type::getInt64Ty(Context), Bound.getMDSignedValue()));5240if (Bound.isMDField())5241return Bound.getMDFieldValue();5242return nullptr;5243};52445245Count = convToMetadata(count);5246LowerBound = convToMetadata(lowerBound);5247UpperBound = convToMetadata(upperBound);5248Stride = convToMetadata(stride);52495250Result = GET_OR_DISTINCT(DISubrange,5251(Context, Count, LowerBound, UpperBound, Stride));52525253return false;5254}52555256/// parseDIGenericSubrange:5257/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:5258/// !node3)5259bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {5260#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5261OPTIONAL(count, MDSignedOrMDField, ); \5262OPTIONAL(lowerBound, MDSignedOrMDField, ); \5263OPTIONAL(upperBound, MDSignedOrMDField, ); \5264OPTIONAL(stride, MDSignedOrMDField, );5265PARSE_MD_FIELDS();5266#undef VISIT_MD_FIELDS52675268auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {5269if (Bound.isMDSignedField())5270return DIExpression::get(5271Context, {dwarf::DW_OP_consts,5272static_cast<uint64_t>(Bound.getMDSignedValue())});5273if (Bound.isMDField())5274return Bound.getMDFieldValue();5275return nullptr;5276};52775278Metadata *Count = ConvToMetadata(count);5279Metadata *LowerBound = ConvToMetadata(lowerBound);5280Metadata *UpperBound = ConvToMetadata(upperBound);5281Metadata *Stride = ConvToMetadata(stride);52825283Result = GET_OR_DISTINCT(DIGenericSubrange,5284(Context, Count, LowerBound, UpperBound, Stride));52855286return false;5287}52885289/// parseDIEnumerator:5290/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")5291bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {5292#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5293REQUIRED(name, MDStringField, ); \5294REQUIRED(value, MDAPSIntField, ); \5295OPTIONAL(isUnsigned, MDBoolField, (false));5296PARSE_MD_FIELDS();5297#undef VISIT_MD_FIELDS52985299if (isUnsigned.Val && value.Val.isNegative())5300return tokError("unsigned enumerator with negative value");53015302APSInt Value(value.Val);5303// Add a leading zero so that unsigned values with the msb set are not5304// mistaken for negative values when used for signed enumerators.5305if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())5306Value = Value.zext(Value.getBitWidth() + 1);53075308Result =5309GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));53105311return false;5312}53135314/// parseDIBasicType:5315/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,5316/// encoding: DW_ATE_encoding, flags: 0)5317bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {5318#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5319OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \5320OPTIONAL(name, MDStringField, ); \5321OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \5322OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \5323OPTIONAL(encoding, DwarfAttEncodingField, ); \5324OPTIONAL(flags, DIFlagField, );5325PARSE_MD_FIELDS();5326#undef VISIT_MD_FIELDS53275328Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,5329align.Val, encoding.Val, flags.Val));5330return false;5331}53325333/// parseDIStringType:5334/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)5335bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {5336#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5337OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \5338OPTIONAL(name, MDStringField, ); \5339OPTIONAL(stringLength, MDField, ); \5340OPTIONAL(stringLengthExpression, MDField, ); \5341OPTIONAL(stringLocationExpression, MDField, ); \5342OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \5343OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \5344OPTIONAL(encoding, DwarfAttEncodingField, );5345PARSE_MD_FIELDS();5346#undef VISIT_MD_FIELDS53475348Result = GET_OR_DISTINCT(5349DIStringType,5350(Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,5351stringLocationExpression.Val, size.Val, align.Val, encoding.Val));5352return false;5353}53545355/// parseDIDerivedType:5356/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,5357/// line: 7, scope: !1, baseType: !2, size: 32,5358/// align: 32, offset: 0, flags: 0, extraData: !3,5359/// dwarfAddressSpace: 3, ptrAuthKey: 1,5360/// ptrAuthIsAddressDiscriminated: true,5361/// ptrAuthExtraDiscriminator: 0x1234,5362/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:15363/// )5364bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {5365#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5366REQUIRED(tag, DwarfTagField, ); \5367OPTIONAL(name, MDStringField, ); \5368OPTIONAL(file, MDField, ); \5369OPTIONAL(line, LineField, ); \5370OPTIONAL(scope, MDField, ); \5371REQUIRED(baseType, MDField, ); \5372OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \5373OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \5374OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \5375OPTIONAL(flags, DIFlagField, ); \5376OPTIONAL(extraData, MDField, ); \5377OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \5378OPTIONAL(annotations, MDField, ); \5379OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \5380OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \5381OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \5382OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \5383OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );5384PARSE_MD_FIELDS();5385#undef VISIT_MD_FIELDS53865387std::optional<unsigned> DWARFAddressSpace;5388if (dwarfAddressSpace.Val != UINT32_MAX)5389DWARFAddressSpace = dwarfAddressSpace.Val;5390std::optional<DIDerivedType::PtrAuthData> PtrAuthData;5391if (ptrAuthKey.Val)5392PtrAuthData.emplace(5393(unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,5394(unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,5395ptrAuthAuthenticatesNullValues.Val);53965397Result = GET_OR_DISTINCT(DIDerivedType,5398(Context, tag.Val, name.Val, file.Val, line.Val,5399scope.Val, baseType.Val, size.Val, align.Val,5400offset.Val, DWARFAddressSpace, PtrAuthData,5401flags.Val, extraData.Val, annotations.Val));5402return false;5403}54045405bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {5406#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5407REQUIRED(tag, DwarfTagField, ); \5408OPTIONAL(name, MDStringField, ); \5409OPTIONAL(file, MDField, ); \5410OPTIONAL(line, LineField, ); \5411OPTIONAL(scope, MDField, ); \5412OPTIONAL(baseType, MDField, ); \5413OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \5414OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \5415OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \5416OPTIONAL(flags, DIFlagField, ); \5417OPTIONAL(elements, MDField, ); \5418OPTIONAL(runtimeLang, DwarfLangField, ); \5419OPTIONAL(vtableHolder, MDField, ); \5420OPTIONAL(templateParams, MDField, ); \5421OPTIONAL(identifier, MDStringField, ); \5422OPTIONAL(discriminator, MDField, ); \5423OPTIONAL(dataLocation, MDField, ); \5424OPTIONAL(associated, MDField, ); \5425OPTIONAL(allocated, MDField, ); \5426OPTIONAL(rank, MDSignedOrMDField, ); \5427OPTIONAL(annotations, MDField, );5428PARSE_MD_FIELDS();5429#undef VISIT_MD_FIELDS54305431Metadata *Rank = nullptr;5432if (rank.isMDSignedField())5433Rank = ConstantAsMetadata::get(ConstantInt::getSigned(5434Type::getInt64Ty(Context), rank.getMDSignedValue()));5435else if (rank.isMDField())5436Rank = rank.getMDFieldValue();54375438// If this has an identifier try to build an ODR type.5439if (identifier.Val)5440if (auto *CT = DICompositeType::buildODRType(5441Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,5442scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,5443elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,5444discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,5445Rank, annotations.Val)) {5446Result = CT;5447return false;5448}54495450// Create a new node, and save it in the context if it belongs in the type5451// map.5452Result = GET_OR_DISTINCT(5453DICompositeType,5454(Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,5455size.Val, align.Val, offset.Val, flags.Val, elements.Val,5456runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,5457discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,5458annotations.Val));5459return false;5460}54615462bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {5463#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5464OPTIONAL(flags, DIFlagField, ); \5465OPTIONAL(cc, DwarfCCField, ); \5466REQUIRED(types, MDField, );5467PARSE_MD_FIELDS();5468#undef VISIT_MD_FIELDS54695470Result = GET_OR_DISTINCT(DISubroutineType,5471(Context, flags.Val, cc.Val, types.Val));5472return false;5473}54745475/// parseDIFileType:5476/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",5477/// checksumkind: CSK_MD5,5478/// checksum: "000102030405060708090a0b0c0d0e0f",5479/// source: "source file contents")5480bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {5481// The default constructed value for checksumkind is required, but will never5482// be used, as the parser checks if the field was actually Seen before using5483// the Val.5484#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5485REQUIRED(filename, MDStringField, ); \5486REQUIRED(directory, MDStringField, ); \5487OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \5488OPTIONAL(checksum, MDStringField, ); \5489OPTIONAL(source, MDStringField, );5490PARSE_MD_FIELDS();5491#undef VISIT_MD_FIELDS54925493std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;5494if (checksumkind.Seen && checksum.Seen)5495OptChecksum.emplace(checksumkind.Val, checksum.Val);5496else if (checksumkind.Seen || checksum.Seen)5497return Lex.Error("'checksumkind' and 'checksum' must be provided together");54985499MDString *Source = nullptr;5500if (source.Seen)5501Source = source.Val;5502Result = GET_OR_DISTINCT(5503DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));5504return false;5505}55065507/// parseDICompileUnit:5508/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",5509/// isOptimized: true, flags: "-O2", runtimeVersion: 1,5510/// splitDebugFilename: "abc.debug",5511/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,5512/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,5513/// sysroot: "/", sdk: "MacOSX.sdk")5514bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {5515if (!IsDistinct)5516return Lex.Error("missing 'distinct', required for !DICompileUnit");55175518#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5519REQUIRED(language, DwarfLangField, ); \5520REQUIRED(file, MDField, (/* AllowNull */ false)); \5521OPTIONAL(producer, MDStringField, ); \5522OPTIONAL(isOptimized, MDBoolField, ); \5523OPTIONAL(flags, MDStringField, ); \5524OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \5525OPTIONAL(splitDebugFilename, MDStringField, ); \5526OPTIONAL(emissionKind, EmissionKindField, ); \5527OPTIONAL(enums, MDField, ); \5528OPTIONAL(retainedTypes, MDField, ); \5529OPTIONAL(globals, MDField, ); \5530OPTIONAL(imports, MDField, ); \5531OPTIONAL(macros, MDField, ); \5532OPTIONAL(dwoId, MDUnsignedField, ); \5533OPTIONAL(splitDebugInlining, MDBoolField, = true); \5534OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \5535OPTIONAL(nameTableKind, NameTableKindField, ); \5536OPTIONAL(rangesBaseAddress, MDBoolField, = false); \5537OPTIONAL(sysroot, MDStringField, ); \5538OPTIONAL(sdk, MDStringField, );5539PARSE_MD_FIELDS();5540#undef VISIT_MD_FIELDS55415542Result = DICompileUnit::getDistinct(5543Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,5544runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,5545retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,5546splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,5547rangesBaseAddress.Val, sysroot.Val, sdk.Val);5548return false;5549}55505551/// parseDISubprogram:5552/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",5553/// file: !1, line: 7, type: !2, isLocal: false,5554/// isDefinition: true, scopeLine: 8, containingType: !3,5555/// virtuality: DW_VIRTUALTIY_pure_virtual,5556/// virtualIndex: 10, thisAdjustment: 4, flags: 11,5557/// spFlags: 10, isOptimized: false, templateParams: !4,5558/// declaration: !5, retainedNodes: !6, thrownTypes: !7,5559/// annotations: !8)5560bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {5561auto Loc = Lex.getLoc();5562#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5563OPTIONAL(scope, MDField, ); \5564OPTIONAL(name, MDStringField, ); \5565OPTIONAL(linkageName, MDStringField, ); \5566OPTIONAL(file, MDField, ); \5567OPTIONAL(line, LineField, ); \5568OPTIONAL(type, MDField, ); \5569OPTIONAL(isLocal, MDBoolField, ); \5570OPTIONAL(isDefinition, MDBoolField, (true)); \5571OPTIONAL(scopeLine, LineField, ); \5572OPTIONAL(containingType, MDField, ); \5573OPTIONAL(virtuality, DwarfVirtualityField, ); \5574OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \5575OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \5576OPTIONAL(flags, DIFlagField, ); \5577OPTIONAL(spFlags, DISPFlagField, ); \5578OPTIONAL(isOptimized, MDBoolField, ); \5579OPTIONAL(unit, MDField, ); \5580OPTIONAL(templateParams, MDField, ); \5581OPTIONAL(declaration, MDField, ); \5582OPTIONAL(retainedNodes, MDField, ); \5583OPTIONAL(thrownTypes, MDField, ); \5584OPTIONAL(annotations, MDField, ); \5585OPTIONAL(targetFuncName, MDStringField, );5586PARSE_MD_FIELDS();5587#undef VISIT_MD_FIELDS55885589// An explicit spFlags field takes precedence over individual fields in5590// older IR versions.5591DISubprogram::DISPFlags SPFlags =5592spFlags.Seen ? spFlags.Val5593: DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,5594isOptimized.Val, virtuality.Val);5595if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)5596return Lex.Error(5597Loc,5598"missing 'distinct', required for !DISubprogram that is a Definition");5599Result = GET_OR_DISTINCT(5600DISubprogram,5601(Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,5602type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,5603thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,5604declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,5605targetFuncName.Val));5606return false;5607}56085609/// parseDILexicalBlock:5610/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)5611bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {5612#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5613REQUIRED(scope, MDField, (/* AllowNull */ false)); \5614OPTIONAL(file, MDField, ); \5615OPTIONAL(line, LineField, ); \5616OPTIONAL(column, ColumnField, );5617PARSE_MD_FIELDS();5618#undef VISIT_MD_FIELDS56195620Result = GET_OR_DISTINCT(5621DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));5622return false;5623}56245625/// parseDILexicalBlockFile:5626/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)5627bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {5628#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5629REQUIRED(scope, MDField, (/* AllowNull */ false)); \5630OPTIONAL(file, MDField, ); \5631REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));5632PARSE_MD_FIELDS();5633#undef VISIT_MD_FIELDS56345635Result = GET_OR_DISTINCT(DILexicalBlockFile,5636(Context, scope.Val, file.Val, discriminator.Val));5637return false;5638}56395640/// parseDICommonBlock:5641/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)5642bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {5643#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5644REQUIRED(scope, MDField, ); \5645OPTIONAL(declaration, MDField, ); \5646OPTIONAL(name, MDStringField, ); \5647OPTIONAL(file, MDField, ); \5648OPTIONAL(line, LineField, );5649PARSE_MD_FIELDS();5650#undef VISIT_MD_FIELDS56515652Result = GET_OR_DISTINCT(DICommonBlock,5653(Context, scope.Val, declaration.Val, name.Val,5654file.Val, line.Val));5655return false;5656}56575658/// parseDINamespace:5659/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)5660bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {5661#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5662REQUIRED(scope, MDField, ); \5663OPTIONAL(name, MDStringField, ); \5664OPTIONAL(exportSymbols, MDBoolField, );5665PARSE_MD_FIELDS();5666#undef VISIT_MD_FIELDS56675668Result = GET_OR_DISTINCT(DINamespace,5669(Context, scope.Val, name.Val, exportSymbols.Val));5670return false;5671}56725673/// parseDIMacro:5674/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:5675/// "SomeValue")5676bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {5677#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5678REQUIRED(type, DwarfMacinfoTypeField, ); \5679OPTIONAL(line, LineField, ); \5680REQUIRED(name, MDStringField, ); \5681OPTIONAL(value, MDStringField, );5682PARSE_MD_FIELDS();5683#undef VISIT_MD_FIELDS56845685Result = GET_OR_DISTINCT(DIMacro,5686(Context, type.Val, line.Val, name.Val, value.Val));5687return false;5688}56895690/// parseDIMacroFile:5691/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)5692bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {5693#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5694OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \5695OPTIONAL(line, LineField, ); \5696REQUIRED(file, MDField, ); \5697OPTIONAL(nodes, MDField, );5698PARSE_MD_FIELDS();5699#undef VISIT_MD_FIELDS57005701Result = GET_OR_DISTINCT(DIMacroFile,5702(Context, type.Val, line.Val, file.Val, nodes.Val));5703return false;5704}57055706/// parseDIModule:5707/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:5708/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",5709/// file: !1, line: 4, isDecl: false)5710bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {5711#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5712REQUIRED(scope, MDField, ); \5713REQUIRED(name, MDStringField, ); \5714OPTIONAL(configMacros, MDStringField, ); \5715OPTIONAL(includePath, MDStringField, ); \5716OPTIONAL(apinotes, MDStringField, ); \5717OPTIONAL(file, MDField, ); \5718OPTIONAL(line, LineField, ); \5719OPTIONAL(isDecl, MDBoolField, );5720PARSE_MD_FIELDS();5721#undef VISIT_MD_FIELDS57225723Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,5724configMacros.Val, includePath.Val,5725apinotes.Val, line.Val, isDecl.Val));5726return false;5727}57285729/// parseDITemplateTypeParameter:5730/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)5731bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {5732#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5733OPTIONAL(name, MDStringField, ); \5734REQUIRED(type, MDField, ); \5735OPTIONAL(defaulted, MDBoolField, );5736PARSE_MD_FIELDS();5737#undef VISIT_MD_FIELDS57385739Result = GET_OR_DISTINCT(DITemplateTypeParameter,5740(Context, name.Val, type.Val, defaulted.Val));5741return false;5742}57435744/// parseDITemplateValueParameter:5745/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,5746/// name: "V", type: !1, defaulted: false,5747/// value: i32 7)5748bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {5749#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5750OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \5751OPTIONAL(name, MDStringField, ); \5752OPTIONAL(type, MDField, ); \5753OPTIONAL(defaulted, MDBoolField, ); \5754REQUIRED(value, MDField, );57555756PARSE_MD_FIELDS();5757#undef VISIT_MD_FIELDS57585759Result = GET_OR_DISTINCT(5760DITemplateValueParameter,5761(Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));5762return false;5763}57645765/// parseDIGlobalVariable:5766/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",5767/// file: !1, line: 7, type: !2, isLocal: false,5768/// isDefinition: true, templateParams: !3,5769/// declaration: !4, align: 8)5770bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {5771#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5772OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \5773OPTIONAL(scope, MDField, ); \5774OPTIONAL(linkageName, MDStringField, ); \5775OPTIONAL(file, MDField, ); \5776OPTIONAL(line, LineField, ); \5777OPTIONAL(type, MDField, ); \5778OPTIONAL(isLocal, MDBoolField, ); \5779OPTIONAL(isDefinition, MDBoolField, (true)); \5780OPTIONAL(templateParams, MDField, ); \5781OPTIONAL(declaration, MDField, ); \5782OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \5783OPTIONAL(annotations, MDField, );5784PARSE_MD_FIELDS();5785#undef VISIT_MD_FIELDS57865787Result =5788GET_OR_DISTINCT(DIGlobalVariable,5789(Context, scope.Val, name.Val, linkageName.Val, file.Val,5790line.Val, type.Val, isLocal.Val, isDefinition.Val,5791declaration.Val, templateParams.Val, align.Val,5792annotations.Val));5793return false;5794}57955796/// parseDILocalVariable:5797/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",5798/// file: !1, line: 7, type: !2, arg: 2, flags: 7,5799/// align: 8)5800/// ::= !DILocalVariable(scope: !0, name: "foo",5801/// file: !1, line: 7, type: !2, arg: 2, flags: 7,5802/// align: 8)5803bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {5804#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5805REQUIRED(scope, MDField, (/* AllowNull */ false)); \5806OPTIONAL(name, MDStringField, ); \5807OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \5808OPTIONAL(file, MDField, ); \5809OPTIONAL(line, LineField, ); \5810OPTIONAL(type, MDField, ); \5811OPTIONAL(flags, DIFlagField, ); \5812OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \5813OPTIONAL(annotations, MDField, );5814PARSE_MD_FIELDS();5815#undef VISIT_MD_FIELDS58165817Result = GET_OR_DISTINCT(DILocalVariable,5818(Context, scope.Val, name.Val, file.Val, line.Val,5819type.Val, arg.Val, flags.Val, align.Val,5820annotations.Val));5821return false;5822}58235824/// parseDILabel:5825/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)5826bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {5827#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5828REQUIRED(scope, MDField, (/* AllowNull */ false)); \5829REQUIRED(name, MDStringField, ); \5830REQUIRED(file, MDField, ); \5831REQUIRED(line, LineField, );5832PARSE_MD_FIELDS();5833#undef VISIT_MD_FIELDS58345835Result = GET_OR_DISTINCT(DILabel,5836(Context, scope.Val, name.Val, file.Val, line.Val));5837return false;5838}58395840/// parseDIExpressionBody:5841/// ::= (0, 7, -1)5842bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {5843if (parseToken(lltok::lparen, "expected '(' here"))5844return true;58455846SmallVector<uint64_t, 8> Elements;5847if (Lex.getKind() != lltok::rparen)5848do {5849if (Lex.getKind() == lltok::DwarfOp) {5850if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {5851Lex.Lex();5852Elements.push_back(Op);5853continue;5854}5855return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");5856}58575858if (Lex.getKind() == lltok::DwarfAttEncoding) {5859if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {5860Lex.Lex();5861Elements.push_back(Op);5862continue;5863}5864return tokError(Twine("invalid DWARF attribute encoding '") +5865Lex.getStrVal() + "'");5866}58675868if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())5869return tokError("expected unsigned integer");58705871auto &U = Lex.getAPSIntVal();5872if (U.ugt(UINT64_MAX))5873return tokError("element too large, limit is " + Twine(UINT64_MAX));5874Elements.push_back(U.getZExtValue());5875Lex.Lex();5876} while (EatIfPresent(lltok::comma));58775878if (parseToken(lltok::rparen, "expected ')' here"))5879return true;58805881Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));5882return false;5883}58845885/// parseDIExpression:5886/// ::= !DIExpression(0, 7, -1)5887bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {5888assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");5889assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");5890Lex.Lex();58915892return parseDIExpressionBody(Result, IsDistinct);5893}58945895/// ParseDIArgList:5896/// ::= !DIArgList(i32 7, i64 %0)5897bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {5898assert(PFS && "Expected valid function state");5899assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");5900Lex.Lex();59015902if (parseToken(lltok::lparen, "expected '(' here"))5903return true;59045905SmallVector<ValueAsMetadata *, 4> Args;5906if (Lex.getKind() != lltok::rparen)5907do {5908Metadata *MD;5909if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))5910return true;5911Args.push_back(dyn_cast<ValueAsMetadata>(MD));5912} while (EatIfPresent(lltok::comma));59135914if (parseToken(lltok::rparen, "expected ')' here"))5915return true;59165917MD = DIArgList::get(Context, Args);5918return false;5919}59205921/// parseDIGlobalVariableExpression:5922/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)5923bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,5924bool IsDistinct) {5925#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5926REQUIRED(var, MDField, ); \5927REQUIRED(expr, MDField, );5928PARSE_MD_FIELDS();5929#undef VISIT_MD_FIELDS59305931Result =5932GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));5933return false;5934}59355936/// parseDIObjCProperty:5937/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",5938/// getter: "getFoo", attributes: 7, type: !2)5939bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {5940#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5941OPTIONAL(name, MDStringField, ); \5942OPTIONAL(file, MDField, ); \5943OPTIONAL(line, LineField, ); \5944OPTIONAL(setter, MDStringField, ); \5945OPTIONAL(getter, MDStringField, ); \5946OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \5947OPTIONAL(type, MDField, );5948PARSE_MD_FIELDS();5949#undef VISIT_MD_FIELDS59505951Result = GET_OR_DISTINCT(DIObjCProperty,5952(Context, name.Val, file.Val, line.Val, setter.Val,5953getter.Val, attributes.Val, type.Val));5954return false;5955}59565957/// parseDIImportedEntity:5958/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,5959/// line: 7, name: "foo", elements: !2)5960bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {5961#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \5962REQUIRED(tag, DwarfTagField, ); \5963REQUIRED(scope, MDField, ); \5964OPTIONAL(entity, MDField, ); \5965OPTIONAL(file, MDField, ); \5966OPTIONAL(line, LineField, ); \5967OPTIONAL(name, MDStringField, ); \5968OPTIONAL(elements, MDField, );5969PARSE_MD_FIELDS();5970#undef VISIT_MD_FIELDS59715972Result = GET_OR_DISTINCT(DIImportedEntity,5973(Context, tag.Val, scope.Val, entity.Val, file.Val,5974line.Val, name.Val, elements.Val));5975return false;5976}59775978#undef PARSE_MD_FIELD5979#undef NOP_FIELD5980#undef REQUIRE_FIELD5981#undef DECLARE_FIELD59825983/// parseMetadataAsValue5984/// ::= metadata i32 %local5985/// ::= metadata i32 @global5986/// ::= metadata i32 75987/// ::= metadata !05988/// ::= metadata !{...}5989/// ::= metadata !"string"5990bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {5991// Note: the type 'metadata' has already been parsed.5992Metadata *MD;5993if (parseMetadata(MD, &PFS))5994return true;59955996V = MetadataAsValue::get(Context, MD);5997return false;5998}59996000/// parseValueAsMetadata6001/// ::= i32 %local6002/// ::= i32 @global6003/// ::= i32 76004bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,6005PerFunctionState *PFS) {6006Type *Ty;6007LocTy Loc;6008if (parseType(Ty, TypeMsg, Loc))6009return true;6010if (Ty->isMetadataTy())6011return error(Loc, "invalid metadata-value-metadata roundtrip");60126013Value *V;6014if (parseValue(Ty, V, PFS))6015return true;60166017MD = ValueAsMetadata::get(V);6018return false;6019}60206021/// parseMetadata6022/// ::= i32 %local6023/// ::= i32 @global6024/// ::= i32 76025/// ::= !426026/// ::= !{...}6027/// ::= !"string"6028/// ::= !DILocation(...)6029bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {6030if (Lex.getKind() == lltok::MetadataVar) {6031// DIArgLists are a special case, as they are a list of ValueAsMetadata and6032// so parsing this requires a Function State.6033if (Lex.getStrVal() == "DIArgList") {6034Metadata *AL;6035if (parseDIArgList(AL, PFS))6036return true;6037MD = AL;6038return false;6039}6040MDNode *N;6041if (parseSpecializedMDNode(N)) {6042return true;6043}6044MD = N;6045return false;6046}60476048// ValueAsMetadata:6049// <type> <value>6050if (Lex.getKind() != lltok::exclaim)6051return parseValueAsMetadata(MD, "expected metadata operand", PFS);60526053// '!'.6054assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");6055Lex.Lex();60566057// MDString:6058// ::= '!' STRINGCONSTANT6059if (Lex.getKind() == lltok::StringConstant) {6060MDString *S;6061if (parseMDString(S))6062return true;6063MD = S;6064return false;6065}60666067// MDNode:6068// !{ ... }6069// !76070MDNode *N;6071if (parseMDNodeTail(N))6072return true;6073MD = N;6074return false;6075}60766077//===----------------------------------------------------------------------===//6078// Function Parsing.6079//===----------------------------------------------------------------------===//60806081bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,6082PerFunctionState *PFS) {6083if (Ty->isFunctionTy())6084return error(ID.Loc, "functions are not values, refer to them as pointers");60856086switch (ID.Kind) {6087case ValID::t_LocalID:6088if (!PFS)6089return error(ID.Loc, "invalid use of function-local name");6090V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);6091return V == nullptr;6092case ValID::t_LocalName:6093if (!PFS)6094return error(ID.Loc, "invalid use of function-local name");6095V = PFS->getVal(ID.StrVal, Ty, ID.Loc);6096return V == nullptr;6097case ValID::t_InlineAsm: {6098if (!ID.FTy)6099return error(ID.Loc, "invalid type for inline asm constraint string");6100if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))6101return error(ID.Loc, toString(std::move(Err)));6102V = InlineAsm::get(6103ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,6104InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);6105return false;6106}6107case ValID::t_GlobalName:6108V = getGlobalVal(ID.StrVal, Ty, ID.Loc);6109if (V && ID.NoCFI)6110V = NoCFIValue::get(cast<GlobalValue>(V));6111return V == nullptr;6112case ValID::t_GlobalID:6113V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);6114if (V && ID.NoCFI)6115V = NoCFIValue::get(cast<GlobalValue>(V));6116return V == nullptr;6117case ValID::t_APSInt:6118if (!Ty->isIntegerTy())6119return error(ID.Loc, "integer constant must have integer type");6120ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());6121V = ConstantInt::get(Context, ID.APSIntVal);6122return false;6123case ValID::t_APFloat:6124if (!Ty->isFloatingPointTy() ||6125!ConstantFP::isValueValidForType(Ty, ID.APFloatVal))6126return error(ID.Loc, "floating point constant invalid for type");61276128// The lexer has no type info, so builds all half, bfloat, float, and double6129// FP constants as double. Fix this here. Long double does not need this.6130if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {6131// Check for signaling before potentially converting and losing that info.6132bool IsSNAN = ID.APFloatVal.isSignaling();6133bool Ignored;6134if (Ty->isHalfTy())6135ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,6136&Ignored);6137else if (Ty->isBFloatTy())6138ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,6139&Ignored);6140else if (Ty->isFloatTy())6141ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,6142&Ignored);6143if (IsSNAN) {6144// The convert call above may quiet an SNaN, so manufacture another6145// SNaN. The bitcast works because the payload (significand) parameter6146// is truncated to fit.6147APInt Payload = ID.APFloatVal.bitcastToAPInt();6148ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),6149ID.APFloatVal.isNegative(), &Payload);6150}6151}6152V = ConstantFP::get(Context, ID.APFloatVal);61536154if (V->getType() != Ty)6155return error(ID.Loc, "floating point constant does not have type '" +6156getTypeString(Ty) + "'");61576158return false;6159case ValID::t_Null:6160if (!Ty->isPointerTy())6161return error(ID.Loc, "null must be a pointer type");6162V = ConstantPointerNull::get(cast<PointerType>(Ty));6163return false;6164case ValID::t_Undef:6165// FIXME: LabelTy should not be a first-class type.6166if (!Ty->isFirstClassType() || Ty->isLabelTy())6167return error(ID.Loc, "invalid type for undef constant");6168V = UndefValue::get(Ty);6169return false;6170case ValID::t_EmptyArray:6171if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)6172return error(ID.Loc, "invalid empty array initializer");6173V = UndefValue::get(Ty);6174return false;6175case ValID::t_Zero:6176// FIXME: LabelTy should not be a first-class type.6177if (!Ty->isFirstClassType() || Ty->isLabelTy())6178return error(ID.Loc, "invalid type for null constant");6179if (auto *TETy = dyn_cast<TargetExtType>(Ty))6180if (!TETy->hasProperty(TargetExtType::HasZeroInit))6181return error(ID.Loc, "invalid type for null constant");6182V = Constant::getNullValue(Ty);6183return false;6184case ValID::t_None:6185if (!Ty->isTokenTy())6186return error(ID.Loc, "invalid type for none constant");6187V = Constant::getNullValue(Ty);6188return false;6189case ValID::t_Poison:6190// FIXME: LabelTy should not be a first-class type.6191if (!Ty->isFirstClassType() || Ty->isLabelTy())6192return error(ID.Loc, "invalid type for poison constant");6193V = PoisonValue::get(Ty);6194return false;6195case ValID::t_Constant:6196if (ID.ConstantVal->getType() != Ty)6197return error(ID.Loc, "constant expression type mismatch: got type '" +6198getTypeString(ID.ConstantVal->getType()) +6199"' but expected '" + getTypeString(Ty) + "'");6200V = ID.ConstantVal;6201return false;6202case ValID::t_ConstantSplat:6203if (!Ty->isVectorTy())6204return error(ID.Loc, "vector constant must have vector type");6205if (ID.ConstantVal->getType() != Ty->getScalarType())6206return error(ID.Loc, "constant expression type mismatch: got type '" +6207getTypeString(ID.ConstantVal->getType()) +6208"' but expected '" +6209getTypeString(Ty->getScalarType()) + "'");6210V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),6211ID.ConstantVal);6212return false;6213case ValID::t_ConstantStruct:6214case ValID::t_PackedConstantStruct:6215if (StructType *ST = dyn_cast<StructType>(Ty)) {6216if (ST->getNumElements() != ID.UIntVal)6217return error(ID.Loc,6218"initializer with struct type has wrong # elements");6219if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))6220return error(ID.Loc, "packed'ness of initializer and type don't match");62216222// Verify that the elements are compatible with the structtype.6223for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)6224if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))6225return error(6226ID.Loc,6227"element " + Twine(i) +6228" of struct initializer doesn't match struct element type");62296230V = ConstantStruct::get(6231ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));6232} else6233return error(ID.Loc, "constant expression type mismatch");6234return false;6235}6236llvm_unreachable("Invalid ValID");6237}62386239bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {6240C = nullptr;6241ValID ID;6242auto Loc = Lex.getLoc();6243if (parseValID(ID, /*PFS=*/nullptr))6244return true;6245switch (ID.Kind) {6246case ValID::t_APSInt:6247case ValID::t_APFloat:6248case ValID::t_Undef:6249case ValID::t_Constant:6250case ValID::t_ConstantSplat:6251case ValID::t_ConstantStruct:6252case ValID::t_PackedConstantStruct: {6253Value *V;6254if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))6255return true;6256assert(isa<Constant>(V) && "Expected a constant value");6257C = cast<Constant>(V);6258return false;6259}6260case ValID::t_Null:6261C = Constant::getNullValue(Ty);6262return false;6263default:6264return error(Loc, "expected a constant value");6265}6266}62676268bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {6269V = nullptr;6270ValID ID;6271return parseValID(ID, PFS, Ty) ||6272convertValIDToValue(Ty, ID, V, PFS);6273}62746275bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {6276Type *Ty = nullptr;6277return parseType(Ty) || parseValue(Ty, V, PFS);6278}62796280bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,6281PerFunctionState &PFS) {6282Value *V;6283Loc = Lex.getLoc();6284if (parseTypeAndValue(V, PFS))6285return true;6286if (!isa<BasicBlock>(V))6287return error(Loc, "expected a basic block");6288BB = cast<BasicBlock>(V);6289return false;6290}62916292bool isOldDbgFormatIntrinsic(StringRef Name) {6293// Exit early for the common (non-debug-intrinsic) case.6294// We can make this the only check when we begin supporting all "llvm.dbg"6295// intrinsics in the new debug info format.6296if (!Name.starts_with("llvm.dbg."))6297return false;6298Intrinsic::ID FnID = Function::lookupIntrinsicID(Name);6299return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||6300FnID == Intrinsic::dbg_assign;6301}63026303/// FunctionHeader6304/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility6305/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName6306/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign6307/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn6308bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,6309unsigned &FunctionNumber,6310SmallVectorImpl<unsigned> &UnnamedArgNums) {6311// parse the linkage.6312LocTy LinkageLoc = Lex.getLoc();6313unsigned Linkage;6314unsigned Visibility;6315unsigned DLLStorageClass;6316bool DSOLocal;6317AttrBuilder RetAttrs(M->getContext());6318unsigned CC;6319bool HasLinkage;6320Type *RetType = nullptr;6321LocTy RetTypeLoc = Lex.getLoc();6322if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,6323DSOLocal) ||6324parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||6325parseType(RetType, RetTypeLoc, true /*void allowed*/))6326return true;63276328// Verify that the linkage is ok.6329switch ((GlobalValue::LinkageTypes)Linkage) {6330case GlobalValue::ExternalLinkage:6331break; // always ok.6332case GlobalValue::ExternalWeakLinkage:6333if (IsDefine)6334return error(LinkageLoc, "invalid linkage for function definition");6335break;6336case GlobalValue::PrivateLinkage:6337case GlobalValue::InternalLinkage:6338case GlobalValue::AvailableExternallyLinkage:6339case GlobalValue::LinkOnceAnyLinkage:6340case GlobalValue::LinkOnceODRLinkage:6341case GlobalValue::WeakAnyLinkage:6342case GlobalValue::WeakODRLinkage:6343if (!IsDefine)6344return error(LinkageLoc, "invalid linkage for function declaration");6345break;6346case GlobalValue::AppendingLinkage:6347case GlobalValue::CommonLinkage:6348return error(LinkageLoc, "invalid function linkage type");6349}63506351if (!isValidVisibilityForLinkage(Visibility, Linkage))6352return error(LinkageLoc,6353"symbol with local linkage must have default visibility");63546355if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))6356return error(LinkageLoc,6357"symbol with local linkage cannot have a DLL storage class");63586359if (!FunctionType::isValidReturnType(RetType))6360return error(RetTypeLoc, "invalid function return type");63616362LocTy NameLoc = Lex.getLoc();63636364std::string FunctionName;6365if (Lex.getKind() == lltok::GlobalVar) {6366FunctionName = Lex.getStrVal();6367} else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.6368FunctionNumber = Lex.getUIntVal();6369if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),6370FunctionNumber))6371return true;6372} else {6373return tokError("expected function name");6374}63756376Lex.Lex();63776378if (Lex.getKind() != lltok::lparen)6379return tokError("expected '(' in function argument list");63806381SmallVector<ArgInfo, 8> ArgList;6382bool IsVarArg;6383AttrBuilder FuncAttrs(M->getContext());6384std::vector<unsigned> FwdRefAttrGrps;6385LocTy BuiltinLoc;6386std::string Section;6387std::string Partition;6388MaybeAlign Alignment;6389std::string GC;6390GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;6391unsigned AddrSpace = 0;6392Constant *Prefix = nullptr;6393Constant *Prologue = nullptr;6394Constant *PersonalityFn = nullptr;6395Comdat *C;63966397if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||6398parseOptionalUnnamedAddr(UnnamedAddr) ||6399parseOptionalProgramAddrSpace(AddrSpace) ||6400parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,6401BuiltinLoc) ||6402(EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||6403(EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||6404parseOptionalComdat(FunctionName, C) ||6405parseOptionalAlignment(Alignment) ||6406(EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||6407(EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||6408(EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||6409(EatIfPresent(lltok::kw_personality) &&6410parseGlobalTypeAndValue(PersonalityFn)))6411return true;64126413if (FuncAttrs.contains(Attribute::Builtin))6414return error(BuiltinLoc, "'builtin' attribute not valid on function");64156416// If the alignment was parsed as an attribute, move to the alignment field.6417if (MaybeAlign A = FuncAttrs.getAlignment()) {6418Alignment = A;6419FuncAttrs.removeAttribute(Attribute::Alignment);6420}64216422// Okay, if we got here, the function is syntactically valid. Convert types6423// and do semantic checks.6424std::vector<Type*> ParamTypeList;6425SmallVector<AttributeSet, 8> Attrs;64266427for (const ArgInfo &Arg : ArgList) {6428ParamTypeList.push_back(Arg.Ty);6429Attrs.push_back(Arg.Attrs);6430}64316432AttributeList PAL =6433AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),6434AttributeSet::get(Context, RetAttrs), Attrs);64356436if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())6437return error(RetTypeLoc, "functions with 'sret' argument must return void");64386439FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);6440PointerType *PFT = PointerType::get(FT, AddrSpace);64416442Fn = nullptr;6443GlobalValue *FwdFn = nullptr;6444if (!FunctionName.empty()) {6445// If this was a definition of a forward reference, remove the definition6446// from the forward reference table and fill in the forward ref.6447auto FRVI = ForwardRefVals.find(FunctionName);6448if (FRVI != ForwardRefVals.end()) {6449FwdFn = FRVI->second.first;6450if (FwdFn->getType() != PFT)6451return error(FRVI->second.second,6452"invalid forward reference to "6453"function '" +6454FunctionName +6455"' with wrong type: "6456"expected '" +6457getTypeString(PFT) + "' but was '" +6458getTypeString(FwdFn->getType()) + "'");6459ForwardRefVals.erase(FRVI);6460} else if ((Fn = M->getFunction(FunctionName))) {6461// Reject redefinitions.6462return error(NameLoc,6463"invalid redefinition of function '" + FunctionName + "'");6464} else if (M->getNamedValue(FunctionName)) {6465return error(NameLoc, "redefinition of function '@" + FunctionName + "'");6466}64676468} else {6469// Handle @"", where a name is syntactically specified, but semantically6470// missing.6471if (FunctionNumber == (unsigned)-1)6472FunctionNumber = NumberedVals.getNext();64736474// If this is a definition of a forward referenced function, make sure the6475// types agree.6476auto I = ForwardRefValIDs.find(FunctionNumber);6477if (I != ForwardRefValIDs.end()) {6478FwdFn = I->second.first;6479if (FwdFn->getType() != PFT)6480return error(NameLoc, "type of definition and forward reference of '@" +6481Twine(FunctionNumber) +6482"' disagree: "6483"expected '" +6484getTypeString(PFT) + "' but was '" +6485getTypeString(FwdFn->getType()) + "'");6486ForwardRefValIDs.erase(I);6487}6488}64896490Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,6491FunctionName, M);64926493assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");64946495if (FunctionName.empty())6496NumberedVals.add(FunctionNumber, Fn);64976498Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);6499maybeSetDSOLocal(DSOLocal, *Fn);6500Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);6501Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);6502Fn->setCallingConv(CC);6503Fn->setAttributes(PAL);6504Fn->setUnnamedAddr(UnnamedAddr);6505if (Alignment)6506Fn->setAlignment(*Alignment);6507Fn->setSection(Section);6508Fn->setPartition(Partition);6509Fn->setComdat(C);6510Fn->setPersonalityFn(PersonalityFn);6511if (!GC.empty()) Fn->setGC(GC);6512Fn->setPrefixData(Prefix);6513Fn->setPrologueData(Prologue);6514ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;65156516// Add all of the arguments we parsed to the function.6517Function::arg_iterator ArgIt = Fn->arg_begin();6518for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {6519// If the argument has a name, insert it into the argument symbol table.6520if (ArgList[i].Name.empty()) continue;65216522// Set the name, if it conflicted, it will be auto-renamed.6523ArgIt->setName(ArgList[i].Name);65246525if (ArgIt->getName() != ArgList[i].Name)6526return error(ArgList[i].Loc,6527"redefinition of argument '%" + ArgList[i].Name + "'");6528}65296530if (FwdFn) {6531FwdFn->replaceAllUsesWith(Fn);6532FwdFn->eraseFromParent();6533}65346535if (IsDefine)6536return false;65376538// Check the declaration has no block address forward references.6539ValID ID;6540if (FunctionName.empty()) {6541ID.Kind = ValID::t_GlobalID;6542ID.UIntVal = FunctionNumber;6543} else {6544ID.Kind = ValID::t_GlobalName;6545ID.StrVal = FunctionName;6546}6547auto Blocks = ForwardRefBlockAddresses.find(ID);6548if (Blocks != ForwardRefBlockAddresses.end())6549return error(Blocks->first.Loc,6550"cannot take blockaddress inside a declaration");6551return false;6552}65536554bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {6555ValID ID;6556if (FunctionNumber == -1) {6557ID.Kind = ValID::t_GlobalName;6558ID.StrVal = std::string(F.getName());6559} else {6560ID.Kind = ValID::t_GlobalID;6561ID.UIntVal = FunctionNumber;6562}65636564auto Blocks = P.ForwardRefBlockAddresses.find(ID);6565if (Blocks == P.ForwardRefBlockAddresses.end())6566return false;65676568for (const auto &I : Blocks->second) {6569const ValID &BBID = I.first;6570GlobalValue *GV = I.second;65716572assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&6573"Expected local id or name");6574BasicBlock *BB;6575if (BBID.Kind == ValID::t_LocalName)6576BB = getBB(BBID.StrVal, BBID.Loc);6577else6578BB = getBB(BBID.UIntVal, BBID.Loc);6579if (!BB)6580return P.error(BBID.Loc, "referenced value is not a basic block");65816582Value *ResolvedVal = BlockAddress::get(&F, BB);6583ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),6584ResolvedVal);6585if (!ResolvedVal)6586return true;6587GV->replaceAllUsesWith(ResolvedVal);6588GV->eraseFromParent();6589}65906591P.ForwardRefBlockAddresses.erase(Blocks);6592return false;6593}65946595/// parseFunctionBody6596/// ::= '{' BasicBlock+ UseListOrderDirective* '}'6597bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,6598ArrayRef<unsigned> UnnamedArgNums) {6599if (Lex.getKind() != lltok::lbrace)6600return tokError("expected '{' in function body");6601Lex.Lex(); // eat the {.66026603PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);66046605// Resolve block addresses and allow basic blocks to be forward-declared6606// within this function.6607if (PFS.resolveForwardRefBlockAddresses())6608return true;6609SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);66106611// We need at least one basic block.6612if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)6613return tokError("function body requires at least one basic block");66146615while (Lex.getKind() != lltok::rbrace &&6616Lex.getKind() != lltok::kw_uselistorder)6617if (parseBasicBlock(PFS))6618return true;66196620while (Lex.getKind() != lltok::rbrace)6621if (parseUseListOrder(&PFS))6622return true;66236624// Eat the }.6625Lex.Lex();66266627// Verify function is ok.6628return PFS.finishFunction();6629}66306631/// parseBasicBlock6632/// ::= (LabelStr|LabelID)? Instruction*6633bool LLParser::parseBasicBlock(PerFunctionState &PFS) {6634// If this basic block starts out with a name, remember it.6635std::string Name;6636int NameID = -1;6637LocTy NameLoc = Lex.getLoc();6638if (Lex.getKind() == lltok::LabelStr) {6639Name = Lex.getStrVal();6640Lex.Lex();6641} else if (Lex.getKind() == lltok::LabelID) {6642NameID = Lex.getUIntVal();6643Lex.Lex();6644}66456646BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);6647if (!BB)6648return true;66496650std::string NameStr;66516652// Parse the instructions and debug values in this block until we get a6653// terminator.6654Instruction *Inst;6655auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };6656using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;6657SmallVector<DbgRecordPtr> TrailingDbgRecord;6658do {6659// Handle debug records first - there should always be an instruction6660// following the debug records, i.e. they cannot appear after the block6661// terminator.6662while (Lex.getKind() == lltok::hash) {6663if (SeenOldDbgInfoFormat)6664return error(Lex.getLoc(), "debug record should not appear in a module "6665"containing debug info intrinsics");6666if (!SeenNewDbgInfoFormat)6667M->setNewDbgInfoFormatFlag(true);6668SeenNewDbgInfoFormat = true;6669Lex.Lex();66706671DbgRecord *DR;6672if (parseDebugRecord(DR, PFS))6673return true;6674TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);6675}66766677// This instruction may have three possibilities for a name: a) none6678// specified, b) name specified "%foo =", c) number specified: "%4 =".6679LocTy NameLoc = Lex.getLoc();6680int NameID = -1;6681NameStr = "";66826683if (Lex.getKind() == lltok::LocalVarID) {6684NameID = Lex.getUIntVal();6685Lex.Lex();6686if (parseToken(lltok::equal, "expected '=' after instruction id"))6687return true;6688} else if (Lex.getKind() == lltok::LocalVar) {6689NameStr = Lex.getStrVal();6690Lex.Lex();6691if (parseToken(lltok::equal, "expected '=' after instruction name"))6692return true;6693}66946695switch (parseInstruction(Inst, BB, PFS)) {6696default:6697llvm_unreachable("Unknown parseInstruction result!");6698case InstError: return true;6699case InstNormal:6700Inst->insertInto(BB, BB->end());67016702// With a normal result, we check to see if the instruction is followed by6703// a comma and metadata.6704if (EatIfPresent(lltok::comma))6705if (parseInstructionMetadata(*Inst))6706return true;6707break;6708case InstExtraComma:6709Inst->insertInto(BB, BB->end());67106711// If the instruction parser ate an extra comma at the end of it, it6712// *must* be followed by metadata.6713if (parseInstructionMetadata(*Inst))6714return true;6715break;6716}67176718// Set the name on the instruction.6719if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))6720return true;67216722// Attach any preceding debug values to this instruction.6723for (DbgRecordPtr &DR : TrailingDbgRecord)6724BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());6725TrailingDbgRecord.clear();6726} while (!Inst->isTerminator());67276728assert(TrailingDbgRecord.empty() &&6729"All debug values should have been attached to an instruction.");67306731return false;6732}67336734/// parseDebugRecord6735/// ::= #dbg_label '(' MDNode ')'6736/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','6737/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'6738bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {6739using RecordKind = DbgRecord::Kind;6740using LocType = DbgVariableRecord::LocationType;6741LocTy DVRLoc = Lex.getLoc();6742if (Lex.getKind() != lltok::DbgRecordType)6743return error(DVRLoc, "expected debug record type here");6744RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())6745.Case("declare", RecordKind::ValueKind)6746.Case("value", RecordKind::ValueKind)6747.Case("assign", RecordKind::ValueKind)6748.Case("label", RecordKind::LabelKind);67496750// Parsing labels is trivial; parse here and early exit, otherwise go into the6751// full DbgVariableRecord processing stage.6752if (RecordType == RecordKind::LabelKind) {6753Lex.Lex();6754if (parseToken(lltok::lparen, "Expected '(' here"))6755return true;6756MDNode *Label;6757if (parseMDNode(Label))6758return true;6759if (parseToken(lltok::comma, "Expected ',' here"))6760return true;6761MDNode *DbgLoc;6762if (parseMDNode(DbgLoc))6763return true;6764if (parseToken(lltok::rparen, "Expected ')' here"))6765return true;6766DR = DbgLabelRecord::createUnresolvedDbgLabelRecord(Label, DbgLoc);6767return false;6768}67696770LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())6771.Case("declare", LocType::Declare)6772.Case("value", LocType::Value)6773.Case("assign", LocType::Assign);67746775Lex.Lex();6776if (parseToken(lltok::lparen, "Expected '(' here"))6777return true;67786779// Parse Value field.6780Metadata *ValLocMD;6781if (parseMetadata(ValLocMD, &PFS))6782return true;6783if (parseToken(lltok::comma, "Expected ',' here"))6784return true;67856786// Parse Variable field.6787MDNode *Variable;6788if (parseMDNode(Variable))6789return true;6790if (parseToken(lltok::comma, "Expected ',' here"))6791return true;67926793// Parse Expression field.6794MDNode *Expression;6795if (parseMDNode(Expression))6796return true;6797if (parseToken(lltok::comma, "Expected ',' here"))6798return true;67996800// Parse additional fields for #dbg_assign.6801MDNode *AssignID = nullptr;6802Metadata *AddressLocation = nullptr;6803MDNode *AddressExpression = nullptr;6804if (ValueType == LocType::Assign) {6805// Parse DIAssignID.6806if (parseMDNode(AssignID))6807return true;6808if (parseToken(lltok::comma, "Expected ',' here"))6809return true;68106811// Parse address ValueAsMetadata.6812if (parseMetadata(AddressLocation, &PFS))6813return true;6814if (parseToken(lltok::comma, "Expected ',' here"))6815return true;68166817// Parse address DIExpression.6818if (parseMDNode(AddressExpression))6819return true;6820if (parseToken(lltok::comma, "Expected ',' here"))6821return true;6822}68236824/// Parse DILocation.6825MDNode *DebugLoc;6826if (parseMDNode(DebugLoc))6827return true;68286829if (parseToken(lltok::rparen, "Expected ')' here"))6830return true;6831DR = DbgVariableRecord::createUnresolvedDbgVariableRecord(6832ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,6833AddressExpression, DebugLoc);6834return false;6835}6836//===----------------------------------------------------------------------===//6837// Instruction Parsing.6838//===----------------------------------------------------------------------===//68396840/// parseInstruction - parse one of the many different instructions.6841///6842int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,6843PerFunctionState &PFS) {6844lltok::Kind Token = Lex.getKind();6845if (Token == lltok::Eof)6846return tokError("found end of file when expecting more instructions");6847LocTy Loc = Lex.getLoc();6848unsigned KeywordVal = Lex.getUIntVal();6849Lex.Lex(); // Eat the keyword.68506851switch (Token) {6852default:6853return error(Loc, "expected instruction opcode");6854// Terminator Instructions.6855case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;6856case lltok::kw_ret:6857return parseRet(Inst, BB, PFS);6858case lltok::kw_br:6859return parseBr(Inst, PFS);6860case lltok::kw_switch:6861return parseSwitch(Inst, PFS);6862case lltok::kw_indirectbr:6863return parseIndirectBr(Inst, PFS);6864case lltok::kw_invoke:6865return parseInvoke(Inst, PFS);6866case lltok::kw_resume:6867return parseResume(Inst, PFS);6868case lltok::kw_cleanupret:6869return parseCleanupRet(Inst, PFS);6870case lltok::kw_catchret:6871return parseCatchRet(Inst, PFS);6872case lltok::kw_catchswitch:6873return parseCatchSwitch(Inst, PFS);6874case lltok::kw_catchpad:6875return parseCatchPad(Inst, PFS);6876case lltok::kw_cleanuppad:6877return parseCleanupPad(Inst, PFS);6878case lltok::kw_callbr:6879return parseCallBr(Inst, PFS);6880// Unary Operators.6881case lltok::kw_fneg: {6882FastMathFlags FMF = EatFastMathFlagsIfPresent();6883int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);6884if (Res != 0)6885return Res;6886if (FMF.any())6887Inst->setFastMathFlags(FMF);6888return false;6889}6890// Binary Operators.6891case lltok::kw_add:6892case lltok::kw_sub:6893case lltok::kw_mul:6894case lltok::kw_shl: {6895bool NUW = EatIfPresent(lltok::kw_nuw);6896bool NSW = EatIfPresent(lltok::kw_nsw);6897if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);68986899if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))6900return true;69016902if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);6903if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);6904return false;6905}6906case lltok::kw_fadd:6907case lltok::kw_fsub:6908case lltok::kw_fmul:6909case lltok::kw_fdiv:6910case lltok::kw_frem: {6911FastMathFlags FMF = EatFastMathFlagsIfPresent();6912int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);6913if (Res != 0)6914return Res;6915if (FMF.any())6916Inst->setFastMathFlags(FMF);6917return 0;6918}69196920case lltok::kw_sdiv:6921case lltok::kw_udiv:6922case lltok::kw_lshr:6923case lltok::kw_ashr: {6924bool Exact = EatIfPresent(lltok::kw_exact);69256926if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))6927return true;6928if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);6929return false;6930}69316932case lltok::kw_urem:6933case lltok::kw_srem:6934return parseArithmetic(Inst, PFS, KeywordVal,6935/*IsFP*/ false);6936case lltok::kw_or: {6937bool Disjoint = EatIfPresent(lltok::kw_disjoint);6938if (parseLogical(Inst, PFS, KeywordVal))6939return true;6940if (Disjoint)6941cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);6942return false;6943}6944case lltok::kw_and:6945case lltok::kw_xor:6946return parseLogical(Inst, PFS, KeywordVal);6947case lltok::kw_icmp:6948return parseCompare(Inst, PFS, KeywordVal);6949case lltok::kw_fcmp: {6950FastMathFlags FMF = EatFastMathFlagsIfPresent();6951int Res = parseCompare(Inst, PFS, KeywordVal);6952if (Res != 0)6953return Res;6954if (FMF.any())6955Inst->setFastMathFlags(FMF);6956return 0;6957}69586959// Casts.6960case lltok::kw_uitofp:6961case lltok::kw_zext: {6962bool NonNeg = EatIfPresent(lltok::kw_nneg);6963bool Res = parseCast(Inst, PFS, KeywordVal);6964if (Res != 0)6965return Res;6966if (NonNeg)6967Inst->setNonNeg();6968return 0;6969}6970case lltok::kw_trunc: {6971bool NUW = EatIfPresent(lltok::kw_nuw);6972bool NSW = EatIfPresent(lltok::kw_nsw);6973if (!NUW)6974NUW = EatIfPresent(lltok::kw_nuw);6975if (parseCast(Inst, PFS, KeywordVal))6976return true;6977if (NUW)6978cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);6979if (NSW)6980cast<TruncInst>(Inst)->setHasNoSignedWrap(true);6981return false;6982}6983case lltok::kw_sext:6984case lltok::kw_fptrunc:6985case lltok::kw_fpext:6986case lltok::kw_bitcast:6987case lltok::kw_addrspacecast:6988case lltok::kw_sitofp:6989case lltok::kw_fptoui:6990case lltok::kw_fptosi:6991case lltok::kw_inttoptr:6992case lltok::kw_ptrtoint:6993return parseCast(Inst, PFS, KeywordVal);6994// Other.6995case lltok::kw_select: {6996FastMathFlags FMF = EatFastMathFlagsIfPresent();6997int Res = parseSelect(Inst, PFS);6998if (Res != 0)6999return Res;7000if (FMF.any()) {7001if (!isa<FPMathOperator>(Inst))7002return error(Loc, "fast-math-flags specified for select without "7003"floating-point scalar or vector return type");7004Inst->setFastMathFlags(FMF);7005}7006return 0;7007}7008case lltok::kw_va_arg:7009return parseVAArg(Inst, PFS);7010case lltok::kw_extractelement:7011return parseExtractElement(Inst, PFS);7012case lltok::kw_insertelement:7013return parseInsertElement(Inst, PFS);7014case lltok::kw_shufflevector:7015return parseShuffleVector(Inst, PFS);7016case lltok::kw_phi: {7017FastMathFlags FMF = EatFastMathFlagsIfPresent();7018int Res = parsePHI(Inst, PFS);7019if (Res != 0)7020return Res;7021if (FMF.any()) {7022if (!isa<FPMathOperator>(Inst))7023return error(Loc, "fast-math-flags specified for phi without "7024"floating-point scalar or vector return type");7025Inst->setFastMathFlags(FMF);7026}7027return 0;7028}7029case lltok::kw_landingpad:7030return parseLandingPad(Inst, PFS);7031case lltok::kw_freeze:7032return parseFreeze(Inst, PFS);7033// Call.7034case lltok::kw_call:7035return parseCall(Inst, PFS, CallInst::TCK_None);7036case lltok::kw_tail:7037return parseCall(Inst, PFS, CallInst::TCK_Tail);7038case lltok::kw_musttail:7039return parseCall(Inst, PFS, CallInst::TCK_MustTail);7040case lltok::kw_notail:7041return parseCall(Inst, PFS, CallInst::TCK_NoTail);7042// Memory.7043case lltok::kw_alloca:7044return parseAlloc(Inst, PFS);7045case lltok::kw_load:7046return parseLoad(Inst, PFS);7047case lltok::kw_store:7048return parseStore(Inst, PFS);7049case lltok::kw_cmpxchg:7050return parseCmpXchg(Inst, PFS);7051case lltok::kw_atomicrmw:7052return parseAtomicRMW(Inst, PFS);7053case lltok::kw_fence:7054return parseFence(Inst, PFS);7055case lltok::kw_getelementptr:7056return parseGetElementPtr(Inst, PFS);7057case lltok::kw_extractvalue:7058return parseExtractValue(Inst, PFS);7059case lltok::kw_insertvalue:7060return parseInsertValue(Inst, PFS);7061}7062}70637064/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.7065bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {7066if (Opc == Instruction::FCmp) {7067switch (Lex.getKind()) {7068default:7069return tokError("expected fcmp predicate (e.g. 'oeq')");7070case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;7071case lltok::kw_one: P = CmpInst::FCMP_ONE; break;7072case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;7073case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;7074case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;7075case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;7076case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;7077case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;7078case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;7079case lltok::kw_une: P = CmpInst::FCMP_UNE; break;7080case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;7081case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;7082case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;7083case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;7084case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;7085case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;7086}7087} else {7088switch (Lex.getKind()) {7089default:7090return tokError("expected icmp predicate (e.g. 'eq')");7091case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;7092case lltok::kw_ne: P = CmpInst::ICMP_NE; break;7093case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;7094case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;7095case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;7096case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;7097case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;7098case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;7099case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;7100case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;7101}7102}7103Lex.Lex();7104return false;7105}71067107//===----------------------------------------------------------------------===//7108// Terminator Instructions.7109//===----------------------------------------------------------------------===//71107111/// parseRet - parse a return instruction.7112/// ::= 'ret' void (',' !dbg, !1)*7113/// ::= 'ret' TypeAndValue (',' !dbg, !1)*7114bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,7115PerFunctionState &PFS) {7116SMLoc TypeLoc = Lex.getLoc();7117Type *Ty = nullptr;7118if (parseType(Ty, true /*void allowed*/))7119return true;71207121Type *ResType = PFS.getFunction().getReturnType();71227123if (Ty->isVoidTy()) {7124if (!ResType->isVoidTy())7125return error(TypeLoc, "value doesn't match function result type '" +7126getTypeString(ResType) + "'");71277128Inst = ReturnInst::Create(Context);7129return false;7130}71317132Value *RV;7133if (parseValue(Ty, RV, PFS))7134return true;71357136if (ResType != RV->getType())7137return error(TypeLoc, "value doesn't match function result type '" +7138getTypeString(ResType) + "'");71397140Inst = ReturnInst::Create(Context, RV);7141return false;7142}71437144/// parseBr7145/// ::= 'br' TypeAndValue7146/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue7147bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {7148LocTy Loc, Loc2;7149Value *Op0;7150BasicBlock *Op1, *Op2;7151if (parseTypeAndValue(Op0, Loc, PFS))7152return true;71537154if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {7155Inst = BranchInst::Create(BB);7156return false;7157}71587159if (Op0->getType() != Type::getInt1Ty(Context))7160return error(Loc, "branch condition must have 'i1' type");71617162if (parseToken(lltok::comma, "expected ',' after branch condition") ||7163parseTypeAndBasicBlock(Op1, Loc, PFS) ||7164parseToken(lltok::comma, "expected ',' after true destination") ||7165parseTypeAndBasicBlock(Op2, Loc2, PFS))7166return true;71677168Inst = BranchInst::Create(Op1, Op2, Op0);7169return false;7170}71717172/// parseSwitch7173/// Instruction7174/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'7175/// JumpTable7176/// ::= (TypeAndValue ',' TypeAndValue)*7177bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {7178LocTy CondLoc, BBLoc;7179Value *Cond;7180BasicBlock *DefaultBB;7181if (parseTypeAndValue(Cond, CondLoc, PFS) ||7182parseToken(lltok::comma, "expected ',' after switch condition") ||7183parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||7184parseToken(lltok::lsquare, "expected '[' with switch table"))7185return true;71867187if (!Cond->getType()->isIntegerTy())7188return error(CondLoc, "switch condition must have integer type");71897190// parse the jump table pairs.7191SmallPtrSet<Value*, 32> SeenCases;7192SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;7193while (Lex.getKind() != lltok::rsquare) {7194Value *Constant;7195BasicBlock *DestBB;71967197if (parseTypeAndValue(Constant, CondLoc, PFS) ||7198parseToken(lltok::comma, "expected ',' after case value") ||7199parseTypeAndBasicBlock(DestBB, PFS))7200return true;72017202if (!SeenCases.insert(Constant).second)7203return error(CondLoc, "duplicate case value in switch");7204if (!isa<ConstantInt>(Constant))7205return error(CondLoc, "case value is not a constant integer");72067207Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));7208}72097210Lex.Lex(); // Eat the ']'.72117212SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());7213for (unsigned i = 0, e = Table.size(); i != e; ++i)7214SI->addCase(Table[i].first, Table[i].second);7215Inst = SI;7216return false;7217}72187219/// parseIndirectBr7220/// Instruction7221/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'7222bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {7223LocTy AddrLoc;7224Value *Address;7225if (parseTypeAndValue(Address, AddrLoc, PFS) ||7226parseToken(lltok::comma, "expected ',' after indirectbr address") ||7227parseToken(lltok::lsquare, "expected '[' with indirectbr"))7228return true;72297230if (!Address->getType()->isPointerTy())7231return error(AddrLoc, "indirectbr address must have pointer type");72327233// parse the destination list.7234SmallVector<BasicBlock*, 16> DestList;72357236if (Lex.getKind() != lltok::rsquare) {7237BasicBlock *DestBB;7238if (parseTypeAndBasicBlock(DestBB, PFS))7239return true;7240DestList.push_back(DestBB);72417242while (EatIfPresent(lltok::comma)) {7243if (parseTypeAndBasicBlock(DestBB, PFS))7244return true;7245DestList.push_back(DestBB);7246}7247}72487249if (parseToken(lltok::rsquare, "expected ']' at end of block list"))7250return true;72517252IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());7253for (BasicBlock *Dest : DestList)7254IBI->addDestination(Dest);7255Inst = IBI;7256return false;7257}72587259// If RetType is a non-function pointer type, then this is the short syntax7260// for the call, which means that RetType is just the return type. Infer the7261// rest of the function argument types from the arguments that are present.7262bool LLParser::resolveFunctionType(Type *RetType,7263const SmallVector<ParamInfo, 16> &ArgList,7264FunctionType *&FuncTy) {7265FuncTy = dyn_cast<FunctionType>(RetType);7266if (!FuncTy) {7267// Pull out the types of all of the arguments...7268std::vector<Type*> ParamTypes;7269for (const ParamInfo &Arg : ArgList)7270ParamTypes.push_back(Arg.V->getType());72717272if (!FunctionType::isValidReturnType(RetType))7273return true;72747275FuncTy = FunctionType::get(RetType, ParamTypes, false);7276}7277return false;7278}72797280/// parseInvoke7281/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList7282/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue7283bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {7284LocTy CallLoc = Lex.getLoc();7285AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());7286std::vector<unsigned> FwdRefAttrGrps;7287LocTy NoBuiltinLoc;7288unsigned CC;7289unsigned InvokeAddrSpace;7290Type *RetType = nullptr;7291LocTy RetTypeLoc;7292ValID CalleeID;7293SmallVector<ParamInfo, 16> ArgList;7294SmallVector<OperandBundleDef, 2> BundleList;72957296BasicBlock *NormalBB, *UnwindBB;7297if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||7298parseOptionalProgramAddrSpace(InvokeAddrSpace) ||7299parseType(RetType, RetTypeLoc, true /*void allowed*/) ||7300parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||7301parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,7302NoBuiltinLoc) ||7303parseOptionalOperandBundles(BundleList, PFS) ||7304parseToken(lltok::kw_to, "expected 'to' in invoke") ||7305parseTypeAndBasicBlock(NormalBB, PFS) ||7306parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||7307parseTypeAndBasicBlock(UnwindBB, PFS))7308return true;73097310// If RetType is a non-function pointer type, then this is the short syntax7311// for the call, which means that RetType is just the return type. Infer the7312// rest of the function argument types from the arguments that are present.7313FunctionType *Ty;7314if (resolveFunctionType(RetType, ArgList, Ty))7315return error(RetTypeLoc, "Invalid result type for LLVM function");73167317CalleeID.FTy = Ty;73187319// Look up the callee.7320Value *Callee;7321if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,7322Callee, &PFS))7323return true;73247325// Set up the Attribute for the function.7326SmallVector<Value *, 8> Args;7327SmallVector<AttributeSet, 8> ArgAttrs;73287329// Loop through FunctionType's arguments and ensure they are specified7330// correctly. Also, gather any parameter attributes.7331FunctionType::param_iterator I = Ty->param_begin();7332FunctionType::param_iterator E = Ty->param_end();7333for (const ParamInfo &Arg : ArgList) {7334Type *ExpectedTy = nullptr;7335if (I != E) {7336ExpectedTy = *I++;7337} else if (!Ty->isVarArg()) {7338return error(Arg.Loc, "too many arguments specified");7339}73407341if (ExpectedTy && ExpectedTy != Arg.V->getType())7342return error(Arg.Loc, "argument is not of expected type '" +7343getTypeString(ExpectedTy) + "'");7344Args.push_back(Arg.V);7345ArgAttrs.push_back(Arg.Attrs);7346}73477348if (I != E)7349return error(CallLoc, "not enough parameters specified for call");73507351// Finish off the Attribute and check them7352AttributeList PAL =7353AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),7354AttributeSet::get(Context, RetAttrs), ArgAttrs);73557356InvokeInst *II =7357InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);7358II->setCallingConv(CC);7359II->setAttributes(PAL);7360ForwardRefAttrGroups[II] = FwdRefAttrGrps;7361Inst = II;7362return false;7363}73647365/// parseResume7366/// ::= 'resume' TypeAndValue7367bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {7368Value *Exn; LocTy ExnLoc;7369if (parseTypeAndValue(Exn, ExnLoc, PFS))7370return true;73717372ResumeInst *RI = ResumeInst::Create(Exn);7373Inst = RI;7374return false;7375}73767377bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,7378PerFunctionState &PFS) {7379if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))7380return true;73817382while (Lex.getKind() != lltok::rsquare) {7383// If this isn't the first argument, we need a comma.7384if (!Args.empty() &&7385parseToken(lltok::comma, "expected ',' in argument list"))7386return true;73877388// parse the argument.7389LocTy ArgLoc;7390Type *ArgTy = nullptr;7391if (parseType(ArgTy, ArgLoc))7392return true;73937394Value *V;7395if (ArgTy->isMetadataTy()) {7396if (parseMetadataAsValue(V, PFS))7397return true;7398} else {7399if (parseValue(ArgTy, V, PFS))7400return true;7401}7402Args.push_back(V);7403}74047405Lex.Lex(); // Lex the ']'.7406return false;7407}74087409/// parseCleanupRet7410/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)7411bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {7412Value *CleanupPad = nullptr;74137414if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))7415return true;74167417if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))7418return true;74197420if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))7421return true;74227423BasicBlock *UnwindBB = nullptr;7424if (Lex.getKind() == lltok::kw_to) {7425Lex.Lex();7426if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))7427return true;7428} else {7429if (parseTypeAndBasicBlock(UnwindBB, PFS)) {7430return true;7431}7432}74337434Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);7435return false;7436}74377438/// parseCatchRet7439/// ::= 'catchret' from Parent Value 'to' TypeAndValue7440bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {7441Value *CatchPad = nullptr;74427443if (parseToken(lltok::kw_from, "expected 'from' after catchret"))7444return true;74457446if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))7447return true;74487449BasicBlock *BB;7450if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||7451parseTypeAndBasicBlock(BB, PFS))7452return true;74537454Inst = CatchReturnInst::Create(CatchPad, BB);7455return false;7456}74577458/// parseCatchSwitch7459/// ::= 'catchswitch' within Parent7460bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {7461Value *ParentPad;74627463if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))7464return true;74657466if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&7467Lex.getKind() != lltok::LocalVarID)7468return tokError("expected scope value for catchswitch");74697470if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))7471return true;74727473if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))7474return true;74757476SmallVector<BasicBlock *, 32> Table;7477do {7478BasicBlock *DestBB;7479if (parseTypeAndBasicBlock(DestBB, PFS))7480return true;7481Table.push_back(DestBB);7482} while (EatIfPresent(lltok::comma));74837484if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))7485return true;74867487if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))7488return true;74897490BasicBlock *UnwindBB = nullptr;7491if (EatIfPresent(lltok::kw_to)) {7492if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))7493return true;7494} else {7495if (parseTypeAndBasicBlock(UnwindBB, PFS))7496return true;7497}74987499auto *CatchSwitch =7500CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());7501for (BasicBlock *DestBB : Table)7502CatchSwitch->addHandler(DestBB);7503Inst = CatchSwitch;7504return false;7505}75067507/// parseCatchPad7508/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue7509bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {7510Value *CatchSwitch = nullptr;75117512if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))7513return true;75147515if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)7516return tokError("expected scope value for catchpad");75177518if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))7519return true;75207521SmallVector<Value *, 8> Args;7522if (parseExceptionArgs(Args, PFS))7523return true;75247525Inst = CatchPadInst::Create(CatchSwitch, Args);7526return false;7527}75287529/// parseCleanupPad7530/// ::= 'cleanuppad' within Parent ParamList7531bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {7532Value *ParentPad = nullptr;75337534if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))7535return true;75367537if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&7538Lex.getKind() != lltok::LocalVarID)7539return tokError("expected scope value for cleanuppad");75407541if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))7542return true;75437544SmallVector<Value *, 8> Args;7545if (parseExceptionArgs(Args, PFS))7546return true;75477548Inst = CleanupPadInst::Create(ParentPad, Args);7549return false;7550}75517552//===----------------------------------------------------------------------===//7553// Unary Operators.7554//===----------------------------------------------------------------------===//75557556/// parseUnaryOp7557/// ::= UnaryOp TypeAndValue ',' Value7558///7559/// If IsFP is false, then any integer operand is allowed, if it is true, any fp7560/// operand is allowed.7561bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,7562unsigned Opc, bool IsFP) {7563LocTy Loc; Value *LHS;7564if (parseTypeAndValue(LHS, Loc, PFS))7565return true;75667567bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()7568: LHS->getType()->isIntOrIntVectorTy();75697570if (!Valid)7571return error(Loc, "invalid operand type for instruction");75727573Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);7574return false;7575}75767577/// parseCallBr7578/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList7579/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue7580/// '[' LabelList ']'7581bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {7582LocTy CallLoc = Lex.getLoc();7583AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());7584std::vector<unsigned> FwdRefAttrGrps;7585LocTy NoBuiltinLoc;7586unsigned CC;7587Type *RetType = nullptr;7588LocTy RetTypeLoc;7589ValID CalleeID;7590SmallVector<ParamInfo, 16> ArgList;7591SmallVector<OperandBundleDef, 2> BundleList;75927593BasicBlock *DefaultDest;7594if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||7595parseType(RetType, RetTypeLoc, true /*void allowed*/) ||7596parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||7597parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,7598NoBuiltinLoc) ||7599parseOptionalOperandBundles(BundleList, PFS) ||7600parseToken(lltok::kw_to, "expected 'to' in callbr") ||7601parseTypeAndBasicBlock(DefaultDest, PFS) ||7602parseToken(lltok::lsquare, "expected '[' in callbr"))7603return true;76047605// parse the destination list.7606SmallVector<BasicBlock *, 16> IndirectDests;76077608if (Lex.getKind() != lltok::rsquare) {7609BasicBlock *DestBB;7610if (parseTypeAndBasicBlock(DestBB, PFS))7611return true;7612IndirectDests.push_back(DestBB);76137614while (EatIfPresent(lltok::comma)) {7615if (parseTypeAndBasicBlock(DestBB, PFS))7616return true;7617IndirectDests.push_back(DestBB);7618}7619}76207621if (parseToken(lltok::rsquare, "expected ']' at end of block list"))7622return true;76237624// If RetType is a non-function pointer type, then this is the short syntax7625// for the call, which means that RetType is just the return type. Infer the7626// rest of the function argument types from the arguments that are present.7627FunctionType *Ty;7628if (resolveFunctionType(RetType, ArgList, Ty))7629return error(RetTypeLoc, "Invalid result type for LLVM function");76307631CalleeID.FTy = Ty;76327633// Look up the callee.7634Value *Callee;7635if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))7636return true;76377638// Set up the Attribute for the function.7639SmallVector<Value *, 8> Args;7640SmallVector<AttributeSet, 8> ArgAttrs;76417642// Loop through FunctionType's arguments and ensure they are specified7643// correctly. Also, gather any parameter attributes.7644FunctionType::param_iterator I = Ty->param_begin();7645FunctionType::param_iterator E = Ty->param_end();7646for (const ParamInfo &Arg : ArgList) {7647Type *ExpectedTy = nullptr;7648if (I != E) {7649ExpectedTy = *I++;7650} else if (!Ty->isVarArg()) {7651return error(Arg.Loc, "too many arguments specified");7652}76537654if (ExpectedTy && ExpectedTy != Arg.V->getType())7655return error(Arg.Loc, "argument is not of expected type '" +7656getTypeString(ExpectedTy) + "'");7657Args.push_back(Arg.V);7658ArgAttrs.push_back(Arg.Attrs);7659}76607661if (I != E)7662return error(CallLoc, "not enough parameters specified for call");76637664// Finish off the Attribute and check them7665AttributeList PAL =7666AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),7667AttributeSet::get(Context, RetAttrs), ArgAttrs);76687669CallBrInst *CBI =7670CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,7671BundleList);7672CBI->setCallingConv(CC);7673CBI->setAttributes(PAL);7674ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;7675Inst = CBI;7676return false;7677}76787679//===----------------------------------------------------------------------===//7680// Binary Operators.7681//===----------------------------------------------------------------------===//76827683/// parseArithmetic7684/// ::= ArithmeticOps TypeAndValue ',' Value7685///7686/// If IsFP is false, then any integer operand is allowed, if it is true, any fp7687/// operand is allowed.7688bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,7689unsigned Opc, bool IsFP) {7690LocTy Loc; Value *LHS, *RHS;7691if (parseTypeAndValue(LHS, Loc, PFS) ||7692parseToken(lltok::comma, "expected ',' in arithmetic operation") ||7693parseValue(LHS->getType(), RHS, PFS))7694return true;76957696bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()7697: LHS->getType()->isIntOrIntVectorTy();76987699if (!Valid)7700return error(Loc, "invalid operand type for instruction");77017702Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);7703return false;7704}77057706/// parseLogical7707/// ::= ArithmeticOps TypeAndValue ',' Value {7708bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,7709unsigned Opc) {7710LocTy Loc; Value *LHS, *RHS;7711if (parseTypeAndValue(LHS, Loc, PFS) ||7712parseToken(lltok::comma, "expected ',' in logical operation") ||7713parseValue(LHS->getType(), RHS, PFS))7714return true;77157716if (!LHS->getType()->isIntOrIntVectorTy())7717return error(Loc,7718"instruction requires integer or integer vector operands");77197720Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);7721return false;7722}77237724/// parseCompare7725/// ::= 'icmp' IPredicates TypeAndValue ',' Value7726/// ::= 'fcmp' FPredicates TypeAndValue ',' Value7727bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,7728unsigned Opc) {7729// parse the integer/fp comparison predicate.7730LocTy Loc;7731unsigned Pred;7732Value *LHS, *RHS;7733if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||7734parseToken(lltok::comma, "expected ',' after compare value") ||7735parseValue(LHS->getType(), RHS, PFS))7736return true;77377738if (Opc == Instruction::FCmp) {7739if (!LHS->getType()->isFPOrFPVectorTy())7740return error(Loc, "fcmp requires floating point operands");7741Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);7742} else {7743assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");7744if (!LHS->getType()->isIntOrIntVectorTy() &&7745!LHS->getType()->isPtrOrPtrVectorTy())7746return error(Loc, "icmp requires integer operands");7747Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);7748}7749return false;7750}77517752//===----------------------------------------------------------------------===//7753// Other Instructions.7754//===----------------------------------------------------------------------===//77557756/// parseCast7757/// ::= CastOpc TypeAndValue 'to' Type7758bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,7759unsigned Opc) {7760LocTy Loc;7761Value *Op;7762Type *DestTy = nullptr;7763if (parseTypeAndValue(Op, Loc, PFS) ||7764parseToken(lltok::kw_to, "expected 'to' after cast value") ||7765parseType(DestTy))7766return true;77677768if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {7769CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);7770return error(Loc, "invalid cast opcode for cast from '" +7771getTypeString(Op->getType()) + "' to '" +7772getTypeString(DestTy) + "'");7773}7774Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);7775return false;7776}77777778/// parseSelect7779/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue7780bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {7781LocTy Loc;7782Value *Op0, *Op1, *Op2;7783if (parseTypeAndValue(Op0, Loc, PFS) ||7784parseToken(lltok::comma, "expected ',' after select condition") ||7785parseTypeAndValue(Op1, PFS) ||7786parseToken(lltok::comma, "expected ',' after select value") ||7787parseTypeAndValue(Op2, PFS))7788return true;77897790if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))7791return error(Loc, Reason);77927793Inst = SelectInst::Create(Op0, Op1, Op2);7794return false;7795}77967797/// parseVAArg7798/// ::= 'va_arg' TypeAndValue ',' Type7799bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {7800Value *Op;7801Type *EltTy = nullptr;7802LocTy TypeLoc;7803if (parseTypeAndValue(Op, PFS) ||7804parseToken(lltok::comma, "expected ',' after vaarg operand") ||7805parseType(EltTy, TypeLoc))7806return true;78077808if (!EltTy->isFirstClassType())7809return error(TypeLoc, "va_arg requires operand with first class type");78107811Inst = new VAArgInst(Op, EltTy);7812return false;7813}78147815/// parseExtractElement7816/// ::= 'extractelement' TypeAndValue ',' TypeAndValue7817bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {7818LocTy Loc;7819Value *Op0, *Op1;7820if (parseTypeAndValue(Op0, Loc, PFS) ||7821parseToken(lltok::comma, "expected ',' after extract value") ||7822parseTypeAndValue(Op1, PFS))7823return true;78247825if (!ExtractElementInst::isValidOperands(Op0, Op1))7826return error(Loc, "invalid extractelement operands");78277828Inst = ExtractElementInst::Create(Op0, Op1);7829return false;7830}78317832/// parseInsertElement7833/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue7834bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {7835LocTy Loc;7836Value *Op0, *Op1, *Op2;7837if (parseTypeAndValue(Op0, Loc, PFS) ||7838parseToken(lltok::comma, "expected ',' after insertelement value") ||7839parseTypeAndValue(Op1, PFS) ||7840parseToken(lltok::comma, "expected ',' after insertelement value") ||7841parseTypeAndValue(Op2, PFS))7842return true;78437844if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))7845return error(Loc, "invalid insertelement operands");78467847Inst = InsertElementInst::Create(Op0, Op1, Op2);7848return false;7849}78507851/// parseShuffleVector7852/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue7853bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {7854LocTy Loc;7855Value *Op0, *Op1, *Op2;7856if (parseTypeAndValue(Op0, Loc, PFS) ||7857parseToken(lltok::comma, "expected ',' after shuffle mask") ||7858parseTypeAndValue(Op1, PFS) ||7859parseToken(lltok::comma, "expected ',' after shuffle value") ||7860parseTypeAndValue(Op2, PFS))7861return true;78627863if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))7864return error(Loc, "invalid shufflevector operands");78657866Inst = new ShuffleVectorInst(Op0, Op1, Op2);7867return false;7868}78697870/// parsePHI7871/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*7872int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {7873Type *Ty = nullptr; LocTy TypeLoc;7874Value *Op0, *Op1;78757876if (parseType(Ty, TypeLoc))7877return true;78787879if (!Ty->isFirstClassType())7880return error(TypeLoc, "phi node must have first class type");78817882bool First = true;7883bool AteExtraComma = false;7884SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;78857886while (true) {7887if (First) {7888if (Lex.getKind() != lltok::lsquare)7889break;7890First = false;7891} else if (!EatIfPresent(lltok::comma))7892break;78937894if (Lex.getKind() == lltok::MetadataVar) {7895AteExtraComma = true;7896break;7897}78987899if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||7900parseValue(Ty, Op0, PFS) ||7901parseToken(lltok::comma, "expected ',' after insertelement value") ||7902parseValue(Type::getLabelTy(Context), Op1, PFS) ||7903parseToken(lltok::rsquare, "expected ']' in phi value list"))7904return true;79057906PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));7907}79087909PHINode *PN = PHINode::Create(Ty, PHIVals.size());7910for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)7911PN->addIncoming(PHIVals[i].first, PHIVals[i].second);7912Inst = PN;7913return AteExtraComma ? InstExtraComma : InstNormal;7914}79157916/// parseLandingPad7917/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+7918/// Clause7919/// ::= 'catch' TypeAndValue7920/// ::= 'filter'7921/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*7922bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {7923Type *Ty = nullptr; LocTy TyLoc;79247925if (parseType(Ty, TyLoc))7926return true;79277928std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));7929LP->setCleanup(EatIfPresent(lltok::kw_cleanup));79307931while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){7932LandingPadInst::ClauseType CT;7933if (EatIfPresent(lltok::kw_catch))7934CT = LandingPadInst::Catch;7935else if (EatIfPresent(lltok::kw_filter))7936CT = LandingPadInst::Filter;7937else7938return tokError("expected 'catch' or 'filter' clause type");79397940Value *V;7941LocTy VLoc;7942if (parseTypeAndValue(V, VLoc, PFS))7943return true;79447945// A 'catch' type expects a non-array constant. A filter clause expects an7946// array constant.7947if (CT == LandingPadInst::Catch) {7948if (isa<ArrayType>(V->getType()))7949error(VLoc, "'catch' clause has an invalid type");7950} else {7951if (!isa<ArrayType>(V->getType()))7952error(VLoc, "'filter' clause has an invalid type");7953}79547955Constant *CV = dyn_cast<Constant>(V);7956if (!CV)7957return error(VLoc, "clause argument must be a constant");7958LP->addClause(CV);7959}79607961Inst = LP.release();7962return false;7963}79647965/// parseFreeze7966/// ::= 'freeze' Type Value7967bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {7968LocTy Loc;7969Value *Op;7970if (parseTypeAndValue(Op, Loc, PFS))7971return true;79727973Inst = new FreezeInst(Op);7974return false;7975}79767977/// parseCall7978/// ::= 'call' OptionalFastMathFlags OptionalCallingConv7979/// OptionalAttrs Type Value ParameterList OptionalAttrs7980/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv7981/// OptionalAttrs Type Value ParameterList OptionalAttrs7982/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv7983/// OptionalAttrs Type Value ParameterList OptionalAttrs7984/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv7985/// OptionalAttrs Type Value ParameterList OptionalAttrs7986bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,7987CallInst::TailCallKind TCK) {7988AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());7989std::vector<unsigned> FwdRefAttrGrps;7990LocTy BuiltinLoc;7991unsigned CallAddrSpace;7992unsigned CC;7993Type *RetType = nullptr;7994LocTy RetTypeLoc;7995ValID CalleeID;7996SmallVector<ParamInfo, 16> ArgList;7997SmallVector<OperandBundleDef, 2> BundleList;7998LocTy CallLoc = Lex.getLoc();79998000if (TCK != CallInst::TCK_None &&8001parseToken(lltok::kw_call,8002"expected 'tail call', 'musttail call', or 'notail call'"))8003return true;80048005FastMathFlags FMF = EatFastMathFlagsIfPresent();80068007if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||8008parseOptionalProgramAddrSpace(CallAddrSpace) ||8009parseType(RetType, RetTypeLoc, true /*void allowed*/) ||8010parseValID(CalleeID, &PFS) ||8011parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,8012PFS.getFunction().isVarArg()) ||8013parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||8014parseOptionalOperandBundles(BundleList, PFS))8015return true;80168017// If RetType is a non-function pointer type, then this is the short syntax8018// for the call, which means that RetType is just the return type. Infer the8019// rest of the function argument types from the arguments that are present.8020FunctionType *Ty;8021if (resolveFunctionType(RetType, ArgList, Ty))8022return error(RetTypeLoc, "Invalid result type for LLVM function");80238024CalleeID.FTy = Ty;80258026// Look up the callee.8027Value *Callee;8028if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,8029&PFS))8030return true;80318032// Set up the Attribute for the function.8033SmallVector<AttributeSet, 8> Attrs;80348035SmallVector<Value*, 8> Args;80368037// Loop through FunctionType's arguments and ensure they are specified8038// correctly. Also, gather any parameter attributes.8039FunctionType::param_iterator I = Ty->param_begin();8040FunctionType::param_iterator E = Ty->param_end();8041for (const ParamInfo &Arg : ArgList) {8042Type *ExpectedTy = nullptr;8043if (I != E) {8044ExpectedTy = *I++;8045} else if (!Ty->isVarArg()) {8046return error(Arg.Loc, "too many arguments specified");8047}80488049if (ExpectedTy && ExpectedTy != Arg.V->getType())8050return error(Arg.Loc, "argument is not of expected type '" +8051getTypeString(ExpectedTy) + "'");8052Args.push_back(Arg.V);8053Attrs.push_back(Arg.Attrs);8054}80558056if (I != E)8057return error(CallLoc, "not enough parameters specified for call");80588059// Finish off the Attribute and check them8060AttributeList PAL =8061AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),8062AttributeSet::get(Context, RetAttrs), Attrs);80638064CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);8065CI->setTailCallKind(TCK);8066CI->setCallingConv(CC);8067if (FMF.any()) {8068if (!isa<FPMathOperator>(CI)) {8069CI->deleteValue();8070return error(CallLoc, "fast-math-flags specified for call without "8071"floating-point scalar or vector return type");8072}8073CI->setFastMathFlags(FMF);8074}80758076if (CalleeID.Kind == ValID::t_GlobalName &&8077isOldDbgFormatIntrinsic(CalleeID.StrVal)) {8078if (SeenNewDbgInfoFormat) {8079CI->deleteValue();8080return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "8081"using non-intrinsic debug info");8082}8083if (!SeenOldDbgInfoFormat)8084M->setNewDbgInfoFormatFlag(false);8085SeenOldDbgInfoFormat = true;8086}8087CI->setAttributes(PAL);8088ForwardRefAttrGroups[CI] = FwdRefAttrGrps;8089Inst = CI;8090return false;8091}80928093//===----------------------------------------------------------------------===//8094// Memory Instructions.8095//===----------------------------------------------------------------------===//80968097/// parseAlloc8098/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?8099/// (',' 'align' i32)? (',', 'addrspace(n))?8100int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {8101Value *Size = nullptr;8102LocTy SizeLoc, TyLoc, ASLoc;8103MaybeAlign Alignment;8104unsigned AddrSpace = 0;8105Type *Ty = nullptr;81068107bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);8108bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);81098110if (parseType(Ty, TyLoc))8111return true;81128113if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))8114return error(TyLoc, "invalid type for alloca");81158116bool AteExtraComma = false;8117if (EatIfPresent(lltok::comma)) {8118if (Lex.getKind() == lltok::kw_align) {8119if (parseOptionalAlignment(Alignment))8120return true;8121if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))8122return true;8123} else if (Lex.getKind() == lltok::kw_addrspace) {8124ASLoc = Lex.getLoc();8125if (parseOptionalAddrSpace(AddrSpace))8126return true;8127} else if (Lex.getKind() == lltok::MetadataVar) {8128AteExtraComma = true;8129} else {8130if (parseTypeAndValue(Size, SizeLoc, PFS))8131return true;8132if (EatIfPresent(lltok::comma)) {8133if (Lex.getKind() == lltok::kw_align) {8134if (parseOptionalAlignment(Alignment))8135return true;8136if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))8137return true;8138} else if (Lex.getKind() == lltok::kw_addrspace) {8139ASLoc = Lex.getLoc();8140if (parseOptionalAddrSpace(AddrSpace))8141return true;8142} else if (Lex.getKind() == lltok::MetadataVar) {8143AteExtraComma = true;8144}8145}8146}8147}81488149if (Size && !Size->getType()->isIntegerTy())8150return error(SizeLoc, "element count must have integer type");81518152SmallPtrSet<Type *, 4> Visited;8153if (!Alignment && !Ty->isSized(&Visited))8154return error(TyLoc, "Cannot allocate unsized type");8155if (!Alignment)8156Alignment = M->getDataLayout().getPrefTypeAlign(Ty);8157AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);8158AI->setUsedWithInAlloca(IsInAlloca);8159AI->setSwiftError(IsSwiftError);8160Inst = AI;8161return AteExtraComma ? InstExtraComma : InstNormal;8162}81638164/// parseLoad8165/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?8166/// ::= 'load' 'atomic' 'volatile'? TypeAndValue8167/// 'singlethread'? AtomicOrdering (',' 'align' i32)?8168int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {8169Value *Val; LocTy Loc;8170MaybeAlign Alignment;8171bool AteExtraComma = false;8172bool isAtomic = false;8173AtomicOrdering Ordering = AtomicOrdering::NotAtomic;8174SyncScope::ID SSID = SyncScope::System;81758176if (Lex.getKind() == lltok::kw_atomic) {8177isAtomic = true;8178Lex.Lex();8179}81808181bool isVolatile = false;8182if (Lex.getKind() == lltok::kw_volatile) {8183isVolatile = true;8184Lex.Lex();8185}81868187Type *Ty;8188LocTy ExplicitTypeLoc = Lex.getLoc();8189if (parseType(Ty) ||8190parseToken(lltok::comma, "expected comma after load's type") ||8191parseTypeAndValue(Val, Loc, PFS) ||8192parseScopeAndOrdering(isAtomic, SSID, Ordering) ||8193parseOptionalCommaAlign(Alignment, AteExtraComma))8194return true;81958196if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())8197return error(Loc, "load operand must be a pointer to a first class type");8198if (isAtomic && !Alignment)8199return error(Loc, "atomic load must have explicit non-zero alignment");8200if (Ordering == AtomicOrdering::Release ||8201Ordering == AtomicOrdering::AcquireRelease)8202return error(Loc, "atomic load cannot use Release ordering");82038204SmallPtrSet<Type *, 4> Visited;8205if (!Alignment && !Ty->isSized(&Visited))8206return error(ExplicitTypeLoc, "loading unsized types is not allowed");8207if (!Alignment)8208Alignment = M->getDataLayout().getABITypeAlign(Ty);8209Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);8210return AteExtraComma ? InstExtraComma : InstNormal;8211}82128213/// parseStore82148215/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?8216/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue8217/// 'singlethread'? AtomicOrdering (',' 'align' i32)?8218int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {8219Value *Val, *Ptr; LocTy Loc, PtrLoc;8220MaybeAlign Alignment;8221bool AteExtraComma = false;8222bool isAtomic = false;8223AtomicOrdering Ordering = AtomicOrdering::NotAtomic;8224SyncScope::ID SSID = SyncScope::System;82258226if (Lex.getKind() == lltok::kw_atomic) {8227isAtomic = true;8228Lex.Lex();8229}82308231bool isVolatile = false;8232if (Lex.getKind() == lltok::kw_volatile) {8233isVolatile = true;8234Lex.Lex();8235}82368237if (parseTypeAndValue(Val, Loc, PFS) ||8238parseToken(lltok::comma, "expected ',' after store operand") ||8239parseTypeAndValue(Ptr, PtrLoc, PFS) ||8240parseScopeAndOrdering(isAtomic, SSID, Ordering) ||8241parseOptionalCommaAlign(Alignment, AteExtraComma))8242return true;82438244if (!Ptr->getType()->isPointerTy())8245return error(PtrLoc, "store operand must be a pointer");8246if (!Val->getType()->isFirstClassType())8247return error(Loc, "store operand must be a first class value");8248if (isAtomic && !Alignment)8249return error(Loc, "atomic store must have explicit non-zero alignment");8250if (Ordering == AtomicOrdering::Acquire ||8251Ordering == AtomicOrdering::AcquireRelease)8252return error(Loc, "atomic store cannot use Acquire ordering");8253SmallPtrSet<Type *, 4> Visited;8254if (!Alignment && !Val->getType()->isSized(&Visited))8255return error(Loc, "storing unsized types is not allowed");8256if (!Alignment)8257Alignment = M->getDataLayout().getABITypeAlign(Val->getType());82588259Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);8260return AteExtraComma ? InstExtraComma : InstNormal;8261}82628263/// parseCmpXchg8264/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','8265/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','8266/// 'Align'?8267int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {8268Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;8269bool AteExtraComma = false;8270AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;8271AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;8272SyncScope::ID SSID = SyncScope::System;8273bool isVolatile = false;8274bool isWeak = false;8275MaybeAlign Alignment;82768277if (EatIfPresent(lltok::kw_weak))8278isWeak = true;82798280if (EatIfPresent(lltok::kw_volatile))8281isVolatile = true;82828283if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||8284parseToken(lltok::comma, "expected ',' after cmpxchg address") ||8285parseTypeAndValue(Cmp, CmpLoc, PFS) ||8286parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||8287parseTypeAndValue(New, NewLoc, PFS) ||8288parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||8289parseOrdering(FailureOrdering) ||8290parseOptionalCommaAlign(Alignment, AteExtraComma))8291return true;82928293if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))8294return tokError("invalid cmpxchg success ordering");8295if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))8296return tokError("invalid cmpxchg failure ordering");8297if (!Ptr->getType()->isPointerTy())8298return error(PtrLoc, "cmpxchg operand must be a pointer");8299if (Cmp->getType() != New->getType())8300return error(NewLoc, "compare value and new value type do not match");8301if (!New->getType()->isFirstClassType())8302return error(NewLoc, "cmpxchg operand must be a first class value");83038304const Align DefaultAlignment(8305PFS.getFunction().getDataLayout().getTypeStoreSize(8306Cmp->getType()));83078308AtomicCmpXchgInst *CXI =8309new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),8310SuccessOrdering, FailureOrdering, SSID);8311CXI->setVolatile(isVolatile);8312CXI->setWeak(isWeak);83138314Inst = CXI;8315return AteExtraComma ? InstExtraComma : InstNormal;8316}83178318/// parseAtomicRMW8319/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue8320/// 'singlethread'? AtomicOrdering8321int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {8322Value *Ptr, *Val; LocTy PtrLoc, ValLoc;8323bool AteExtraComma = false;8324AtomicOrdering Ordering = AtomicOrdering::NotAtomic;8325SyncScope::ID SSID = SyncScope::System;8326bool isVolatile = false;8327bool IsFP = false;8328AtomicRMWInst::BinOp Operation;8329MaybeAlign Alignment;83308331if (EatIfPresent(lltok::kw_volatile))8332isVolatile = true;83338334switch (Lex.getKind()) {8335default:8336return tokError("expected binary operation in atomicrmw");8337case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;8338case lltok::kw_add: Operation = AtomicRMWInst::Add; break;8339case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;8340case lltok::kw_and: Operation = AtomicRMWInst::And; break;8341case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;8342case lltok::kw_or: Operation = AtomicRMWInst::Or; break;8343case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;8344case lltok::kw_max: Operation = AtomicRMWInst::Max; break;8345case lltok::kw_min: Operation = AtomicRMWInst::Min; break;8346case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;8347case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;8348case lltok::kw_uinc_wrap:8349Operation = AtomicRMWInst::UIncWrap;8350break;8351case lltok::kw_udec_wrap:8352Operation = AtomicRMWInst::UDecWrap;8353break;8354case lltok::kw_fadd:8355Operation = AtomicRMWInst::FAdd;8356IsFP = true;8357break;8358case lltok::kw_fsub:8359Operation = AtomicRMWInst::FSub;8360IsFP = true;8361break;8362case lltok::kw_fmax:8363Operation = AtomicRMWInst::FMax;8364IsFP = true;8365break;8366case lltok::kw_fmin:8367Operation = AtomicRMWInst::FMin;8368IsFP = true;8369break;8370}8371Lex.Lex(); // Eat the operation.83728373if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||8374parseToken(lltok::comma, "expected ',' after atomicrmw address") ||8375parseTypeAndValue(Val, ValLoc, PFS) ||8376parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||8377parseOptionalCommaAlign(Alignment, AteExtraComma))8378return true;83798380if (Ordering == AtomicOrdering::Unordered)8381return tokError("atomicrmw cannot be unordered");8382if (!Ptr->getType()->isPointerTy())8383return error(PtrLoc, "atomicrmw operand must be a pointer");8384if (Val->getType()->isScalableTy())8385return error(ValLoc, "atomicrmw operand may not be scalable");83868387if (Operation == AtomicRMWInst::Xchg) {8388if (!Val->getType()->isIntegerTy() &&8389!Val->getType()->isFloatingPointTy() &&8390!Val->getType()->isPointerTy()) {8391return error(8392ValLoc,8393"atomicrmw " + AtomicRMWInst::getOperationName(Operation) +8394" operand must be an integer, floating point, or pointer type");8395}8396} else if (IsFP) {8397if (!Val->getType()->isFPOrFPVectorTy()) {8398return error(ValLoc, "atomicrmw " +8399AtomicRMWInst::getOperationName(Operation) +8400" operand must be a floating point type");8401}8402} else {8403if (!Val->getType()->isIntegerTy()) {8404return error(ValLoc, "atomicrmw " +8405AtomicRMWInst::getOperationName(Operation) +8406" operand must be an integer");8407}8408}84098410unsigned Size =8411PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(8412Val->getType());8413if (Size < 8 || (Size & (Size - 1)))8414return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"8415" integer");8416const Align DefaultAlignment(8417PFS.getFunction().getDataLayout().getTypeStoreSize(8418Val->getType()));8419AtomicRMWInst *RMWI =8420new AtomicRMWInst(Operation, Ptr, Val,8421Alignment.value_or(DefaultAlignment), Ordering, SSID);8422RMWI->setVolatile(isVolatile);8423Inst = RMWI;8424return AteExtraComma ? InstExtraComma : InstNormal;8425}84268427/// parseFence8428/// ::= 'fence' 'singlethread'? AtomicOrdering8429int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {8430AtomicOrdering Ordering = AtomicOrdering::NotAtomic;8431SyncScope::ID SSID = SyncScope::System;8432if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))8433return true;84348435if (Ordering == AtomicOrdering::Unordered)8436return tokError("fence cannot be unordered");8437if (Ordering == AtomicOrdering::Monotonic)8438return tokError("fence cannot be monotonic");84398440Inst = new FenceInst(Context, Ordering, SSID);8441return InstNormal;8442}84438444/// parseGetElementPtr8445/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*8446int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {8447Value *Ptr = nullptr;8448Value *Val = nullptr;8449LocTy Loc, EltLoc;8450GEPNoWrapFlags NW;84518452while (true) {8453if (EatIfPresent(lltok::kw_inbounds))8454NW |= GEPNoWrapFlags::inBounds();8455else if (EatIfPresent(lltok::kw_nusw))8456NW |= GEPNoWrapFlags::noUnsignedSignedWrap();8457else if (EatIfPresent(lltok::kw_nuw))8458NW |= GEPNoWrapFlags::noUnsignedWrap();8459else8460break;8461}84628463Type *Ty = nullptr;8464if (parseType(Ty) ||8465parseToken(lltok::comma, "expected comma after getelementptr's type") ||8466parseTypeAndValue(Ptr, Loc, PFS))8467return true;84688469Type *BaseType = Ptr->getType();8470PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());8471if (!BasePointerType)8472return error(Loc, "base of getelementptr must be a pointer");84738474SmallVector<Value*, 16> Indices;8475bool AteExtraComma = false;8476// GEP returns a vector of pointers if at least one of parameters is a vector.8477// All vector parameters should have the same vector width.8478ElementCount GEPWidth = BaseType->isVectorTy()8479? cast<VectorType>(BaseType)->getElementCount()8480: ElementCount::getFixed(0);84818482while (EatIfPresent(lltok::comma)) {8483if (Lex.getKind() == lltok::MetadataVar) {8484AteExtraComma = true;8485break;8486}8487if (parseTypeAndValue(Val, EltLoc, PFS))8488return true;8489if (!Val->getType()->isIntOrIntVectorTy())8490return error(EltLoc, "getelementptr index must be an integer");84918492if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {8493ElementCount ValNumEl = ValVTy->getElementCount();8494if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)8495return error(8496EltLoc,8497"getelementptr vector index has a wrong number of elements");8498GEPWidth = ValNumEl;8499}8500Indices.push_back(Val);8501}85028503SmallPtrSet<Type*, 4> Visited;8504if (!Indices.empty() && !Ty->isSized(&Visited))8505return error(Loc, "base element of getelementptr must be sized");85068507auto *STy = dyn_cast<StructType>(Ty);8508if (STy && STy->containsScalableVectorType())8509return error(Loc, "getelementptr cannot target structure that contains "8510"scalable vector type");85118512if (!GetElementPtrInst::getIndexedType(Ty, Indices))8513return error(Loc, "invalid getelementptr indices");8514GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);8515Inst = GEP;8516GEP->setNoWrapFlags(NW);8517return AteExtraComma ? InstExtraComma : InstNormal;8518}85198520/// parseExtractValue8521/// ::= 'extractvalue' TypeAndValue (',' uint32)+8522int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {8523Value *Val; LocTy Loc;8524SmallVector<unsigned, 4> Indices;8525bool AteExtraComma;8526if (parseTypeAndValue(Val, Loc, PFS) ||8527parseIndexList(Indices, AteExtraComma))8528return true;85298530if (!Val->getType()->isAggregateType())8531return error(Loc, "extractvalue operand must be aggregate type");85328533if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))8534return error(Loc, "invalid indices for extractvalue");8535Inst = ExtractValueInst::Create(Val, Indices);8536return AteExtraComma ? InstExtraComma : InstNormal;8537}85388539/// parseInsertValue8540/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+8541int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {8542Value *Val0, *Val1; LocTy Loc0, Loc1;8543SmallVector<unsigned, 4> Indices;8544bool AteExtraComma;8545if (parseTypeAndValue(Val0, Loc0, PFS) ||8546parseToken(lltok::comma, "expected comma after insertvalue operand") ||8547parseTypeAndValue(Val1, Loc1, PFS) ||8548parseIndexList(Indices, AteExtraComma))8549return true;85508551if (!Val0->getType()->isAggregateType())8552return error(Loc0, "insertvalue operand must be aggregate type");85538554Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);8555if (!IndexedType)8556return error(Loc0, "invalid indices for insertvalue");8557if (IndexedType != Val1->getType())8558return error(Loc1, "insertvalue operand and field disagree in type: '" +8559getTypeString(Val1->getType()) + "' instead of '" +8560getTypeString(IndexedType) + "'");8561Inst = InsertValueInst::Create(Val0, Val1, Indices);8562return AteExtraComma ? InstExtraComma : InstNormal;8563}85648565//===----------------------------------------------------------------------===//8566// Embedded metadata.8567//===----------------------------------------------------------------------===//85688569/// parseMDNodeVector8570/// ::= { Element (',' Element)* }8571/// Element8572/// ::= 'null' | Metadata8573bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {8574if (parseToken(lltok::lbrace, "expected '{' here"))8575return true;85768577// Check for an empty list.8578if (EatIfPresent(lltok::rbrace))8579return false;85808581do {8582if (EatIfPresent(lltok::kw_null)) {8583Elts.push_back(nullptr);8584continue;8585}85868587Metadata *MD;8588if (parseMetadata(MD, nullptr))8589return true;8590Elts.push_back(MD);8591} while (EatIfPresent(lltok::comma));85928593return parseToken(lltok::rbrace, "expected end of metadata node");8594}85958596//===----------------------------------------------------------------------===//8597// Use-list order directives.8598//===----------------------------------------------------------------------===//8599bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,8600SMLoc Loc) {8601if (V->use_empty())8602return error(Loc, "value has no uses");86038604unsigned NumUses = 0;8605SmallDenseMap<const Use *, unsigned, 16> Order;8606for (const Use &U : V->uses()) {8607if (++NumUses > Indexes.size())8608break;8609Order[&U] = Indexes[NumUses - 1];8610}8611if (NumUses < 2)8612return error(Loc, "value only has one use");8613if (Order.size() != Indexes.size() || NumUses > Indexes.size())8614return error(Loc,8615"wrong number of indexes, expected " + Twine(V->getNumUses()));86168617V->sortUseList([&](const Use &L, const Use &R) {8618return Order.lookup(&L) < Order.lookup(&R);8619});8620return false;8621}86228623/// parseUseListOrderIndexes8624/// ::= '{' uint32 (',' uint32)+ '}'8625bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {8626SMLoc Loc = Lex.getLoc();8627if (parseToken(lltok::lbrace, "expected '{' here"))8628return true;8629if (Lex.getKind() == lltok::rbrace)8630return Lex.Error("expected non-empty list of uselistorder indexes");86318632// Use Offset, Max, and IsOrdered to check consistency of indexes. The8633// indexes should be distinct numbers in the range [0, size-1], and should8634// not be in order.8635unsigned Offset = 0;8636unsigned Max = 0;8637bool IsOrdered = true;8638assert(Indexes.empty() && "Expected empty order vector");8639do {8640unsigned Index;8641if (parseUInt32(Index))8642return true;86438644// Update consistency checks.8645Offset += Index - Indexes.size();8646Max = std::max(Max, Index);8647IsOrdered &= Index == Indexes.size();86488649Indexes.push_back(Index);8650} while (EatIfPresent(lltok::comma));86518652if (parseToken(lltok::rbrace, "expected '}' here"))8653return true;86548655if (Indexes.size() < 2)8656return error(Loc, "expected >= 2 uselistorder indexes");8657if (Offset != 0 || Max >= Indexes.size())8658return error(Loc,8659"expected distinct uselistorder indexes in range [0, size)");8660if (IsOrdered)8661return error(Loc, "expected uselistorder indexes to change the order");86628663return false;8664}86658666/// parseUseListOrder8667/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes8668bool LLParser::parseUseListOrder(PerFunctionState *PFS) {8669SMLoc Loc = Lex.getLoc();8670if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))8671return true;86728673Value *V;8674SmallVector<unsigned, 16> Indexes;8675if (parseTypeAndValue(V, PFS) ||8676parseToken(lltok::comma, "expected comma in uselistorder directive") ||8677parseUseListOrderIndexes(Indexes))8678return true;86798680return sortUseListOrder(V, Indexes, Loc);8681}86828683/// parseUseListOrderBB8684/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes8685bool LLParser::parseUseListOrderBB() {8686assert(Lex.getKind() == lltok::kw_uselistorder_bb);8687SMLoc Loc = Lex.getLoc();8688Lex.Lex();86898690ValID Fn, Label;8691SmallVector<unsigned, 16> Indexes;8692if (parseValID(Fn, /*PFS=*/nullptr) ||8693parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||8694parseValID(Label, /*PFS=*/nullptr) ||8695parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||8696parseUseListOrderIndexes(Indexes))8697return true;86988699// Check the function.8700GlobalValue *GV;8701if (Fn.Kind == ValID::t_GlobalName)8702GV = M->getNamedValue(Fn.StrVal);8703else if (Fn.Kind == ValID::t_GlobalID)8704GV = NumberedVals.get(Fn.UIntVal);8705else8706return error(Fn.Loc, "expected function name in uselistorder_bb");8707if (!GV)8708return error(Fn.Loc,8709"invalid function forward reference in uselistorder_bb");8710auto *F = dyn_cast<Function>(GV);8711if (!F)8712return error(Fn.Loc, "expected function name in uselistorder_bb");8713if (F->isDeclaration())8714return error(Fn.Loc, "invalid declaration in uselistorder_bb");87158716// Check the basic block.8717if (Label.Kind == ValID::t_LocalID)8718return error(Label.Loc, "invalid numeric label in uselistorder_bb");8719if (Label.Kind != ValID::t_LocalName)8720return error(Label.Loc, "expected basic block name in uselistorder_bb");8721Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);8722if (!V)8723return error(Label.Loc, "invalid basic block in uselistorder_bb");8724if (!isa<BasicBlock>(V))8725return error(Label.Loc, "expected basic block in uselistorder_bb");87268727return sortUseListOrder(V, Indexes, Loc);8728}87298730/// ModuleEntry8731/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'8732/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'8733bool LLParser::parseModuleEntry(unsigned ID) {8734assert(Lex.getKind() == lltok::kw_module);8735Lex.Lex();87368737std::string Path;8738if (parseToken(lltok::colon, "expected ':' here") ||8739parseToken(lltok::lparen, "expected '(' here") ||8740parseToken(lltok::kw_path, "expected 'path' here") ||8741parseToken(lltok::colon, "expected ':' here") ||8742parseStringConstant(Path) ||8743parseToken(lltok::comma, "expected ',' here") ||8744parseToken(lltok::kw_hash, "expected 'hash' here") ||8745parseToken(lltok::colon, "expected ':' here") ||8746parseToken(lltok::lparen, "expected '(' here"))8747return true;87488749ModuleHash Hash;8750if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||8751parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||8752parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||8753parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||8754parseUInt32(Hash[4]))8755return true;87568757if (parseToken(lltok::rparen, "expected ')' here") ||8758parseToken(lltok::rparen, "expected ')' here"))8759return true;87608761auto ModuleEntry = Index->addModule(Path, Hash);8762ModuleIdMap[ID] = ModuleEntry->first();87638764return false;8765}87668767/// TypeIdEntry8768/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'8769bool LLParser::parseTypeIdEntry(unsigned ID) {8770assert(Lex.getKind() == lltok::kw_typeid);8771Lex.Lex();87728773std::string Name;8774if (parseToken(lltok::colon, "expected ':' here") ||8775parseToken(lltok::lparen, "expected '(' here") ||8776parseToken(lltok::kw_name, "expected 'name' here") ||8777parseToken(lltok::colon, "expected ':' here") ||8778parseStringConstant(Name))8779return true;87808781TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);8782if (parseToken(lltok::comma, "expected ',' here") ||8783parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))8784return true;87858786// Check if this ID was forward referenced, and if so, update the8787// corresponding GUIDs.8788auto FwdRefTIDs = ForwardRefTypeIds.find(ID);8789if (FwdRefTIDs != ForwardRefTypeIds.end()) {8790for (auto TIDRef : FwdRefTIDs->second) {8791assert(!*TIDRef.first &&8792"Forward referenced type id GUID expected to be 0");8793*TIDRef.first = GlobalValue::getGUID(Name);8794}8795ForwardRefTypeIds.erase(FwdRefTIDs);8796}87978798return false;8799}88008801/// TypeIdSummary8802/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'8803bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {8804if (parseToken(lltok::kw_summary, "expected 'summary' here") ||8805parseToken(lltok::colon, "expected ':' here") ||8806parseToken(lltok::lparen, "expected '(' here") ||8807parseTypeTestResolution(TIS.TTRes))8808return true;88098810if (EatIfPresent(lltok::comma)) {8811// Expect optional wpdResolutions field8812if (parseOptionalWpdResolutions(TIS.WPDRes))8813return true;8814}88158816if (parseToken(lltok::rparen, "expected ')' here"))8817return true;88188819return false;8820}88218822static ValueInfo EmptyVI =8823ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);88248825/// TypeIdCompatibleVtableEntry8826/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','8827/// TypeIdCompatibleVtableInfo8828/// ')'8829bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {8830assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);8831Lex.Lex();88328833std::string Name;8834if (parseToken(lltok::colon, "expected ':' here") ||8835parseToken(lltok::lparen, "expected '(' here") ||8836parseToken(lltok::kw_name, "expected 'name' here") ||8837parseToken(lltok::colon, "expected ':' here") ||8838parseStringConstant(Name))8839return true;88408841TypeIdCompatibleVtableInfo &TI =8842Index->getOrInsertTypeIdCompatibleVtableSummary(Name);8843if (parseToken(lltok::comma, "expected ',' here") ||8844parseToken(lltok::kw_summary, "expected 'summary' here") ||8845parseToken(lltok::colon, "expected ':' here") ||8846parseToken(lltok::lparen, "expected '(' here"))8847return true;88488849IdToIndexMapType IdToIndexMap;8850// parse each call edge8851do {8852uint64_t Offset;8853if (parseToken(lltok::lparen, "expected '(' here") ||8854parseToken(lltok::kw_offset, "expected 'offset' here") ||8855parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||8856parseToken(lltok::comma, "expected ',' here"))8857return true;88588859LocTy Loc = Lex.getLoc();8860unsigned GVId;8861ValueInfo VI;8862if (parseGVReference(VI, GVId))8863return true;88648865// Keep track of the TypeIdCompatibleVtableInfo array index needing a8866// forward reference. We will save the location of the ValueInfo needing an8867// update, but can only do so once the std::vector is finalized.8868if (VI == EmptyVI)8869IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));8870TI.push_back({Offset, VI});88718872if (parseToken(lltok::rparen, "expected ')' in call"))8873return true;8874} while (EatIfPresent(lltok::comma));88758876// Now that the TI vector is finalized, it is safe to save the locations8877// of any forward GV references that need updating later.8878for (auto I : IdToIndexMap) {8879auto &Infos = ForwardRefValueInfos[I.first];8880for (auto P : I.second) {8881assert(TI[P.first].VTableVI == EmptyVI &&8882"Forward referenced ValueInfo expected to be empty");8883Infos.emplace_back(&TI[P.first].VTableVI, P.second);8884}8885}88868887if (parseToken(lltok::rparen, "expected ')' here") ||8888parseToken(lltok::rparen, "expected ')' here"))8889return true;88908891// Check if this ID was forward referenced, and if so, update the8892// corresponding GUIDs.8893auto FwdRefTIDs = ForwardRefTypeIds.find(ID);8894if (FwdRefTIDs != ForwardRefTypeIds.end()) {8895for (auto TIDRef : FwdRefTIDs->second) {8896assert(!*TIDRef.first &&8897"Forward referenced type id GUID expected to be 0");8898*TIDRef.first = GlobalValue::getGUID(Name);8899}8900ForwardRefTypeIds.erase(FwdRefTIDs);8901}89028903return false;8904}89058906/// TypeTestResolution8907/// ::= 'typeTestRes' ':' '(' 'kind' ':'8908/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','8909/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?8910/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?8911/// [',' 'inlinesBits' ':' UInt64]? ')'8912bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {8913if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||8914parseToken(lltok::colon, "expected ':' here") ||8915parseToken(lltok::lparen, "expected '(' here") ||8916parseToken(lltok::kw_kind, "expected 'kind' here") ||8917parseToken(lltok::colon, "expected ':' here"))8918return true;89198920switch (Lex.getKind()) {8921case lltok::kw_unknown:8922TTRes.TheKind = TypeTestResolution::Unknown;8923break;8924case lltok::kw_unsat:8925TTRes.TheKind = TypeTestResolution::Unsat;8926break;8927case lltok::kw_byteArray:8928TTRes.TheKind = TypeTestResolution::ByteArray;8929break;8930case lltok::kw_inline:8931TTRes.TheKind = TypeTestResolution::Inline;8932break;8933case lltok::kw_single:8934TTRes.TheKind = TypeTestResolution::Single;8935break;8936case lltok::kw_allOnes:8937TTRes.TheKind = TypeTestResolution::AllOnes;8938break;8939default:8940return error(Lex.getLoc(), "unexpected TypeTestResolution kind");8941}8942Lex.Lex();89438944if (parseToken(lltok::comma, "expected ',' here") ||8945parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||8946parseToken(lltok::colon, "expected ':' here") ||8947parseUInt32(TTRes.SizeM1BitWidth))8948return true;89498950// parse optional fields8951while (EatIfPresent(lltok::comma)) {8952switch (Lex.getKind()) {8953case lltok::kw_alignLog2:8954Lex.Lex();8955if (parseToken(lltok::colon, "expected ':'") ||8956parseUInt64(TTRes.AlignLog2))8957return true;8958break;8959case lltok::kw_sizeM1:8960Lex.Lex();8961if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))8962return true;8963break;8964case lltok::kw_bitMask: {8965unsigned Val;8966Lex.Lex();8967if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))8968return true;8969assert(Val <= 0xff);8970TTRes.BitMask = (uint8_t)Val;8971break;8972}8973case lltok::kw_inlineBits:8974Lex.Lex();8975if (parseToken(lltok::colon, "expected ':'") ||8976parseUInt64(TTRes.InlineBits))8977return true;8978break;8979default:8980return error(Lex.getLoc(), "expected optional TypeTestResolution field");8981}8982}89838984if (parseToken(lltok::rparen, "expected ')' here"))8985return true;89868987return false;8988}89898990/// OptionalWpdResolutions8991/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'8992/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'8993bool LLParser::parseOptionalWpdResolutions(8994std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {8995if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||8996parseToken(lltok::colon, "expected ':' here") ||8997parseToken(lltok::lparen, "expected '(' here"))8998return true;89999000do {9001uint64_t Offset;9002WholeProgramDevirtResolution WPDRes;9003if (parseToken(lltok::lparen, "expected '(' here") ||9004parseToken(lltok::kw_offset, "expected 'offset' here") ||9005parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||9006parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||9007parseToken(lltok::rparen, "expected ')' here"))9008return true;9009WPDResMap[Offset] = WPDRes;9010} while (EatIfPresent(lltok::comma));90119012if (parseToken(lltok::rparen, "expected ')' here"))9013return true;90149015return false;9016}90179018/// WpdRes9019/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'9020/// [',' OptionalResByArg]? ')'9021/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'9022/// ',' 'singleImplName' ':' STRINGCONSTANT ','9023/// [',' OptionalResByArg]? ')'9024/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'9025/// [',' OptionalResByArg]? ')'9026bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {9027if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||9028parseToken(lltok::colon, "expected ':' here") ||9029parseToken(lltok::lparen, "expected '(' here") ||9030parseToken(lltok::kw_kind, "expected 'kind' here") ||9031parseToken(lltok::colon, "expected ':' here"))9032return true;90339034switch (Lex.getKind()) {9035case lltok::kw_indir:9036WPDRes.TheKind = WholeProgramDevirtResolution::Indir;9037break;9038case lltok::kw_singleImpl:9039WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;9040break;9041case lltok::kw_branchFunnel:9042WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;9043break;9044default:9045return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");9046}9047Lex.Lex();90489049// parse optional fields9050while (EatIfPresent(lltok::comma)) {9051switch (Lex.getKind()) {9052case lltok::kw_singleImplName:9053Lex.Lex();9054if (parseToken(lltok::colon, "expected ':' here") ||9055parseStringConstant(WPDRes.SingleImplName))9056return true;9057break;9058case lltok::kw_resByArg:9059if (parseOptionalResByArg(WPDRes.ResByArg))9060return true;9061break;9062default:9063return error(Lex.getLoc(),9064"expected optional WholeProgramDevirtResolution field");9065}9066}90679068if (parseToken(lltok::rparen, "expected ')' here"))9069return true;90709071return false;9072}90739074/// OptionalResByArg9075/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'9076/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'9077/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |9078/// 'virtualConstProp' )9079/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?9080/// [',' 'bit' ':' UInt32]? ')'9081bool LLParser::parseOptionalResByArg(9082std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>9083&ResByArg) {9084if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||9085parseToken(lltok::colon, "expected ':' here") ||9086parseToken(lltok::lparen, "expected '(' here"))9087return true;90889089do {9090std::vector<uint64_t> Args;9091if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||9092parseToken(lltok::kw_byArg, "expected 'byArg here") ||9093parseToken(lltok::colon, "expected ':' here") ||9094parseToken(lltok::lparen, "expected '(' here") ||9095parseToken(lltok::kw_kind, "expected 'kind' here") ||9096parseToken(lltok::colon, "expected ':' here"))9097return true;90989099WholeProgramDevirtResolution::ByArg ByArg;9100switch (Lex.getKind()) {9101case lltok::kw_indir:9102ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;9103break;9104case lltok::kw_uniformRetVal:9105ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;9106break;9107case lltok::kw_uniqueRetVal:9108ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;9109break;9110case lltok::kw_virtualConstProp:9111ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;9112break;9113default:9114return error(Lex.getLoc(),9115"unexpected WholeProgramDevirtResolution::ByArg kind");9116}9117Lex.Lex();91189119// parse optional fields9120while (EatIfPresent(lltok::comma)) {9121switch (Lex.getKind()) {9122case lltok::kw_info:9123Lex.Lex();9124if (parseToken(lltok::colon, "expected ':' here") ||9125parseUInt64(ByArg.Info))9126return true;9127break;9128case lltok::kw_byte:9129Lex.Lex();9130if (parseToken(lltok::colon, "expected ':' here") ||9131parseUInt32(ByArg.Byte))9132return true;9133break;9134case lltok::kw_bit:9135Lex.Lex();9136if (parseToken(lltok::colon, "expected ':' here") ||9137parseUInt32(ByArg.Bit))9138return true;9139break;9140default:9141return error(Lex.getLoc(),9142"expected optional whole program devirt field");9143}9144}91459146if (parseToken(lltok::rparen, "expected ')' here"))9147return true;91489149ResByArg[Args] = ByArg;9150} while (EatIfPresent(lltok::comma));91519152if (parseToken(lltok::rparen, "expected ')' here"))9153return true;91549155return false;9156}91579158/// OptionalResByArg9159/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'9160bool LLParser::parseArgs(std::vector<uint64_t> &Args) {9161if (parseToken(lltok::kw_args, "expected 'args' here") ||9162parseToken(lltok::colon, "expected ':' here") ||9163parseToken(lltok::lparen, "expected '(' here"))9164return true;91659166do {9167uint64_t Val;9168if (parseUInt64(Val))9169return true;9170Args.push_back(Val);9171} while (EatIfPresent(lltok::comma));91729173if (parseToken(lltok::rparen, "expected ')' here"))9174return true;91759176return false;9177}91789179static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;91809181static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {9182bool ReadOnly = Fwd->isReadOnly();9183bool WriteOnly = Fwd->isWriteOnly();9184assert(!(ReadOnly && WriteOnly));9185*Fwd = Resolved;9186if (ReadOnly)9187Fwd->setReadOnly();9188if (WriteOnly)9189Fwd->setWriteOnly();9190}91919192/// Stores the given Name/GUID and associated summary into the Index.9193/// Also updates any forward references to the associated entry ID.9194bool LLParser::addGlobalValueToIndex(9195std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,9196unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {9197// First create the ValueInfo utilizing the Name or GUID.9198ValueInfo VI;9199if (GUID != 0) {9200assert(Name.empty());9201VI = Index->getOrInsertValueInfo(GUID);9202} else {9203assert(!Name.empty());9204if (M) {9205auto *GV = M->getNamedValue(Name);9206if (!GV)9207return error(Loc, "Reference to undefined global \"" + Name + "\"");92089209VI = Index->getOrInsertValueInfo(GV);9210} else {9211assert(9212(!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&9213"Need a source_filename to compute GUID for local");9214GUID = GlobalValue::getGUID(9215GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));9216VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));9217}9218}92199220// Resolve forward references from calls/refs9221auto FwdRefVIs = ForwardRefValueInfos.find(ID);9222if (FwdRefVIs != ForwardRefValueInfos.end()) {9223for (auto VIRef : FwdRefVIs->second) {9224assert(VIRef.first->getRef() == FwdVIRef &&9225"Forward referenced ValueInfo expected to be empty");9226resolveFwdRef(VIRef.first, VI);9227}9228ForwardRefValueInfos.erase(FwdRefVIs);9229}92309231// Resolve forward references from aliases9232auto FwdRefAliasees = ForwardRefAliasees.find(ID);9233if (FwdRefAliasees != ForwardRefAliasees.end()) {9234for (auto AliaseeRef : FwdRefAliasees->second) {9235assert(!AliaseeRef.first->hasAliasee() &&9236"Forward referencing alias already has aliasee");9237assert(Summary && "Aliasee must be a definition");9238AliaseeRef.first->setAliasee(VI, Summary.get());9239}9240ForwardRefAliasees.erase(FwdRefAliasees);9241}92429243// Add the summary if one was provided.9244if (Summary)9245Index->addGlobalValueSummary(VI, std::move(Summary));92469247// Save the associated ValueInfo for use in later references by ID.9248if (ID == NumberedValueInfos.size())9249NumberedValueInfos.push_back(VI);9250else {9251// Handle non-continuous numbers (to make test simplification easier).9252if (ID > NumberedValueInfos.size())9253NumberedValueInfos.resize(ID + 1);9254NumberedValueInfos[ID] = VI;9255}92569257return false;9258}92599260/// parseSummaryIndexFlags9261/// ::= 'flags' ':' UInt649262bool LLParser::parseSummaryIndexFlags() {9263assert(Lex.getKind() == lltok::kw_flags);9264Lex.Lex();92659266if (parseToken(lltok::colon, "expected ':' here"))9267return true;9268uint64_t Flags;9269if (parseUInt64(Flags))9270return true;9271if (Index)9272Index->setFlags(Flags);9273return false;9274}92759276/// parseBlockCount9277/// ::= 'blockcount' ':' UInt649278bool LLParser::parseBlockCount() {9279assert(Lex.getKind() == lltok::kw_blockcount);9280Lex.Lex();92819282if (parseToken(lltok::colon, "expected ':' here"))9283return true;9284uint64_t BlockCount;9285if (parseUInt64(BlockCount))9286return true;9287if (Index)9288Index->setBlockCount(BlockCount);9289return false;9290}92919292/// parseGVEntry9293/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)9294/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'9295/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'9296bool LLParser::parseGVEntry(unsigned ID) {9297assert(Lex.getKind() == lltok::kw_gv);9298Lex.Lex();92999300if (parseToken(lltok::colon, "expected ':' here") ||9301parseToken(lltok::lparen, "expected '(' here"))9302return true;93039304LocTy Loc = Lex.getLoc();9305std::string Name;9306GlobalValue::GUID GUID = 0;9307switch (Lex.getKind()) {9308case lltok::kw_name:9309Lex.Lex();9310if (parseToken(lltok::colon, "expected ':' here") ||9311parseStringConstant(Name))9312return true;9313// Can't create GUID/ValueInfo until we have the linkage.9314break;9315case lltok::kw_guid:9316Lex.Lex();9317if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))9318return true;9319break;9320default:9321return error(Lex.getLoc(), "expected name or guid tag");9322}93239324if (!EatIfPresent(lltok::comma)) {9325// No summaries. Wrap up.9326if (parseToken(lltok::rparen, "expected ')' here"))9327return true;9328// This was created for a call to an external or indirect target.9329// A GUID with no summary came from a VALUE_GUID record, dummy GUID9330// created for indirect calls with VP. A Name with no GUID came from9331// an external definition. We pass ExternalLinkage since that is only9332// used when the GUID must be computed from Name, and in that case9333// the symbol must have external linkage.9334return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,9335nullptr, Loc);9336}93379338// Have a list of summaries9339if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||9340parseToken(lltok::colon, "expected ':' here") ||9341parseToken(lltok::lparen, "expected '(' here"))9342return true;9343do {9344switch (Lex.getKind()) {9345case lltok::kw_function:9346if (parseFunctionSummary(Name, GUID, ID))9347return true;9348break;9349case lltok::kw_variable:9350if (parseVariableSummary(Name, GUID, ID))9351return true;9352break;9353case lltok::kw_alias:9354if (parseAliasSummary(Name, GUID, ID))9355return true;9356break;9357default:9358return error(Lex.getLoc(), "expected summary type");9359}9360} while (EatIfPresent(lltok::comma));93619362if (parseToken(lltok::rparen, "expected ')' here") ||9363parseToken(lltok::rparen, "expected ')' here"))9364return true;93659366return false;9367}93689369/// FunctionSummary9370/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags9371/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?9372/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?9373/// [',' OptionalRefs]? ')'9374bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,9375unsigned ID) {9376LocTy Loc = Lex.getLoc();9377assert(Lex.getKind() == lltok::kw_function);9378Lex.Lex();93799380StringRef ModulePath;9381GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(9382GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,9383/*NotEligibleToImport=*/false,9384/*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,9385GlobalValueSummary::Definition);9386unsigned InstCount;9387std::vector<FunctionSummary::EdgeTy> Calls;9388FunctionSummary::TypeIdInfo TypeIdInfo;9389std::vector<FunctionSummary::ParamAccess> ParamAccesses;9390std::vector<ValueInfo> Refs;9391std::vector<CallsiteInfo> Callsites;9392std::vector<AllocInfo> Allocs;9393// Default is all-zeros (conservative values).9394FunctionSummary::FFlags FFlags = {};9395if (parseToken(lltok::colon, "expected ':' here") ||9396parseToken(lltok::lparen, "expected '(' here") ||9397parseModuleReference(ModulePath) ||9398parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||9399parseToken(lltok::comma, "expected ',' here") ||9400parseToken(lltok::kw_insts, "expected 'insts' here") ||9401parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))9402return true;94039404// parse optional fields9405while (EatIfPresent(lltok::comma)) {9406switch (Lex.getKind()) {9407case lltok::kw_funcFlags:9408if (parseOptionalFFlags(FFlags))9409return true;9410break;9411case lltok::kw_calls:9412if (parseOptionalCalls(Calls))9413return true;9414break;9415case lltok::kw_typeIdInfo:9416if (parseOptionalTypeIdInfo(TypeIdInfo))9417return true;9418break;9419case lltok::kw_refs:9420if (parseOptionalRefs(Refs))9421return true;9422break;9423case lltok::kw_params:9424if (parseOptionalParamAccesses(ParamAccesses))9425return true;9426break;9427case lltok::kw_allocs:9428if (parseOptionalAllocs(Allocs))9429return true;9430break;9431case lltok::kw_callsites:9432if (parseOptionalCallsites(Callsites))9433return true;9434break;9435default:9436return error(Lex.getLoc(), "expected optional function summary field");9437}9438}94399440if (parseToken(lltok::rparen, "expected ')' here"))9441return true;94429443auto FS = std::make_unique<FunctionSummary>(9444GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),9445std::move(Calls), std::move(TypeIdInfo.TypeTests),9446std::move(TypeIdInfo.TypeTestAssumeVCalls),9447std::move(TypeIdInfo.TypeCheckedLoadVCalls),9448std::move(TypeIdInfo.TypeTestAssumeConstVCalls),9449std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),9450std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));94519452FS->setModulePath(ModulePath);94539454return addGlobalValueToIndex(Name, GUID,9455(GlobalValue::LinkageTypes)GVFlags.Linkage, ID,9456std::move(FS), Loc);9457}94589459/// VariableSummary9460/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags9461/// [',' OptionalRefs]? ')'9462bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,9463unsigned ID) {9464LocTy Loc = Lex.getLoc();9465assert(Lex.getKind() == lltok::kw_variable);9466Lex.Lex();94679468StringRef ModulePath;9469GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(9470GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,9471/*NotEligibleToImport=*/false,9472/*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,9473GlobalValueSummary::Definition);9474GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,9475/* WriteOnly */ false,9476/* Constant */ false,9477GlobalObject::VCallVisibilityPublic);9478std::vector<ValueInfo> Refs;9479VTableFuncList VTableFuncs;9480if (parseToken(lltok::colon, "expected ':' here") ||9481parseToken(lltok::lparen, "expected '(' here") ||9482parseModuleReference(ModulePath) ||9483parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||9484parseToken(lltok::comma, "expected ',' here") ||9485parseGVarFlags(GVarFlags))9486return true;94879488// parse optional fields9489while (EatIfPresent(lltok::comma)) {9490switch (Lex.getKind()) {9491case lltok::kw_vTableFuncs:9492if (parseOptionalVTableFuncs(VTableFuncs))9493return true;9494break;9495case lltok::kw_refs:9496if (parseOptionalRefs(Refs))9497return true;9498break;9499default:9500return error(Lex.getLoc(), "expected optional variable summary field");9501}9502}95039504if (parseToken(lltok::rparen, "expected ')' here"))9505return true;95069507auto GS =9508std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));95099510GS->setModulePath(ModulePath);9511GS->setVTableFuncs(std::move(VTableFuncs));95129513return addGlobalValueToIndex(Name, GUID,9514(GlobalValue::LinkageTypes)GVFlags.Linkage, ID,9515std::move(GS), Loc);9516}95179518/// AliasSummary9519/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','9520/// 'aliasee' ':' GVReference ')'9521bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,9522unsigned ID) {9523assert(Lex.getKind() == lltok::kw_alias);9524LocTy Loc = Lex.getLoc();9525Lex.Lex();95269527StringRef ModulePath;9528GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(9529GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,9530/*NotEligibleToImport=*/false,9531/*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,9532GlobalValueSummary::Definition);9533if (parseToken(lltok::colon, "expected ':' here") ||9534parseToken(lltok::lparen, "expected '(' here") ||9535parseModuleReference(ModulePath) ||9536parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||9537parseToken(lltok::comma, "expected ',' here") ||9538parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||9539parseToken(lltok::colon, "expected ':' here"))9540return true;95419542ValueInfo AliaseeVI;9543unsigned GVId;9544if (parseGVReference(AliaseeVI, GVId))9545return true;95469547if (parseToken(lltok::rparen, "expected ')' here"))9548return true;95499550auto AS = std::make_unique<AliasSummary>(GVFlags);95519552AS->setModulePath(ModulePath);95539554// Record forward reference if the aliasee is not parsed yet.9555if (AliaseeVI.getRef() == FwdVIRef) {9556ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);9557} else {9558auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);9559assert(Summary && "Aliasee must be a definition");9560AS->setAliasee(AliaseeVI, Summary);9561}95629563return addGlobalValueToIndex(Name, GUID,9564(GlobalValue::LinkageTypes)GVFlags.Linkage, ID,9565std::move(AS), Loc);9566}95679568/// Flag9569/// ::= [0|1]9570bool LLParser::parseFlag(unsigned &Val) {9571if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())9572return tokError("expected integer");9573Val = (unsigned)Lex.getAPSIntVal().getBoolValue();9574Lex.Lex();9575return false;9576}95779578/// OptionalFFlags9579/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?9580/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?9581/// [',' 'returnDoesNotAlias' ':' Flag]? ')'9582/// [',' 'noInline' ':' Flag]? ')'9583/// [',' 'alwaysInline' ':' Flag]? ')'9584/// [',' 'noUnwind' ':' Flag]? ')'9585/// [',' 'mayThrow' ':' Flag]? ')'9586/// [',' 'hasUnknownCall' ':' Flag]? ')'9587/// [',' 'mustBeUnreachable' ':' Flag]? ')'95889589bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {9590assert(Lex.getKind() == lltok::kw_funcFlags);9591Lex.Lex();95929593if (parseToken(lltok::colon, "expected ':' in funcFlags") ||9594parseToken(lltok::lparen, "expected '(' in funcFlags"))9595return true;95969597do {9598unsigned Val = 0;9599switch (Lex.getKind()) {9600case lltok::kw_readNone:9601Lex.Lex();9602if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9603return true;9604FFlags.ReadNone = Val;9605break;9606case lltok::kw_readOnly:9607Lex.Lex();9608if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9609return true;9610FFlags.ReadOnly = Val;9611break;9612case lltok::kw_noRecurse:9613Lex.Lex();9614if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9615return true;9616FFlags.NoRecurse = Val;9617break;9618case lltok::kw_returnDoesNotAlias:9619Lex.Lex();9620if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9621return true;9622FFlags.ReturnDoesNotAlias = Val;9623break;9624case lltok::kw_noInline:9625Lex.Lex();9626if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9627return true;9628FFlags.NoInline = Val;9629break;9630case lltok::kw_alwaysInline:9631Lex.Lex();9632if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9633return true;9634FFlags.AlwaysInline = Val;9635break;9636case lltok::kw_noUnwind:9637Lex.Lex();9638if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9639return true;9640FFlags.NoUnwind = Val;9641break;9642case lltok::kw_mayThrow:9643Lex.Lex();9644if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9645return true;9646FFlags.MayThrow = Val;9647break;9648case lltok::kw_hasUnknownCall:9649Lex.Lex();9650if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9651return true;9652FFlags.HasUnknownCall = Val;9653break;9654case lltok::kw_mustBeUnreachable:9655Lex.Lex();9656if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))9657return true;9658FFlags.MustBeUnreachable = Val;9659break;9660default:9661return error(Lex.getLoc(), "expected function flag type");9662}9663} while (EatIfPresent(lltok::comma));96649665if (parseToken(lltok::rparen, "expected ')' in funcFlags"))9666return true;96679668return false;9669}96709671/// OptionalCalls9672/// := 'calls' ':' '(' Call [',' Call]* ')'9673/// Call ::= '(' 'callee' ':' GVReference9674/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?9675/// [ ',' 'tail' ]? ')'9676bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {9677assert(Lex.getKind() == lltok::kw_calls);9678Lex.Lex();96799680if (parseToken(lltok::colon, "expected ':' in calls") ||9681parseToken(lltok::lparen, "expected '(' in calls"))9682return true;96839684IdToIndexMapType IdToIndexMap;9685// parse each call edge9686do {9687ValueInfo VI;9688if (parseToken(lltok::lparen, "expected '(' in call") ||9689parseToken(lltok::kw_callee, "expected 'callee' in call") ||9690parseToken(lltok::colon, "expected ':'"))9691return true;96929693LocTy Loc = Lex.getLoc();9694unsigned GVId;9695if (parseGVReference(VI, GVId))9696return true;96979698CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;9699unsigned RelBF = 0;9700unsigned HasTailCall = false;97019702// parse optional fields9703while (EatIfPresent(lltok::comma)) {9704switch (Lex.getKind()) {9705case lltok::kw_hotness:9706Lex.Lex();9707if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))9708return true;9709break;9710case lltok::kw_relbf:9711Lex.Lex();9712if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))9713return true;9714break;9715case lltok::kw_tail:9716Lex.Lex();9717if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))9718return true;9719break;9720default:9721return error(Lex.getLoc(), "expected hotness, relbf, or tail");9722}9723}9724if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)9725return tokError("Expected only one of hotness or relbf");9726// Keep track of the Call array index needing a forward reference.9727// We will save the location of the ValueInfo needing an update, but9728// can only do so once the std::vector is finalized.9729if (VI.getRef() == FwdVIRef)9730IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));9731Calls.push_back(9732FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});97339734if (parseToken(lltok::rparen, "expected ')' in call"))9735return true;9736} while (EatIfPresent(lltok::comma));97379738// Now that the Calls vector is finalized, it is safe to save the locations9739// of any forward GV references that need updating later.9740for (auto I : IdToIndexMap) {9741auto &Infos = ForwardRefValueInfos[I.first];9742for (auto P : I.second) {9743assert(Calls[P.first].first.getRef() == FwdVIRef &&9744"Forward referenced ValueInfo expected to be empty");9745Infos.emplace_back(&Calls[P.first].first, P.second);9746}9747}97489749if (parseToken(lltok::rparen, "expected ')' in calls"))9750return true;97519752return false;9753}97549755/// Hotness9756/// := ('unknown'|'cold'|'none'|'hot'|'critical')9757bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {9758switch (Lex.getKind()) {9759case lltok::kw_unknown:9760Hotness = CalleeInfo::HotnessType::Unknown;9761break;9762case lltok::kw_cold:9763Hotness = CalleeInfo::HotnessType::Cold;9764break;9765case lltok::kw_none:9766Hotness = CalleeInfo::HotnessType::None;9767break;9768case lltok::kw_hot:9769Hotness = CalleeInfo::HotnessType::Hot;9770break;9771case lltok::kw_critical:9772Hotness = CalleeInfo::HotnessType::Critical;9773break;9774default:9775return error(Lex.getLoc(), "invalid call edge hotness");9776}9777Lex.Lex();9778return false;9779}97809781/// OptionalVTableFuncs9782/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'9783/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'9784bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {9785assert(Lex.getKind() == lltok::kw_vTableFuncs);9786Lex.Lex();97879788if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||9789parseToken(lltok::lparen, "expected '(' in vTableFuncs"))9790return true;97919792IdToIndexMapType IdToIndexMap;9793// parse each virtual function pair9794do {9795ValueInfo VI;9796if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||9797parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||9798parseToken(lltok::colon, "expected ':'"))9799return true;98009801LocTy Loc = Lex.getLoc();9802unsigned GVId;9803if (parseGVReference(VI, GVId))9804return true;98059806uint64_t Offset;9807if (parseToken(lltok::comma, "expected comma") ||9808parseToken(lltok::kw_offset, "expected offset") ||9809parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))9810return true;98119812// Keep track of the VTableFuncs array index needing a forward reference.9813// We will save the location of the ValueInfo needing an update, but9814// can only do so once the std::vector is finalized.9815if (VI == EmptyVI)9816IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));9817VTableFuncs.push_back({VI, Offset});98189819if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))9820return true;9821} while (EatIfPresent(lltok::comma));98229823// Now that the VTableFuncs vector is finalized, it is safe to save the9824// locations of any forward GV references that need updating later.9825for (auto I : IdToIndexMap) {9826auto &Infos = ForwardRefValueInfos[I.first];9827for (auto P : I.second) {9828assert(VTableFuncs[P.first].FuncVI == EmptyVI &&9829"Forward referenced ValueInfo expected to be empty");9830Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);9831}9832}98339834if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))9835return true;98369837return false;9838}98399840/// ParamNo := 'param' ':' UInt649841bool LLParser::parseParamNo(uint64_t &ParamNo) {9842if (parseToken(lltok::kw_param, "expected 'param' here") ||9843parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))9844return true;9845return false;9846}98479848/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'9849bool LLParser::parseParamAccessOffset(ConstantRange &Range) {9850APSInt Lower;9851APSInt Upper;9852auto ParseAPSInt = [&](APSInt &Val) {9853if (Lex.getKind() != lltok::APSInt)9854return tokError("expected integer");9855Val = Lex.getAPSIntVal();9856Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);9857Val.setIsSigned(true);9858Lex.Lex();9859return false;9860};9861if (parseToken(lltok::kw_offset, "expected 'offset' here") ||9862parseToken(lltok::colon, "expected ':' here") ||9863parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||9864parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||9865parseToken(lltok::rsquare, "expected ']' here"))9866return true;98679868++Upper;9869Range =9870(Lower == Upper && !Lower.isMaxValue())9871? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)9872: ConstantRange(Lower, Upper);98739874return false;9875}98769877/// ParamAccessCall9878/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'9879bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,9880IdLocListType &IdLocList) {9881if (parseToken(lltok::lparen, "expected '(' here") ||9882parseToken(lltok::kw_callee, "expected 'callee' here") ||9883parseToken(lltok::colon, "expected ':' here"))9884return true;98859886unsigned GVId;9887ValueInfo VI;9888LocTy Loc = Lex.getLoc();9889if (parseGVReference(VI, GVId))9890return true;98919892Call.Callee = VI;9893IdLocList.emplace_back(GVId, Loc);98949895if (parseToken(lltok::comma, "expected ',' here") ||9896parseParamNo(Call.ParamNo) ||9897parseToken(lltok::comma, "expected ',' here") ||9898parseParamAccessOffset(Call.Offsets))9899return true;99009901if (parseToken(lltok::rparen, "expected ')' here"))9902return true;99039904return false;9905}99069907/// ParamAccess9908/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'9909/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'9910bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,9911IdLocListType &IdLocList) {9912if (parseToken(lltok::lparen, "expected '(' here") ||9913parseParamNo(Param.ParamNo) ||9914parseToken(lltok::comma, "expected ',' here") ||9915parseParamAccessOffset(Param.Use))9916return true;99179918if (EatIfPresent(lltok::comma)) {9919if (parseToken(lltok::kw_calls, "expected 'calls' here") ||9920parseToken(lltok::colon, "expected ':' here") ||9921parseToken(lltok::lparen, "expected '(' here"))9922return true;9923do {9924FunctionSummary::ParamAccess::Call Call;9925if (parseParamAccessCall(Call, IdLocList))9926return true;9927Param.Calls.push_back(Call);9928} while (EatIfPresent(lltok::comma));99299930if (parseToken(lltok::rparen, "expected ')' here"))9931return true;9932}99339934if (parseToken(lltok::rparen, "expected ')' here"))9935return true;99369937return false;9938}99399940/// OptionalParamAccesses9941/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'9942bool LLParser::parseOptionalParamAccesses(9943std::vector<FunctionSummary::ParamAccess> &Params) {9944assert(Lex.getKind() == lltok::kw_params);9945Lex.Lex();99469947if (parseToken(lltok::colon, "expected ':' here") ||9948parseToken(lltok::lparen, "expected '(' here"))9949return true;99509951IdLocListType VContexts;9952size_t CallsNum = 0;9953do {9954FunctionSummary::ParamAccess ParamAccess;9955if (parseParamAccess(ParamAccess, VContexts))9956return true;9957CallsNum += ParamAccess.Calls.size();9958assert(VContexts.size() == CallsNum);9959(void)CallsNum;9960Params.emplace_back(std::move(ParamAccess));9961} while (EatIfPresent(lltok::comma));99629963if (parseToken(lltok::rparen, "expected ')' here"))9964return true;99659966// Now that the Params is finalized, it is safe to save the locations9967// of any forward GV references that need updating later.9968IdLocListType::const_iterator ItContext = VContexts.begin();9969for (auto &PA : Params) {9970for (auto &C : PA.Calls) {9971if (C.Callee.getRef() == FwdVIRef)9972ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,9973ItContext->second);9974++ItContext;9975}9976}9977assert(ItContext == VContexts.end());99789979return false;9980}99819982/// OptionalRefs9983/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'9984bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {9985assert(Lex.getKind() == lltok::kw_refs);9986Lex.Lex();99879988if (parseToken(lltok::colon, "expected ':' in refs") ||9989parseToken(lltok::lparen, "expected '(' in refs"))9990return true;99919992struct ValueContext {9993ValueInfo VI;9994unsigned GVId;9995LocTy Loc;9996};9997std::vector<ValueContext> VContexts;9998// parse each ref edge9999do {10000ValueContext VC;10001VC.Loc = Lex.getLoc();10002if (parseGVReference(VC.VI, VC.GVId))10003return true;10004VContexts.push_back(VC);10005} while (EatIfPresent(lltok::comma));1000610007// Sort value contexts so that ones with writeonly10008// and readonly ValueInfo are at the end of VContexts vector.10009// See FunctionSummary::specialRefCounts()10010llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {10011return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();10012});1001310014IdToIndexMapType IdToIndexMap;10015for (auto &VC : VContexts) {10016// Keep track of the Refs array index needing a forward reference.10017// We will save the location of the ValueInfo needing an update, but10018// can only do so once the std::vector is finalized.10019if (VC.VI.getRef() == FwdVIRef)10020IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));10021Refs.push_back(VC.VI);10022}1002310024// Now that the Refs vector is finalized, it is safe to save the locations10025// of any forward GV references that need updating later.10026for (auto I : IdToIndexMap) {10027auto &Infos = ForwardRefValueInfos[I.first];10028for (auto P : I.second) {10029assert(Refs[P.first].getRef() == FwdVIRef &&10030"Forward referenced ValueInfo expected to be empty");10031Infos.emplace_back(&Refs[P.first], P.second);10032}10033}1003410035if (parseToken(lltok::rparen, "expected ')' in refs"))10036return true;1003710038return false;10039}1004010041/// OptionalTypeIdInfo10042/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?10043/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?10044/// [',' TypeCheckedLoadConstVCalls]? ')'10045bool LLParser::parseOptionalTypeIdInfo(10046FunctionSummary::TypeIdInfo &TypeIdInfo) {10047assert(Lex.getKind() == lltok::kw_typeIdInfo);10048Lex.Lex();1004910050if (parseToken(lltok::colon, "expected ':' here") ||10051parseToken(lltok::lparen, "expected '(' in typeIdInfo"))10052return true;1005310054do {10055switch (Lex.getKind()) {10056case lltok::kw_typeTests:10057if (parseTypeTests(TypeIdInfo.TypeTests))10058return true;10059break;10060case lltok::kw_typeTestAssumeVCalls:10061if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,10062TypeIdInfo.TypeTestAssumeVCalls))10063return true;10064break;10065case lltok::kw_typeCheckedLoadVCalls:10066if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,10067TypeIdInfo.TypeCheckedLoadVCalls))10068return true;10069break;10070case lltok::kw_typeTestAssumeConstVCalls:10071if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,10072TypeIdInfo.TypeTestAssumeConstVCalls))10073return true;10074break;10075case lltok::kw_typeCheckedLoadConstVCalls:10076if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,10077TypeIdInfo.TypeCheckedLoadConstVCalls))10078return true;10079break;10080default:10081return error(Lex.getLoc(), "invalid typeIdInfo list type");10082}10083} while (EatIfPresent(lltok::comma));1008410085if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))10086return true;1008710088return false;10089}1009010091/// TypeTests10092/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)10093/// [',' (SummaryID | UInt64)]* ')'10094bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {10095assert(Lex.getKind() == lltok::kw_typeTests);10096Lex.Lex();1009710098if (parseToken(lltok::colon, "expected ':' here") ||10099parseToken(lltok::lparen, "expected '(' in typeIdInfo"))10100return true;1010110102IdToIndexMapType IdToIndexMap;10103do {10104GlobalValue::GUID GUID = 0;10105if (Lex.getKind() == lltok::SummaryID) {10106unsigned ID = Lex.getUIntVal();10107LocTy Loc = Lex.getLoc();10108// Keep track of the TypeTests array index needing a forward reference.10109// We will save the location of the GUID needing an update, but10110// can only do so once the std::vector is finalized.10111IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));10112Lex.Lex();10113} else if (parseUInt64(GUID))10114return true;10115TypeTests.push_back(GUID);10116} while (EatIfPresent(lltok::comma));1011710118// Now that the TypeTests vector is finalized, it is safe to save the10119// locations of any forward GV references that need updating later.10120for (auto I : IdToIndexMap) {10121auto &Ids = ForwardRefTypeIds[I.first];10122for (auto P : I.second) {10123assert(TypeTests[P.first] == 0 &&10124"Forward referenced type id GUID expected to be 0");10125Ids.emplace_back(&TypeTests[P.first], P.second);10126}10127}1012810129if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))10130return true;1013110132return false;10133}1013410135/// VFuncIdList10136/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'10137bool LLParser::parseVFuncIdList(10138lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {10139assert(Lex.getKind() == Kind);10140Lex.Lex();1014110142if (parseToken(lltok::colon, "expected ':' here") ||10143parseToken(lltok::lparen, "expected '(' here"))10144return true;1014510146IdToIndexMapType IdToIndexMap;10147do {10148FunctionSummary::VFuncId VFuncId;10149if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))10150return true;10151VFuncIdList.push_back(VFuncId);10152} while (EatIfPresent(lltok::comma));1015310154if (parseToken(lltok::rparen, "expected ')' here"))10155return true;1015610157// Now that the VFuncIdList vector is finalized, it is safe to save the10158// locations of any forward GV references that need updating later.10159for (auto I : IdToIndexMap) {10160auto &Ids = ForwardRefTypeIds[I.first];10161for (auto P : I.second) {10162assert(VFuncIdList[P.first].GUID == 0 &&10163"Forward referenced type id GUID expected to be 0");10164Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);10165}10166}1016710168return false;10169}1017010171/// ConstVCallList10172/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'10173bool LLParser::parseConstVCallList(10174lltok::Kind Kind,10175std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {10176assert(Lex.getKind() == Kind);10177Lex.Lex();1017810179if (parseToken(lltok::colon, "expected ':' here") ||10180parseToken(lltok::lparen, "expected '(' here"))10181return true;1018210183IdToIndexMapType IdToIndexMap;10184do {10185FunctionSummary::ConstVCall ConstVCall;10186if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))10187return true;10188ConstVCallList.push_back(ConstVCall);10189} while (EatIfPresent(lltok::comma));1019010191if (parseToken(lltok::rparen, "expected ')' here"))10192return true;1019310194// Now that the ConstVCallList vector is finalized, it is safe to save the10195// locations of any forward GV references that need updating later.10196for (auto I : IdToIndexMap) {10197auto &Ids = ForwardRefTypeIds[I.first];10198for (auto P : I.second) {10199assert(ConstVCallList[P.first].VFunc.GUID == 0 &&10200"Forward referenced type id GUID expected to be 0");10201Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);10202}10203}1020410205return false;10206}1020710208/// ConstVCall10209/// ::= '(' VFuncId ',' Args ')'10210bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,10211IdToIndexMapType &IdToIndexMap, unsigned Index) {10212if (parseToken(lltok::lparen, "expected '(' here") ||10213parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))10214return true;1021510216if (EatIfPresent(lltok::comma))10217if (parseArgs(ConstVCall.Args))10218return true;1021910220if (parseToken(lltok::rparen, "expected ')' here"))10221return true;1022210223return false;10224}1022510226/// VFuncId10227/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','10228/// 'offset' ':' UInt64 ')'10229bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,10230IdToIndexMapType &IdToIndexMap, unsigned Index) {10231assert(Lex.getKind() == lltok::kw_vFuncId);10232Lex.Lex();1023310234if (parseToken(lltok::colon, "expected ':' here") ||10235parseToken(lltok::lparen, "expected '(' here"))10236return true;1023710238if (Lex.getKind() == lltok::SummaryID) {10239VFuncId.GUID = 0;10240unsigned ID = Lex.getUIntVal();10241LocTy Loc = Lex.getLoc();10242// Keep track of the array index needing a forward reference.10243// We will save the location of the GUID needing an update, but10244// can only do so once the caller's std::vector is finalized.10245IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));10246Lex.Lex();10247} else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||10248parseToken(lltok::colon, "expected ':' here") ||10249parseUInt64(VFuncId.GUID))10250return true;1025110252if (parseToken(lltok::comma, "expected ',' here") ||10253parseToken(lltok::kw_offset, "expected 'offset' here") ||10254parseToken(lltok::colon, "expected ':' here") ||10255parseUInt64(VFuncId.Offset) ||10256parseToken(lltok::rparen, "expected ')' here"))10257return true;1025810259return false;10260}1026110262/// GVFlags10263/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','10264/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','10265/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','10266/// 'canAutoHide' ':' Flag ',' ')'10267bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {10268assert(Lex.getKind() == lltok::kw_flags);10269Lex.Lex();1027010271if (parseToken(lltok::colon, "expected ':' here") ||10272parseToken(lltok::lparen, "expected '(' here"))10273return true;1027410275do {10276unsigned Flag = 0;10277switch (Lex.getKind()) {10278case lltok::kw_linkage:10279Lex.Lex();10280if (parseToken(lltok::colon, "expected ':'"))10281return true;10282bool HasLinkage;10283GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);10284assert(HasLinkage && "Linkage not optional in summary entry");10285Lex.Lex();10286break;10287case lltok::kw_visibility:10288Lex.Lex();10289if (parseToken(lltok::colon, "expected ':'"))10290return true;10291parseOptionalVisibility(Flag);10292GVFlags.Visibility = Flag;10293break;10294case lltok::kw_notEligibleToImport:10295Lex.Lex();10296if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))10297return true;10298GVFlags.NotEligibleToImport = Flag;10299break;10300case lltok::kw_live:10301Lex.Lex();10302if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))10303return true;10304GVFlags.Live = Flag;10305break;10306case lltok::kw_dsoLocal:10307Lex.Lex();10308if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))10309return true;10310GVFlags.DSOLocal = Flag;10311break;10312case lltok::kw_canAutoHide:10313Lex.Lex();10314if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))10315return true;10316GVFlags.CanAutoHide = Flag;10317break;10318case lltok::kw_importType:10319Lex.Lex();10320if (parseToken(lltok::colon, "expected ':'"))10321return true;10322GlobalValueSummary::ImportKind IK;10323if (parseOptionalImportType(Lex.getKind(), IK))10324return true;10325GVFlags.ImportType = static_cast<unsigned>(IK);10326Lex.Lex();10327break;10328default:10329return error(Lex.getLoc(), "expected gv flag type");10330}10331} while (EatIfPresent(lltok::comma));1033210333if (parseToken(lltok::rparen, "expected ')' here"))10334return true;1033510336return false;10337}1033810339/// GVarFlags10340/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag10341/// ',' 'writeonly' ':' Flag10342/// ',' 'constant' ':' Flag ')'10343bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {10344assert(Lex.getKind() == lltok::kw_varFlags);10345Lex.Lex();1034610347if (parseToken(lltok::colon, "expected ':' here") ||10348parseToken(lltok::lparen, "expected '(' here"))10349return true;1035010351auto ParseRest = [this](unsigned int &Val) {10352Lex.Lex();10353if (parseToken(lltok::colon, "expected ':'"))10354return true;10355return parseFlag(Val);10356};1035710358do {10359unsigned Flag = 0;10360switch (Lex.getKind()) {10361case lltok::kw_readonly:10362if (ParseRest(Flag))10363return true;10364GVarFlags.MaybeReadOnly = Flag;10365break;10366case lltok::kw_writeonly:10367if (ParseRest(Flag))10368return true;10369GVarFlags.MaybeWriteOnly = Flag;10370break;10371case lltok::kw_constant:10372if (ParseRest(Flag))10373return true;10374GVarFlags.Constant = Flag;10375break;10376case lltok::kw_vcall_visibility:10377if (ParseRest(Flag))10378return true;10379GVarFlags.VCallVisibility = Flag;10380break;10381default:10382return error(Lex.getLoc(), "expected gvar flag type");10383}10384} while (EatIfPresent(lltok::comma));10385return parseToken(lltok::rparen, "expected ')' here");10386}1038710388/// ModuleReference10389/// ::= 'module' ':' UInt10390bool LLParser::parseModuleReference(StringRef &ModulePath) {10391// parse module id.10392if (parseToken(lltok::kw_module, "expected 'module' here") ||10393parseToken(lltok::colon, "expected ':' here") ||10394parseToken(lltok::SummaryID, "expected module ID"))10395return true;1039610397unsigned ModuleID = Lex.getUIntVal();10398auto I = ModuleIdMap.find(ModuleID);10399// We should have already parsed all module IDs10400assert(I != ModuleIdMap.end());10401ModulePath = I->second;10402return false;10403}1040410405/// GVReference10406/// ::= SummaryID10407bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {10408bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);10409if (!ReadOnly)10410WriteOnly = EatIfPresent(lltok::kw_writeonly);10411if (parseToken(lltok::SummaryID, "expected GV ID"))10412return true;1041310414GVId = Lex.getUIntVal();10415// Check if we already have a VI for this GV10416if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {10417assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);10418VI = NumberedValueInfos[GVId];10419} else10420// We will create a forward reference to the stored location.10421VI = ValueInfo(false, FwdVIRef);1042210423if (ReadOnly)10424VI.setReadOnly();10425if (WriteOnly)10426VI.setWriteOnly();10427return false;10428}1042910430/// OptionalAllocs10431/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'10432/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'10433/// ',' MemProfs ')'10434/// Version ::= UInt3210435bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {10436assert(Lex.getKind() == lltok::kw_allocs);10437Lex.Lex();1043810439if (parseToken(lltok::colon, "expected ':' in allocs") ||10440parseToken(lltok::lparen, "expected '(' in allocs"))10441return true;1044210443// parse each alloc10444do {10445if (parseToken(lltok::lparen, "expected '(' in alloc") ||10446parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||10447parseToken(lltok::colon, "expected ':'") ||10448parseToken(lltok::lparen, "expected '(' in versions"))10449return true;1045010451SmallVector<uint8_t> Versions;10452do {10453uint8_t V = 0;10454if (parseAllocType(V))10455return true;10456Versions.push_back(V);10457} while (EatIfPresent(lltok::comma));1045810459if (parseToken(lltok::rparen, "expected ')' in versions") ||10460parseToken(lltok::comma, "expected ',' in alloc"))10461return true;1046210463std::vector<MIBInfo> MIBs;10464if (parseMemProfs(MIBs))10465return true;1046610467Allocs.push_back({Versions, MIBs});1046810469if (parseToken(lltok::rparen, "expected ')' in alloc"))10470return true;10471} while (EatIfPresent(lltok::comma));1047210473if (parseToken(lltok::rparen, "expected ')' in allocs"))10474return true;1047510476return false;10477}1047810479/// MemProfs10480/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'10481/// MemProf ::= '(' 'type' ':' AllocType10482/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'10483/// StackId ::= UInt6410484bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {10485assert(Lex.getKind() == lltok::kw_memProf);10486Lex.Lex();1048710488if (parseToken(lltok::colon, "expected ':' in memprof") ||10489parseToken(lltok::lparen, "expected '(' in memprof"))10490return true;1049110492// parse each MIB10493do {10494if (parseToken(lltok::lparen, "expected '(' in memprof") ||10495parseToken(lltok::kw_type, "expected 'type' in memprof") ||10496parseToken(lltok::colon, "expected ':'"))10497return true;1049810499uint8_t AllocType;10500if (parseAllocType(AllocType))10501return true;1050210503if (parseToken(lltok::comma, "expected ',' in memprof") ||10504parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||10505parseToken(lltok::colon, "expected ':'") ||10506parseToken(lltok::lparen, "expected '(' in stackIds"))10507return true;1050810509SmallVector<unsigned> StackIdIndices;10510do {10511uint64_t StackId = 0;10512if (parseUInt64(StackId))10513return true;10514StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));10515} while (EatIfPresent(lltok::comma));1051610517if (parseToken(lltok::rparen, "expected ')' in stackIds"))10518return true;1051910520MIBs.push_back({(AllocationType)AllocType, StackIdIndices});1052110522if (parseToken(lltok::rparen, "expected ')' in memprof"))10523return true;10524} while (EatIfPresent(lltok::comma));1052510526if (parseToken(lltok::rparen, "expected ')' in memprof"))10527return true;1052810529return false;10530}1053110532/// AllocType10533/// := ('none'|'notcold'|'cold'|'hot')10534bool LLParser::parseAllocType(uint8_t &AllocType) {10535switch (Lex.getKind()) {10536case lltok::kw_none:10537AllocType = (uint8_t)AllocationType::None;10538break;10539case lltok::kw_notcold:10540AllocType = (uint8_t)AllocationType::NotCold;10541break;10542case lltok::kw_cold:10543AllocType = (uint8_t)AllocationType::Cold;10544break;10545case lltok::kw_hot:10546AllocType = (uint8_t)AllocationType::Hot;10547break;10548default:10549return error(Lex.getLoc(), "invalid alloc type");10550}10551Lex.Lex();10552return false;10553}1055410555/// OptionalCallsites10556/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'10557/// Callsite ::= '(' 'callee' ':' GVReference10558/// ',' 'clones' ':' '(' Version [',' Version]* ')'10559/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'10560/// Version ::= UInt3210561/// StackId ::= UInt6410562bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {10563assert(Lex.getKind() == lltok::kw_callsites);10564Lex.Lex();1056510566if (parseToken(lltok::colon, "expected ':' in callsites") ||10567parseToken(lltok::lparen, "expected '(' in callsites"))10568return true;1056910570IdToIndexMapType IdToIndexMap;10571// parse each callsite10572do {10573if (parseToken(lltok::lparen, "expected '(' in callsite") ||10574parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||10575parseToken(lltok::colon, "expected ':'"))10576return true;1057710578ValueInfo VI;10579unsigned GVId = 0;10580LocTy Loc = Lex.getLoc();10581if (!EatIfPresent(lltok::kw_null)) {10582if (parseGVReference(VI, GVId))10583return true;10584}1058510586if (parseToken(lltok::comma, "expected ',' in callsite") ||10587parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||10588parseToken(lltok::colon, "expected ':'") ||10589parseToken(lltok::lparen, "expected '(' in clones"))10590return true;1059110592SmallVector<unsigned> Clones;10593do {10594unsigned V = 0;10595if (parseUInt32(V))10596return true;10597Clones.push_back(V);10598} while (EatIfPresent(lltok::comma));1059910600if (parseToken(lltok::rparen, "expected ')' in clones") ||10601parseToken(lltok::comma, "expected ',' in callsite") ||10602parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||10603parseToken(lltok::colon, "expected ':'") ||10604parseToken(lltok::lparen, "expected '(' in stackIds"))10605return true;1060610607SmallVector<unsigned> StackIdIndices;10608do {10609uint64_t StackId = 0;10610if (parseUInt64(StackId))10611return true;10612StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));10613} while (EatIfPresent(lltok::comma));1061410615if (parseToken(lltok::rparen, "expected ')' in stackIds"))10616return true;1061710618// Keep track of the Callsites array index needing a forward reference.10619// We will save the location of the ValueInfo needing an update, but10620// can only do so once the SmallVector is finalized.10621if (VI.getRef() == FwdVIRef)10622IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));10623Callsites.push_back({VI, Clones, StackIdIndices});1062410625if (parseToken(lltok::rparen, "expected ')' in callsite"))10626return true;10627} while (EatIfPresent(lltok::comma));1062810629// Now that the Callsites vector is finalized, it is safe to save the10630// locations of any forward GV references that need updating later.10631for (auto I : IdToIndexMap) {10632auto &Infos = ForwardRefValueInfos[I.first];10633for (auto P : I.second) {10634assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&10635"Forward referenced ValueInfo expected to be empty");10636Infos.emplace_back(&Callsites[P.first].Callee, P.second);10637}10638}1063910640if (parseToken(lltok::rparen, "expected ')' in callsites"))10641return true;1064210643return false;10644}106451064610647