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