1 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_ASMPARSER_LLPARSER_H
14 #define LLVM_ASMPARSER_LLPARSER_H
15 
16 #include "LLLexer.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/AsmParser/Parser.h"
19 #include "llvm/IR/Attributes.h"
20 #include "llvm/IR/FMF.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/ModuleSummaryIndex.h"
23 #include "llvm/Support/ModRef.h"
24 #include <map>
25 #include <optional>
26 
27 namespace llvm {
28   class Module;
29   class ConstantRange;
30   class FunctionType;
31   class GlobalObject;
32   class SMDiagnostic;
33   class SMLoc;
34   class SourceMgr;
35   class Type;
36   struct MaybeAlign;
37   class Function;
38   class Value;
39   class BasicBlock;
40   class Instruction;
41   class Constant;
42   class GlobalValue;
43   class Comdat;
44   class MDString;
45   class MDNode;
46   struct SlotMapping;
47 
48   /// ValID - Represents a reference of a definition of some sort with no type.
49   /// There are several cases where we have to parse the value but where the
50   /// type can depend on later context.  This may either be a numeric reference
51   /// or a symbolic (%var) reference.  This is just a discriminated union.
52   struct ValID {
53     enum {
54       t_LocalID, t_GlobalID,           // ID in UIntVal.
55       t_LocalName, t_GlobalName,       // Name in StrVal.
56       t_APSInt, t_APFloat,             // Value in APSIntVal/APFloatVal.
57       t_Null, t_Undef, t_Zero, t_None, t_Poison, // No value.
58       t_EmptyArray,                    // No value:  []
59       t_Constant,                      // Value in ConstantVal.
60       t_InlineAsm,                     // Value in FTy/StrVal/StrVal2/UIntVal.
61       t_ConstantStruct,                // Value in ConstantStructElts.
62       t_PackedConstantStruct           // Value in ConstantStructElts.
63     } Kind = t_LocalID;
64 
65     LLLexer::LocTy Loc;
66     unsigned UIntVal;
67     FunctionType *FTy = nullptr;
68     std::string StrVal, StrVal2;
69     APSInt APSIntVal;
70     APFloat APFloatVal{0.0};
71     Constant *ConstantVal;
72     std::unique_ptr<Constant *[]> ConstantStructElts;
73     bool NoCFI = false;
74 
75     ValID() = default;
76     ValID(const ValID &RHS)
77         : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
78           StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
79           APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal),
80           NoCFI(RHS.NoCFI) {
81       assert(!RHS.ConstantStructElts);
82     }
83 
84     bool operator<(const ValID &RHS) const {
85       assert(Kind == RHS.Kind && "Comparing ValIDs of different kinds");
86       if (Kind == t_LocalID || Kind == t_GlobalID)
87         return UIntVal < RHS.UIntVal;
88       assert((Kind == t_LocalName || Kind == t_GlobalName ||
89               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
90              "Ordering not defined for this ValID kind yet");
91       return StrVal < RHS.StrVal;
92     }
93   };
94 
95   class LLParser {
96   public:
97     typedef LLLexer::LocTy LocTy;
98   private:
99     LLVMContext &Context;
100     // Lexer to determine whether to use opaque pointers or not.
101     LLLexer OPLex;
102     LLLexer Lex;
103     // Module being parsed, null if we are only parsing summary index.
104     Module *M;
105     // Summary index being parsed, null if we are only parsing Module.
106     ModuleSummaryIndex *Index;
107     SlotMapping *Slots;
108 
109     SmallVector<Instruction*, 64> InstsWithTBAATag;
110 
111     /// DIAssignID metadata does not support temporary RAUW so we cannot use
112     /// the normal metadata forward reference resolution method. Instead,
113     /// non-temporary DIAssignID are attached to instructions (recorded here)
114     /// then replaced later.
115     DenseMap<MDNode *, SmallVector<Instruction *, 2>> TempDIAssignIDAttachments;
116 
117     // Type resolution handling data structures.  The location is set when we
118     // have processed a use of the type but not a definition yet.
119     StringMap<std::pair<Type*, LocTy> > NamedTypes;
120     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
121 
122     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
123     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
124 
125     // Global Value reference information.
126     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
127     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
128     std::vector<GlobalValue*> NumberedVals;
129 
130     // Comdat forward reference information.
131     std::map<std::string, LocTy> ForwardRefComdats;
132 
133     // References to blockaddress.  The key is the function ValID, the value is
134     // a list of references to blocks in that function.
135     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
136     class PerFunctionState;
137     /// Reference to per-function state to allow basic blocks to be
138     /// forward-referenced by blockaddress instructions within the same
139     /// function.
140     PerFunctionState *BlockAddressPFS;
141 
142     // References to dso_local_equivalent. The key is the global's ValID, the
143     // value is a placeholder value that will be replaced. Note there are two
144     // maps for tracking ValIDs that are GlobalNames and ValIDs that are
145     // GlobalIDs. These are needed because "operator<" doesn't discriminate
146     // between the two.
147     std::map<ValID, GlobalValue *> ForwardRefDSOLocalEquivalentNames;
148     std::map<ValID, GlobalValue *> ForwardRefDSOLocalEquivalentIDs;
149 
150     // Attribute builder reference information.
151     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
152     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
153 
154     // Summary global value reference information.
155     std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
156         ForwardRefValueInfos;
157     std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
158         ForwardRefAliasees;
159     std::vector<ValueInfo> NumberedValueInfos;
160 
161     // Summary type id reference information.
162     std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
163         ForwardRefTypeIds;
164 
165     // Map of module ID to path.
166     std::map<unsigned, StringRef> ModuleIdMap;
167 
168     /// Only the llvm-as tool may set this to false to bypass
169     /// UpgradeDebuginfo so it can generate broken bitcode.
170     bool UpgradeDebugInfo;
171 
172     std::string SourceFileName;
173 
174   public:
175     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
176              ModuleSummaryIndex *Index, LLVMContext &Context,
177              SlotMapping *Slots = nullptr)
178         : Context(Context), OPLex(F, SM, Err, Context),
179           Lex(F, SM, Err, Context), M(M), Index(Index), Slots(Slots),
180           BlockAddressPFS(nullptr) {}
181     bool Run(
182         bool UpgradeDebugInfo,
183         DataLayoutCallbackTy DataLayoutCallback = [](StringRef, StringRef) {
184           return std::nullopt;
185         });
186 
187     bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
188 
189     bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
190                               const SlotMapping *Slots);
191 
192     LLVMContext &getContext() { return Context; }
193 
194   private:
195     bool error(LocTy L, const Twine &Msg) const { return Lex.Error(L, Msg); }
196     bool tokError(const Twine &Msg) const { return error(Lex.getLoc(), Msg); }
197 
198     /// Restore the internal name and slot mappings using the mappings that
199     /// were created at an earlier parsing stage.
200     void restoreParsingState(const SlotMapping *Slots);
201 
202     /// getGlobalVal - Get a value with the specified name or ID, creating a
203     /// forward reference record if needed.  This can return null if the value
204     /// exists but does not have the right type.
205     GlobalValue *getGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
206     GlobalValue *getGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
207 
208     /// Get a Comdat with the specified name, creating a forward reference
209     /// record if needed.
210     Comdat *getComdat(const std::string &Name, LocTy Loc);
211 
212     // Helper Routines.
213     bool parseToken(lltok::Kind T, const char *ErrMsg);
214     bool EatIfPresent(lltok::Kind T) {
215       if (Lex.getKind() != T) return false;
216       Lex.Lex();
217       return true;
218     }
219 
220     FastMathFlags EatFastMathFlagsIfPresent() {
221       FastMathFlags FMF;
222       while (true)
223         switch (Lex.getKind()) {
224         case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
225         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
226         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
227         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
228         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
229         case lltok::kw_contract:
230           FMF.setAllowContract(true);
231           Lex.Lex();
232           continue;
233         case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
234         case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
235         default: return FMF;
236         }
237       return FMF;
238     }
239 
240     bool parseOptionalToken(lltok::Kind T, bool &Present,
241                             LocTy *Loc = nullptr) {
242       if (Lex.getKind() != T) {
243         Present = false;
244       } else {
245         if (Loc)
246           *Loc = Lex.getLoc();
247         Lex.Lex();
248         Present = true;
249       }
250       return false;
251     }
252     bool parseStringConstant(std::string &Result);
253     bool parseUInt32(unsigned &Val);
254     bool parseUInt32(unsigned &Val, LocTy &Loc) {
255       Loc = Lex.getLoc();
256       return parseUInt32(Val);
257     }
258     bool parseUInt64(uint64_t &Val);
259     bool parseUInt64(uint64_t &Val, LocTy &Loc) {
260       Loc = Lex.getLoc();
261       return parseUInt64(Val);
262     }
263     bool parseFlag(unsigned &Val);
264 
265     bool parseStringAttribute(AttrBuilder &B);
266 
267     bool parseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
268     bool parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
269     bool parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
270     bool parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
271     bool parseOptionalProgramAddrSpace(unsigned &AddrSpace) {
272       return parseOptionalAddrSpace(
273           AddrSpace, M->getDataLayout().getProgramAddressSpace());
274     };
275     bool parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
276                             bool InAttrGroup);
277     bool parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam);
278     bool parseOptionalParamAttrs(AttrBuilder &B) {
279       return parseOptionalParamOrReturnAttrs(B, true);
280     }
281     bool parseOptionalReturnAttrs(AttrBuilder &B) {
282       return parseOptionalParamOrReturnAttrs(B, false);
283     }
284     bool parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
285                               unsigned &Visibility, unsigned &DLLStorageClass,
286                               bool &DSOLocal);
287     void parseOptionalDSOLocal(bool &DSOLocal);
288     void parseOptionalVisibility(unsigned &Res);
289     void parseOptionalDLLStorageClass(unsigned &Res);
290     bool parseOptionalCallingConv(unsigned &CC);
291     bool parseOptionalAlignment(MaybeAlign &Alignment,
292                                 bool AllowParens = false);
293     bool parseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
294     bool parseOptionalUWTableKind(UWTableKind &Kind);
295     bool parseAllocKind(AllocFnKind &Kind);
296     std::optional<MemoryEffects> parseMemoryAttr();
297     unsigned parseNoFPClassAttr();
298     bool parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
299                                AtomicOrdering &Ordering);
300     bool parseScope(SyncScope::ID &SSID);
301     bool parseOrdering(AtomicOrdering &Ordering);
302     bool parseOptionalStackAlignment(unsigned &Alignment);
303     bool parseOptionalCommaAlign(MaybeAlign &Alignment, bool &AteExtraComma);
304     bool parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
305                                      bool &AteExtraComma);
306     bool parseAllocSizeArguments(unsigned &BaseSizeArg,
307                                  std::optional<unsigned> &HowManyArg);
308     bool parseVScaleRangeArguments(unsigned &MinValue, unsigned &MaxValue);
309     bool parseIndexList(SmallVectorImpl<unsigned> &Indices,
310                         bool &AteExtraComma);
311     bool parseIndexList(SmallVectorImpl<unsigned> &Indices) {
312       bool AteExtraComma;
313       if (parseIndexList(Indices, AteExtraComma))
314         return true;
315       if (AteExtraComma)
316         return tokError("expected index");
317       return false;
318     }
319 
320     // Top-Level Entities
321     bool parseTopLevelEntities();
322     bool validateEndOfModule(bool UpgradeDebugInfo);
323     bool validateEndOfIndex();
324     bool parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback);
325     bool parseTargetDefinition(std::string &TentativeDLStr, LocTy &DLStrLoc);
326     bool parseModuleAsm();
327     bool parseSourceFileName();
328     bool parseUnnamedType();
329     bool parseNamedType();
330     bool parseDeclare();
331     bool parseDefine();
332 
333     bool parseGlobalType(bool &IsConstant);
334     bool parseUnnamedGlobal();
335     bool parseNamedGlobal();
336     bool parseGlobal(const std::string &Name, LocTy NameLoc, unsigned Linkage,
337                      bool HasLinkage, unsigned Visibility,
338                      unsigned DLLStorageClass, bool DSOLocal,
339                      GlobalVariable::ThreadLocalMode TLM,
340                      GlobalVariable::UnnamedAddr UnnamedAddr);
341     bool parseAliasOrIFunc(const std::string &Name, LocTy NameLoc, unsigned L,
342                            unsigned Visibility, unsigned DLLStorageClass,
343                            bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
344                            GlobalVariable::UnnamedAddr UnnamedAddr);
345     bool parseComdat();
346     bool parseStandaloneMetadata();
347     bool parseNamedMetadata();
348     bool parseMDString(MDString *&Result);
349     bool parseMDNodeID(MDNode *&Result);
350     bool parseUnnamedAttrGrp();
351     bool parseFnAttributeValuePairs(AttrBuilder &B,
352                                     std::vector<unsigned> &FwdRefAttrGrps,
353                                     bool inAttrGrp, LocTy &BuiltinLoc);
354     bool parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
355                                Attribute::AttrKind AttrKind);
356 
357     // Module Summary Index Parsing.
358     bool skipModuleSummaryEntry();
359     bool parseSummaryEntry();
360     bool parseModuleEntry(unsigned ID);
361     bool parseModuleReference(StringRef &ModulePath);
362     bool parseGVReference(ValueInfo &VI, unsigned &GVId);
363     bool parseSummaryIndexFlags();
364     bool parseBlockCount();
365     bool parseGVEntry(unsigned ID);
366     bool parseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
367     bool parseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
368     bool parseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
369     bool parseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
370     bool parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
371     bool parseOptionalFFlags(FunctionSummary::FFlags &FFlags);
372     bool parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls);
373     bool parseHotness(CalleeInfo::HotnessType &Hotness);
374     bool parseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
375     bool parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
376     bool parseVFuncIdList(lltok::Kind Kind,
377                           std::vector<FunctionSummary::VFuncId> &VFuncIdList);
378     bool parseConstVCallList(
379         lltok::Kind Kind,
380         std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
381     using IdToIndexMapType =
382         std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
383     bool parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
384                          IdToIndexMapType &IdToIndexMap, unsigned Index);
385     bool parseVFuncId(FunctionSummary::VFuncId &VFuncId,
386                       IdToIndexMapType &IdToIndexMap, unsigned Index);
387     bool parseOptionalVTableFuncs(VTableFuncList &VTableFuncs);
388     bool parseOptionalParamAccesses(
389         std::vector<FunctionSummary::ParamAccess> &Params);
390     bool parseParamNo(uint64_t &ParamNo);
391     using IdLocListType = std::vector<std::pair<unsigned, LocTy>>;
392     bool parseParamAccess(FunctionSummary::ParamAccess &Param,
393                           IdLocListType &IdLocList);
394     bool parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
395                               IdLocListType &IdLocList);
396     bool parseParamAccessOffset(ConstantRange &Range);
397     bool parseOptionalRefs(std::vector<ValueInfo> &Refs);
398     bool parseTypeIdEntry(unsigned ID);
399     bool parseTypeIdSummary(TypeIdSummary &TIS);
400     bool parseTypeIdCompatibleVtableEntry(unsigned ID);
401     bool parseTypeTestResolution(TypeTestResolution &TTRes);
402     bool parseOptionalWpdResolutions(
403         std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
404     bool parseWpdRes(WholeProgramDevirtResolution &WPDRes);
405     bool parseOptionalResByArg(
406         std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
407             &ResByArg);
408     bool parseArgs(std::vector<uint64_t> &Args);
409     void addGlobalValueToIndex(std::string Name, GlobalValue::GUID,
410                                GlobalValue::LinkageTypes Linkage, unsigned ID,
411                                std::unique_ptr<GlobalValueSummary> Summary);
412     bool parseOptionalAllocs(std::vector<AllocInfo> &Allocs);
413     bool parseMemProfs(std::vector<MIBInfo> &MIBs);
414     bool parseAllocType(uint8_t &AllocType);
415     bool parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites);
416 
417     // Type Parsing.
418     bool parseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
419     bool parseType(Type *&Result, bool AllowVoid = false) {
420       return parseType(Result, "expected type", AllowVoid);
421     }
422     bool parseType(Type *&Result, const Twine &Msg, LocTy &Loc,
423                    bool AllowVoid = false) {
424       Loc = Lex.getLoc();
425       return parseType(Result, Msg, AllowVoid);
426     }
427     bool parseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
428       Loc = Lex.getLoc();
429       return parseType(Result, AllowVoid);
430     }
431     bool parseAnonStructType(Type *&Result, bool Packed);
432     bool parseStructBody(SmallVectorImpl<Type *> &Body);
433     bool parseStructDefinition(SMLoc TypeLoc, StringRef Name,
434                                std::pair<Type *, LocTy> &Entry,
435                                Type *&ResultTy);
436 
437     bool parseArrayVectorType(Type *&Result, bool IsVector);
438     bool parseFunctionType(Type *&Result);
439     bool parseTargetExtType(Type *&Result);
440 
441     // Function Semantic Analysis.
442     class PerFunctionState {
443       LLParser &P;
444       Function &F;
445       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
446       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
447       std::vector<Value*> NumberedVals;
448 
449       /// FunctionNumber - If this is an unnamed function, this is the slot
450       /// number of it, otherwise it is -1.
451       int FunctionNumber;
452     public:
453       PerFunctionState(LLParser &p, Function &f, int functionNumber);
454       ~PerFunctionState();
455 
456       Function &getFunction() const { return F; }
457 
458       bool finishFunction();
459 
460       /// GetVal - Get a value with the specified name or ID, creating a
461       /// forward reference record if needed.  This can return null if the value
462       /// exists but does not have the right type.
463       Value *getVal(const std::string &Name, Type *Ty, LocTy Loc);
464       Value *getVal(unsigned ID, Type *Ty, LocTy Loc);
465 
466       /// setInstName - After an instruction is parsed and inserted into its
467       /// basic block, this installs its name.
468       bool setInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
469                        Instruction *Inst);
470 
471       /// GetBB - Get a basic block with the specified name or ID, creating a
472       /// forward reference record if needed.  This can return null if the value
473       /// is not a BasicBlock.
474       BasicBlock *getBB(const std::string &Name, LocTy Loc);
475       BasicBlock *getBB(unsigned ID, LocTy Loc);
476 
477       /// DefineBB - Define the specified basic block, which is either named or
478       /// unnamed.  If there is an error, this returns null otherwise it returns
479       /// the block being defined.
480       BasicBlock *defineBB(const std::string &Name, int NameID, LocTy Loc);
481 
482       bool resolveForwardRefBlockAddresses();
483     };
484 
485     bool convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
486                              PerFunctionState *PFS);
487 
488     Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
489                                   Value *Val);
490 
491     bool parseConstantValue(Type *Ty, Constant *&C);
492     bool parseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
493     bool parseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
494       return parseValue(Ty, V, &PFS);
495     }
496 
497     bool parseValue(Type *Ty, Value *&V, LocTy &Loc, PerFunctionState &PFS) {
498       Loc = Lex.getLoc();
499       return parseValue(Ty, V, &PFS);
500     }
501 
502     bool parseTypeAndValue(Value *&V, PerFunctionState *PFS);
503     bool parseTypeAndValue(Value *&V, PerFunctionState &PFS) {
504       return parseTypeAndValue(V, &PFS);
505     }
506     bool parseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
507       Loc = Lex.getLoc();
508       return parseTypeAndValue(V, PFS);
509     }
510     bool parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
511                                 PerFunctionState &PFS);
512     bool parseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
513       LocTy Loc;
514       return parseTypeAndBasicBlock(BB, Loc, PFS);
515     }
516 
517     struct ParamInfo {
518       LocTy Loc;
519       Value *V;
520       AttributeSet Attrs;
521       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
522           : Loc(loc), V(v), Attrs(attrs) {}
523     };
524     bool parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
525                             PerFunctionState &PFS, bool IsMustTailCall = false,
526                             bool InVarArgsFunc = false);
527 
528     bool
529     parseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
530                                 PerFunctionState &PFS);
531 
532     bool parseExceptionArgs(SmallVectorImpl<Value *> &Args,
533                             PerFunctionState &PFS);
534 
535     bool resolveFunctionType(Type *RetType,
536                              const SmallVector<ParamInfo, 16> &ArgList,
537                              FunctionType *&FuncTy);
538 
539     // Constant Parsing.
540     bool parseValID(ValID &ID, PerFunctionState *PFS,
541                     Type *ExpectedTy = nullptr);
542     bool parseGlobalValue(Type *Ty, Constant *&C);
543     bool parseGlobalTypeAndValue(Constant *&V);
544     bool parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
545                                 std::optional<unsigned> *InRangeOp = nullptr);
546     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
547     bool parseSanitizer(GlobalVariable *GV);
548     bool parseMetadataAsValue(Value *&V, PerFunctionState &PFS);
549     bool parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
550                               PerFunctionState *PFS);
551     bool parseMetadata(Metadata *&MD, PerFunctionState *PFS);
552     bool parseMDTuple(MDNode *&MD, bool IsDistinct = false);
553     bool parseMDNode(MDNode *&N);
554     bool parseMDNodeTail(MDNode *&N);
555     bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
556     bool parseMetadataAttachment(unsigned &Kind, MDNode *&MD);
557     bool parseInstructionMetadata(Instruction &Inst);
558     bool parseGlobalObjectMetadataAttachment(GlobalObject &GO);
559     bool parseOptionalFunctionMetadata(Function &F);
560 
561     template <class FieldTy>
562     bool parseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
563     template <class FieldTy> bool parseMDField(StringRef Name, FieldTy &Result);
564     template <class ParserTy> bool parseMDFieldsImplBody(ParserTy ParseField);
565     template <class ParserTy>
566     bool parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc);
567     bool parseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
568 
569 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
570   bool parse##CLASS(MDNode *&Result, bool IsDistinct);
571 #include "llvm/IR/Metadata.def"
572     bool parseDIArgList(MDNode *&Result, bool IsDistinct,
573                         PerFunctionState *PFS);
574 
575     // Function Parsing.
576     struct ArgInfo {
577       LocTy Loc;
578       Type *Ty;
579       AttributeSet Attrs;
580       std::string Name;
581       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
582           : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
583     };
584     bool parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &IsVarArg);
585     bool parseFunctionHeader(Function *&Fn, bool IsDefine);
586     bool parseFunctionBody(Function &Fn);
587     bool parseBasicBlock(PerFunctionState &PFS);
588 
589     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
590 
591     // Instruction Parsing.  Each instruction parsing routine can return with a
592     // normal result, an error result, or return having eaten an extra comma.
593     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
594     int parseInstruction(Instruction *&Inst, BasicBlock *BB,
595                          PerFunctionState &PFS);
596     bool parseCmpPredicate(unsigned &P, unsigned Opc);
597 
598     bool parseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
599     bool parseBr(Instruction *&Inst, PerFunctionState &PFS);
600     bool parseSwitch(Instruction *&Inst, PerFunctionState &PFS);
601     bool parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
602     bool parseInvoke(Instruction *&Inst, PerFunctionState &PFS);
603     bool parseResume(Instruction *&Inst, PerFunctionState &PFS);
604     bool parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
605     bool parseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
606     bool parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
607     bool parseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
608     bool parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
609     bool parseCallBr(Instruction *&Inst, PerFunctionState &PFS);
610 
611     bool parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
612                       bool IsFP);
613     bool parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
614                          unsigned Opc, bool IsFP);
615     bool parseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
616     bool parseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
617     bool parseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
618     bool parseSelect(Instruction *&Inst, PerFunctionState &PFS);
619     bool parseVAArg(Instruction *&Inst, PerFunctionState &PFS);
620     bool parseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
621     bool parseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
622     bool parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
623     int parsePHI(Instruction *&Inst, PerFunctionState &PFS);
624     bool parseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
625     bool parseCall(Instruction *&Inst, PerFunctionState &PFS,
626                    CallInst::TailCallKind TCK);
627     int parseAlloc(Instruction *&Inst, PerFunctionState &PFS);
628     int parseLoad(Instruction *&Inst, PerFunctionState &PFS);
629     int parseStore(Instruction *&Inst, PerFunctionState &PFS);
630     int parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
631     int parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
632     int parseFence(Instruction *&Inst, PerFunctionState &PFS);
633     int parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
634     int parseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
635     int parseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
636     bool parseFreeze(Instruction *&I, PerFunctionState &PFS);
637 
638     // Use-list order directives.
639     bool parseUseListOrder(PerFunctionState *PFS = nullptr);
640     bool parseUseListOrderBB();
641     bool parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
642     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
643   };
644 } // End llvm namespace
645 
646 #endif
647