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