Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:20

0001 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 //  This file defines the parser class for .ll files.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_ASMPARSER_LLPARSER_H
0014 #define LLVM_ASMPARSER_LLPARSER_H
0015 
0016 #include "LLLexer.h"
0017 #include "llvm/ADT/StringMap.h"
0018 #include "llvm/AsmParser/NumberedValues.h"
0019 #include "llvm/AsmParser/Parser.h"
0020 #include "llvm/IR/Attributes.h"
0021 #include "llvm/IR/FMF.h"
0022 #include "llvm/IR/Instructions.h"
0023 #include "llvm/IR/ModuleSummaryIndex.h"
0024 #include "llvm/Support/ModRef.h"
0025 #include <map>
0026 #include <optional>
0027 
0028 namespace llvm {
0029   class Module;
0030   class ConstantRange;
0031   class FunctionType;
0032   class GlobalObject;
0033   class SMDiagnostic;
0034   class SMLoc;
0035   class SourceMgr;
0036   class Type;
0037   struct MaybeAlign;
0038   class Function;
0039   class Value;
0040   class BasicBlock;
0041   class Instruction;
0042   class Constant;
0043   class GlobalValue;
0044   class Comdat;
0045   class MDString;
0046   class MDNode;
0047   struct SlotMapping;
0048 
0049   /// ValID - Represents a reference of a definition of some sort with no type.
0050   /// There are several cases where we have to parse the value but where the
0051   /// type can depend on later context.  This may either be a numeric reference
0052   /// or a symbolic (%var) reference.  This is just a discriminated union.
0053   struct ValID {
0054     enum {
0055       t_LocalID,             // ID in UIntVal.
0056       t_GlobalID,            // ID in UIntVal.
0057       t_LocalName,           // Name in StrVal.
0058       t_GlobalName,          // Name in StrVal.
0059       t_APSInt,              // Value in APSIntVal.
0060       t_APFloat,             // Value in APFloatVal.
0061       t_Null,                // No value.
0062       t_Undef,               // No value.
0063       t_Zero,                // No value.
0064       t_None,                // No value.
0065       t_Poison,              // No value.
0066       t_EmptyArray,          // No value:  []
0067       t_Constant,            // Value in ConstantVal.
0068       t_ConstantSplat,       // Value in ConstantVal.
0069       t_InlineAsm,           // Value in FTy/StrVal/StrVal2/UIntVal.
0070       t_ConstantStruct,      // Value in ConstantStructElts.
0071       t_PackedConstantStruct // Value in ConstantStructElts.
0072     } Kind = t_LocalID;
0073 
0074     LLLexer::LocTy Loc;
0075     unsigned UIntVal;
0076     FunctionType *FTy = nullptr;
0077     std::string StrVal, StrVal2;
0078     APSInt APSIntVal;
0079     APFloat APFloatVal{0.0};
0080     Constant *ConstantVal;
0081     std::unique_ptr<Constant *[]> ConstantStructElts;
0082     bool NoCFI = false;
0083 
0084     ValID() = default;
0085     ValID(const ValID &RHS)
0086         : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
0087           StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
0088           APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal),
0089           NoCFI(RHS.NoCFI) {
0090       assert(!RHS.ConstantStructElts);
0091     }
0092 
0093     bool operator<(const ValID &RHS) const {
0094       assert((((Kind == t_LocalID || Kind == t_LocalName) &&
0095                (RHS.Kind == t_LocalID || RHS.Kind == t_LocalName)) ||
0096               ((Kind == t_GlobalID || Kind == t_GlobalName) &&
0097                (RHS.Kind == t_GlobalID || RHS.Kind == t_GlobalName))) &&
0098              "Comparing ValIDs of different kinds");
0099       if (Kind != RHS.Kind)
0100         return Kind < RHS.Kind;
0101       if (Kind == t_LocalID || Kind == t_GlobalID)
0102         return UIntVal < RHS.UIntVal;
0103       return StrVal < RHS.StrVal;
0104     }
0105   };
0106 
0107   class LLParser {
0108   public:
0109     typedef LLLexer::LocTy LocTy;
0110   private:
0111     LLVMContext &Context;
0112     // Lexer to determine whether to use opaque pointers or not.
0113     LLLexer OPLex;
0114     LLLexer Lex;
0115     // Module being parsed, null if we are only parsing summary index.
0116     Module *M;
0117     // Summary index being parsed, null if we are only parsing Module.
0118     ModuleSummaryIndex *Index;
0119     SlotMapping *Slots;
0120 
0121     SmallVector<Instruction*, 64> InstsWithTBAATag;
0122 
0123     /// DIAssignID metadata does not support temporary RAUW so we cannot use
0124     /// the normal metadata forward reference resolution method. Instead,
0125     /// non-temporary DIAssignID are attached to instructions (recorded here)
0126     /// then replaced later.
0127     DenseMap<MDNode *, SmallVector<Instruction *, 2>> TempDIAssignIDAttachments;
0128 
0129     // Type resolution handling data structures.  The location is set when we
0130     // have processed a use of the type but not a definition yet.
0131     StringMap<std::pair<Type*, LocTy> > NamedTypes;
0132     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
0133 
0134     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
0135     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
0136 
0137     // Global Value reference information.
0138     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
0139     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
0140     NumberedValues<GlobalValue *> NumberedVals;
0141 
0142     // Comdat forward reference information.
0143     std::map<std::string, LocTy> ForwardRefComdats;
0144 
0145     // References to blockaddress.  The key is the function ValID, the value is
0146     // a list of references to blocks in that function.
0147     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
0148     class PerFunctionState;
0149     /// Reference to per-function state to allow basic blocks to be
0150     /// forward-referenced by blockaddress instructions within the same
0151     /// function.
0152     PerFunctionState *BlockAddressPFS;
0153 
0154     // References to dso_local_equivalent. The key is the global's ValID, the
0155     // value is a placeholder value that will be replaced. Note there are two
0156     // maps for tracking ValIDs that are GlobalNames and ValIDs that are
0157     // GlobalIDs. These are needed because "operator<" doesn't discriminate
0158     // between the two.
0159     std::map<ValID, GlobalValue *> ForwardRefDSOLocalEquivalentNames;
0160     std::map<ValID, GlobalValue *> ForwardRefDSOLocalEquivalentIDs;
0161 
0162     // Attribute builder reference information.
0163     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
0164     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
0165 
0166     // Summary global value reference information.
0167     std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
0168         ForwardRefValueInfos;
0169     std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
0170         ForwardRefAliasees;
0171     std::vector<ValueInfo> NumberedValueInfos;
0172 
0173     // Summary type id reference information.
0174     std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
0175         ForwardRefTypeIds;
0176 
0177     // Map of module ID to path.
0178     std::map<unsigned, StringRef> ModuleIdMap;
0179 
0180     /// Only the llvm-as tool may set this to false to bypass
0181     /// UpgradeDebuginfo so it can generate broken bitcode.
0182     bool UpgradeDebugInfo;
0183 
0184     bool SeenNewDbgInfoFormat = false;
0185     bool SeenOldDbgInfoFormat = false;
0186 
0187     std::string SourceFileName;
0188 
0189   public:
0190     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
0191              ModuleSummaryIndex *Index, LLVMContext &Context,
0192              SlotMapping *Slots = nullptr)
0193         : Context(Context), OPLex(F, SM, Err, Context),
0194           Lex(F, SM, Err, Context), M(M), Index(Index), Slots(Slots),
0195           BlockAddressPFS(nullptr) {}
0196     bool Run(
0197         bool UpgradeDebugInfo,
0198         DataLayoutCallbackTy DataLayoutCallback = [](StringRef, StringRef) {
0199           return std::nullopt;
0200         });
0201 
0202     bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
0203 
0204     bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
0205                               const SlotMapping *Slots);
0206 
0207     bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read,
0208                                           const SlotMapping *Slots);
0209 
0210     LLVMContext &getContext() { return Context; }
0211 
0212   private:
0213     bool error(LocTy L, const Twine &Msg) { return Lex.ParseError(L, Msg); }
0214     bool tokError(const Twine &Msg) { return error(Lex.getLoc(), Msg); }
0215 
0216     bool checkValueID(LocTy L, StringRef Kind, StringRef Prefix,
0217                       unsigned NextID, unsigned ID);
0218 
0219     /// Restore the internal name and slot mappings using the mappings that
0220     /// were created at an earlier parsing stage.
0221     void restoreParsingState(const SlotMapping *Slots);
0222 
0223     /// getGlobalVal - Get a value with the specified name or ID, creating a
0224     /// forward reference record if needed.  This can return null if the value
0225     /// exists but does not have the right type.
0226     GlobalValue *getGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
0227     GlobalValue *getGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
0228 
0229     /// Get a Comdat with the specified name, creating a forward reference
0230     /// record if needed.
0231     Comdat *getComdat(const std::string &Name, LocTy Loc);
0232 
0233     // Helper Routines.
0234     bool parseToken(lltok::Kind T, const char *ErrMsg);
0235     bool EatIfPresent(lltok::Kind T) {
0236       if (Lex.getKind() != T) return false;
0237       Lex.Lex();
0238       return true;
0239     }
0240 
0241     FastMathFlags EatFastMathFlagsIfPresent() {
0242       FastMathFlags FMF;
0243       while (true)
0244         switch (Lex.getKind()) {
0245         case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
0246         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
0247         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
0248         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
0249         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
0250         case lltok::kw_contract:
0251           FMF.setAllowContract(true);
0252           Lex.Lex();
0253           continue;
0254         case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
0255         case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
0256         default: return FMF;
0257         }
0258       return FMF;
0259     }
0260 
0261     bool parseOptionalToken(lltok::Kind T, bool &Present,
0262                             LocTy *Loc = nullptr) {
0263       if (Lex.getKind() != T) {
0264         Present = false;
0265       } else {
0266         if (Loc)
0267           *Loc = Lex.getLoc();
0268         Lex.Lex();
0269         Present = true;
0270       }
0271       return false;
0272     }
0273     bool parseStringConstant(std::string &Result);
0274     bool parseUInt32(unsigned &Val);
0275     bool parseUInt32(unsigned &Val, LocTy &Loc) {
0276       Loc = Lex.getLoc();
0277       return parseUInt32(Val);
0278     }
0279     bool parseUInt64(uint64_t &Val);
0280     bool parseUInt64(uint64_t &Val, LocTy &Loc) {
0281       Loc = Lex.getLoc();
0282       return parseUInt64(Val);
0283     }
0284     bool parseFlag(unsigned &Val);
0285 
0286     bool parseStringAttribute(AttrBuilder &B);
0287 
0288     bool parseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
0289     bool parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
0290     bool parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
0291     bool parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
0292     bool parseOptionalProgramAddrSpace(unsigned &AddrSpace) {
0293       return parseOptionalAddrSpace(
0294           AddrSpace, M->getDataLayout().getProgramAddressSpace());
0295     };
0296     bool parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
0297                             bool InAttrGroup);
0298     bool parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam);
0299     bool parseOptionalParamAttrs(AttrBuilder &B) {
0300       return parseOptionalParamOrReturnAttrs(B, true);
0301     }
0302     bool parseOptionalReturnAttrs(AttrBuilder &B) {
0303       return parseOptionalParamOrReturnAttrs(B, false);
0304     }
0305     bool parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
0306                               unsigned &Visibility, unsigned &DLLStorageClass,
0307                               bool &DSOLocal);
0308     void parseOptionalDSOLocal(bool &DSOLocal);
0309     void parseOptionalVisibility(unsigned &Res);
0310     bool parseOptionalImportType(lltok::Kind Kind,
0311                                  GlobalValueSummary::ImportKind &Res);
0312     void parseOptionalDLLStorageClass(unsigned &Res);
0313     bool parseOptionalCallingConv(unsigned &CC);
0314     bool parseOptionalAlignment(MaybeAlign &Alignment,
0315                                 bool AllowParens = false);
0316     bool parseOptionalCodeModel(CodeModel::Model &model);
0317     bool parseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
0318     bool parseOptionalUWTableKind(UWTableKind &Kind);
0319     bool parseAllocKind(AllocFnKind &Kind);
0320     std::optional<MemoryEffects> parseMemoryAttr();
0321     unsigned parseNoFPClassAttr();
0322     bool parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
0323                                AtomicOrdering &Ordering);
0324     bool parseScope(SyncScope::ID &SSID);
0325     bool parseOrdering(AtomicOrdering &Ordering);
0326     bool parseOptionalStackAlignment(unsigned &Alignment);
0327     bool parseOptionalCommaAlign(MaybeAlign &Alignment, bool &AteExtraComma);
0328     bool parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
0329                                      bool &AteExtraComma);
0330     bool parseAllocSizeArguments(unsigned &BaseSizeArg,
0331                                  std::optional<unsigned> &HowManyArg);
0332     bool parseVScaleRangeArguments(unsigned &MinValue, unsigned &MaxValue);
0333     bool parseIndexList(SmallVectorImpl<unsigned> &Indices,
0334                         bool &AteExtraComma);
0335     bool parseIndexList(SmallVectorImpl<unsigned> &Indices) {
0336       bool AteExtraComma;
0337       if (parseIndexList(Indices, AteExtraComma))
0338         return true;
0339       if (AteExtraComma)
0340         return tokError("expected index");
0341       return false;
0342     }
0343 
0344     // Top-Level Entities
0345     bool parseTopLevelEntities();
0346     void dropUnknownMetadataReferences();
0347     bool validateEndOfModule(bool UpgradeDebugInfo);
0348     bool validateEndOfIndex();
0349     bool parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback);
0350     bool parseTargetDefinition(std::string &TentativeDLStr, LocTy &DLStrLoc);
0351     bool parseModuleAsm();
0352     bool parseSourceFileName();
0353     bool parseUnnamedType();
0354     bool parseNamedType();
0355     bool parseDeclare();
0356     bool parseDefine();
0357 
0358     bool parseGlobalType(bool &IsConstant);
0359     bool parseUnnamedGlobal();
0360     bool parseNamedGlobal();
0361     bool parseGlobal(const std::string &Name, unsigned NameID, LocTy NameLoc,
0362                      unsigned Linkage, bool HasLinkage, unsigned Visibility,
0363                      unsigned DLLStorageClass, bool DSOLocal,
0364                      GlobalVariable::ThreadLocalMode TLM,
0365                      GlobalVariable::UnnamedAddr UnnamedAddr);
0366     bool parseAliasOrIFunc(const std::string &Name, unsigned NameID,
0367                            LocTy NameLoc, unsigned L, unsigned Visibility,
0368                            unsigned DLLStorageClass, bool DSOLocal,
0369                            GlobalVariable::ThreadLocalMode TLM,
0370                            GlobalVariable::UnnamedAddr UnnamedAddr);
0371     bool parseComdat();
0372     bool parseStandaloneMetadata();
0373     bool parseNamedMetadata();
0374     bool parseMDString(MDString *&Result);
0375     bool parseMDNodeID(MDNode *&Result);
0376     bool parseUnnamedAttrGrp();
0377     bool parseFnAttributeValuePairs(AttrBuilder &B,
0378                                     std::vector<unsigned> &FwdRefAttrGrps,
0379                                     bool inAttrGrp, LocTy &BuiltinLoc);
0380     bool parseRangeAttr(AttrBuilder &B);
0381     bool parseInitializesAttr(AttrBuilder &B);
0382     bool parseCapturesAttr(AttrBuilder &B);
0383     bool parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
0384                                Attribute::AttrKind AttrKind);
0385 
0386     // Module Summary Index Parsing.
0387     bool skipModuleSummaryEntry();
0388     bool parseSummaryEntry();
0389     bool parseModuleEntry(unsigned ID);
0390     bool parseModuleReference(StringRef &ModulePath);
0391     bool parseGVReference(ValueInfo &VI, unsigned &GVId);
0392     bool parseSummaryIndexFlags();
0393     bool parseBlockCount();
0394     bool parseGVEntry(unsigned ID);
0395     bool parseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
0396     bool parseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
0397     bool parseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
0398     bool parseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
0399     bool parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
0400     bool parseOptionalFFlags(FunctionSummary::FFlags &FFlags);
0401     bool parseOptionalCalls(SmallVectorImpl<FunctionSummary::EdgeTy> &Calls);
0402     bool parseHotness(CalleeInfo::HotnessType &Hotness);
0403     bool parseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
0404     bool parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
0405     bool parseVFuncIdList(lltok::Kind Kind,
0406                           std::vector<FunctionSummary::VFuncId> &VFuncIdList);
0407     bool parseConstVCallList(
0408         lltok::Kind Kind,
0409         std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
0410     using IdToIndexMapType =
0411         std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
0412     bool parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
0413                          IdToIndexMapType &IdToIndexMap, unsigned Index);
0414     bool parseVFuncId(FunctionSummary::VFuncId &VFuncId,
0415                       IdToIndexMapType &IdToIndexMap, unsigned Index);
0416     bool parseOptionalVTableFuncs(VTableFuncList &VTableFuncs);
0417     bool parseOptionalParamAccesses(
0418         std::vector<FunctionSummary::ParamAccess> &Params);
0419     bool parseParamNo(uint64_t &ParamNo);
0420     using IdLocListType = std::vector<std::pair<unsigned, LocTy>>;
0421     bool parseParamAccess(FunctionSummary::ParamAccess &Param,
0422                           IdLocListType &IdLocList);
0423     bool parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
0424                               IdLocListType &IdLocList);
0425     bool parseParamAccessOffset(ConstantRange &Range);
0426     bool parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs);
0427     bool parseTypeIdEntry(unsigned ID);
0428     bool parseTypeIdSummary(TypeIdSummary &TIS);
0429     bool parseTypeIdCompatibleVtableEntry(unsigned ID);
0430     bool parseTypeTestResolution(TypeTestResolution &TTRes);
0431     bool parseOptionalWpdResolutions(
0432         std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
0433     bool parseWpdRes(WholeProgramDevirtResolution &WPDRes);
0434     bool parseOptionalResByArg(
0435         std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
0436             &ResByArg);
0437     bool parseArgs(std::vector<uint64_t> &Args);
0438     bool addGlobalValueToIndex(std::string Name, GlobalValue::GUID,
0439                                GlobalValue::LinkageTypes Linkage, unsigned ID,
0440                                std::unique_ptr<GlobalValueSummary> Summary,
0441                                LocTy Loc);
0442     bool parseOptionalAllocs(std::vector<AllocInfo> &Allocs);
0443     bool parseMemProfs(std::vector<MIBInfo> &MIBs);
0444     bool parseAllocType(uint8_t &AllocType);
0445     bool parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites);
0446 
0447     // Type Parsing.
0448     bool parseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
0449     bool parseType(Type *&Result, bool AllowVoid = false) {
0450       return parseType(Result, "expected type", AllowVoid);
0451     }
0452     bool parseType(Type *&Result, const Twine &Msg, LocTy &Loc,
0453                    bool AllowVoid = false) {
0454       Loc = Lex.getLoc();
0455       return parseType(Result, Msg, AllowVoid);
0456     }
0457     bool parseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
0458       Loc = Lex.getLoc();
0459       return parseType(Result, AllowVoid);
0460     }
0461     bool parseAnonStructType(Type *&Result, bool Packed);
0462     bool parseStructBody(SmallVectorImpl<Type *> &Body);
0463     bool parseStructDefinition(SMLoc TypeLoc, StringRef Name,
0464                                std::pair<Type *, LocTy> &Entry,
0465                                Type *&ResultTy);
0466 
0467     bool parseArrayVectorType(Type *&Result, bool IsVector);
0468     bool parseFunctionType(Type *&Result);
0469     bool parseTargetExtType(Type *&Result);
0470 
0471     // Function Semantic Analysis.
0472     class PerFunctionState {
0473       LLParser &P;
0474       Function &F;
0475       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
0476       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
0477       NumberedValues<Value *> NumberedVals;
0478 
0479       /// FunctionNumber - If this is an unnamed function, this is the slot
0480       /// number of it, otherwise it is -1.
0481       int FunctionNumber;
0482 
0483     public:
0484       PerFunctionState(LLParser &p, Function &f, int functionNumber,
0485                        ArrayRef<unsigned> UnnamedArgNums);
0486       ~PerFunctionState();
0487 
0488       Function &getFunction() const { return F; }
0489 
0490       bool finishFunction();
0491 
0492       /// GetVal - Get a value with the specified name or ID, creating a
0493       /// forward reference record if needed.  This can return null if the value
0494       /// exists but does not have the right type.
0495       Value *getVal(const std::string &Name, Type *Ty, LocTy Loc);
0496       Value *getVal(unsigned ID, Type *Ty, LocTy Loc);
0497 
0498       /// setInstName - After an instruction is parsed and inserted into its
0499       /// basic block, this installs its name.
0500       bool setInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
0501                        Instruction *Inst);
0502 
0503       /// GetBB - Get a basic block with the specified name or ID, creating a
0504       /// forward reference record if needed.  This can return null if the value
0505       /// is not a BasicBlock.
0506       BasicBlock *getBB(const std::string &Name, LocTy Loc);
0507       BasicBlock *getBB(unsigned ID, LocTy Loc);
0508 
0509       /// DefineBB - Define the specified basic block, which is either named or
0510       /// unnamed.  If there is an error, this returns null otherwise it returns
0511       /// the block being defined.
0512       BasicBlock *defineBB(const std::string &Name, int NameID, LocTy Loc);
0513 
0514       bool resolveForwardRefBlockAddresses();
0515     };
0516 
0517     bool convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
0518                              PerFunctionState *PFS);
0519 
0520     Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
0521                                   Value *Val);
0522 
0523     bool parseConstantValue(Type *Ty, Constant *&C);
0524     bool parseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
0525     bool parseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
0526       return parseValue(Ty, V, &PFS);
0527     }
0528 
0529     bool parseValue(Type *Ty, Value *&V, LocTy &Loc, PerFunctionState &PFS) {
0530       Loc = Lex.getLoc();
0531       return parseValue(Ty, V, &PFS);
0532     }
0533 
0534     bool parseTypeAndValue(Value *&V, PerFunctionState *PFS);
0535     bool parseTypeAndValue(Value *&V, PerFunctionState &PFS) {
0536       return parseTypeAndValue(V, &PFS);
0537     }
0538     bool parseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
0539       Loc = Lex.getLoc();
0540       return parseTypeAndValue(V, PFS);
0541     }
0542     bool parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
0543                                 PerFunctionState &PFS);
0544     bool parseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
0545       LocTy Loc;
0546       return parseTypeAndBasicBlock(BB, Loc, PFS);
0547     }
0548 
0549     struct ParamInfo {
0550       LocTy Loc;
0551       Value *V;
0552       AttributeSet Attrs;
0553       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
0554           : Loc(loc), V(v), Attrs(attrs) {}
0555     };
0556     bool parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
0557                             PerFunctionState &PFS, bool IsMustTailCall = false,
0558                             bool InVarArgsFunc = false);
0559 
0560     bool
0561     parseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
0562                                 PerFunctionState &PFS);
0563 
0564     bool parseExceptionArgs(SmallVectorImpl<Value *> &Args,
0565                             PerFunctionState &PFS);
0566 
0567     bool resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
0568                              FunctionType *&FuncTy);
0569 
0570     // Constant Parsing.
0571     bool parseValID(ValID &ID, PerFunctionState *PFS,
0572                     Type *ExpectedTy = nullptr);
0573     bool parseGlobalValue(Type *Ty, Constant *&C);
0574     bool parseGlobalTypeAndValue(Constant *&V);
0575     bool parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
0576     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
0577     bool parseSanitizer(GlobalVariable *GV);
0578     bool parseMetadataAsValue(Value *&V, PerFunctionState &PFS);
0579     bool parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
0580                               PerFunctionState *PFS);
0581     bool parseDIArgList(Metadata *&MD, PerFunctionState *PFS);
0582     bool parseMetadata(Metadata *&MD, PerFunctionState *PFS);
0583     bool parseMDTuple(MDNode *&MD, bool IsDistinct = false);
0584     bool parseMDNode(MDNode *&N);
0585     bool parseMDNodeTail(MDNode *&N);
0586     bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
0587     bool parseMetadataAttachment(unsigned &Kind, MDNode *&MD);
0588     bool parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS);
0589     bool parseInstructionMetadata(Instruction &Inst);
0590     bool parseGlobalObjectMetadataAttachment(GlobalObject &GO);
0591     bool parseOptionalFunctionMetadata(Function &F);
0592 
0593     template <class FieldTy>
0594     bool parseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
0595     template <class FieldTy> bool parseMDField(StringRef Name, FieldTy &Result);
0596     template <class ParserTy> bool parseMDFieldsImplBody(ParserTy ParseField);
0597     template <class ParserTy>
0598     bool parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc);
0599     bool parseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
0600     bool parseDIExpressionBody(MDNode *&Result, bool IsDistinct);
0601 
0602 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
0603   bool parse##CLASS(MDNode *&Result, bool IsDistinct);
0604 #include "llvm/IR/Metadata.def"
0605 
0606     // Function Parsing.
0607     struct ArgInfo {
0608       LocTy Loc;
0609       Type *Ty;
0610       AttributeSet Attrs;
0611       std::string Name;
0612       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
0613           : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
0614     };
0615     bool parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
0616                            SmallVectorImpl<unsigned> &UnnamedArgNums,
0617                            bool &IsVarArg);
0618     bool parseFunctionHeader(Function *&Fn, bool IsDefine,
0619                              unsigned &FunctionNumber,
0620                              SmallVectorImpl<unsigned> &UnnamedArgNums);
0621     bool parseFunctionBody(Function &Fn, unsigned FunctionNumber,
0622                            ArrayRef<unsigned> UnnamedArgNums);
0623     bool parseBasicBlock(PerFunctionState &PFS);
0624 
0625     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
0626 
0627     // Instruction Parsing.  Each instruction parsing routine can return with a
0628     // normal result, an error result, or return having eaten an extra comma.
0629     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
0630     int parseInstruction(Instruction *&Inst, BasicBlock *BB,
0631                          PerFunctionState &PFS);
0632     bool parseCmpPredicate(unsigned &P, unsigned Opc);
0633 
0634     bool parseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
0635     bool parseBr(Instruction *&Inst, PerFunctionState &PFS);
0636     bool parseSwitch(Instruction *&Inst, PerFunctionState &PFS);
0637     bool parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
0638     bool parseInvoke(Instruction *&Inst, PerFunctionState &PFS);
0639     bool parseResume(Instruction *&Inst, PerFunctionState &PFS);
0640     bool parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
0641     bool parseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
0642     bool parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
0643     bool parseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
0644     bool parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
0645     bool parseCallBr(Instruction *&Inst, PerFunctionState &PFS);
0646 
0647     bool parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
0648                       bool IsFP);
0649     bool parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
0650                          unsigned Opc, bool IsFP);
0651     bool parseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
0652     bool parseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
0653     bool parseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
0654     bool parseSelect(Instruction *&Inst, PerFunctionState &PFS);
0655     bool parseVAArg(Instruction *&Inst, PerFunctionState &PFS);
0656     bool parseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
0657     bool parseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
0658     bool parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
0659     int parsePHI(Instruction *&Inst, PerFunctionState &PFS);
0660     bool parseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
0661     bool parseCall(Instruction *&Inst, PerFunctionState &PFS,
0662                    CallInst::TailCallKind TCK);
0663     int parseAlloc(Instruction *&Inst, PerFunctionState &PFS);
0664     int parseLoad(Instruction *&Inst, PerFunctionState &PFS);
0665     int parseStore(Instruction *&Inst, PerFunctionState &PFS);
0666     int parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
0667     int parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
0668     int parseFence(Instruction *&Inst, PerFunctionState &PFS);
0669     int parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
0670     int parseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
0671     int parseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
0672     bool parseFreeze(Instruction *&I, PerFunctionState &PFS);
0673 
0674     // Use-list order directives.
0675     bool parseUseListOrder(PerFunctionState *PFS = nullptr);
0676     bool parseUseListOrderBB();
0677     bool parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
0678     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
0679   };
0680 } // End llvm namespace
0681 
0682 #endif