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