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 
getContext()204     LLVMContext &getContext() { return Context; }
205 
206   private:
error(LocTy L,const Twine & Msg)207     bool error(LocTy L, const Twine &Msg) const { return Lex.Error(L, Msg); }
tokError(const Twine & Msg)208     bool tokError(const Twine &Msg) const { return error(Lex.getLoc(), Msg); }
209 
210     bool checkValueID(LocTy L, StringRef Kind, StringRef Prefix,
211                       unsigned NextID, unsigned ID) const;
212 
213     /// Restore the internal name and slot mappings using the mappings that
214     /// were created at an earlier parsing stage.
215     void restoreParsingState(const SlotMapping *Slots);
216 
217     /// getGlobalVal - Get a value with the specified name or ID, creating a
218     /// forward reference record if needed.  This can return null if the value
219     /// exists but does not have the right type.
220     GlobalValue *getGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
221     GlobalValue *getGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
222 
223     /// Get a Comdat with the specified name, creating a forward reference
224     /// record if needed.
225     Comdat *getComdat(const std::string &Name, LocTy Loc);
226 
227     // Helper Routines.
228     bool parseToken(lltok::Kind T, const char *ErrMsg);
EatIfPresent(lltok::Kind T)229     bool EatIfPresent(lltok::Kind T) {
230       if (Lex.getKind() != T) return false;
231       Lex.Lex();
232       return true;
233     }
234 
EatFastMathFlagsIfPresent()235     FastMathFlags EatFastMathFlagsIfPresent() {
236       FastMathFlags FMF;
237       while (true)
238         switch (Lex.getKind()) {
239         case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
240         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
241         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
242         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
243         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
244         case lltok::kw_contract:
245           FMF.setAllowContract(true);
246           Lex.Lex();
247           continue;
248         case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
249         case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
250         default: return FMF;
251         }
252       return FMF;
253     }
254 
255     bool parseOptionalToken(lltok::Kind T, bool &Present,
256                             LocTy *Loc = nullptr) {
257       if (Lex.getKind() != T) {
258         Present = false;
259       } else {
260         if (Loc)
261           *Loc = Lex.getLoc();
262         Lex.Lex();
263         Present = true;
264       }
265       return false;
266     }
267     bool parseStringConstant(std::string &Result);
268     bool parseUInt32(unsigned &Val);
parseUInt32(unsigned & Val,LocTy & Loc)269     bool parseUInt32(unsigned &Val, LocTy &Loc) {
270       Loc = Lex.getLoc();
271       return parseUInt32(Val);
272     }
273     bool parseUInt64(uint64_t &Val);
parseUInt64(uint64_t & Val,LocTy & Loc)274     bool parseUInt64(uint64_t &Val, LocTy &Loc) {
275       Loc = Lex.getLoc();
276       return parseUInt64(Val);
277     }
278     bool parseFlag(unsigned &Val);
279 
280     bool parseStringAttribute(AttrBuilder &B);
281 
282     bool parseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
283     bool parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
284     bool parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
285     bool parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
parseOptionalProgramAddrSpace(unsigned & AddrSpace)286     bool parseOptionalProgramAddrSpace(unsigned &AddrSpace) {
287       return parseOptionalAddrSpace(
288           AddrSpace, M->getDataLayout().getProgramAddressSpace());
289     };
290     bool parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
291                             bool InAttrGroup);
292     bool parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam);
parseOptionalParamAttrs(AttrBuilder & B)293     bool parseOptionalParamAttrs(AttrBuilder &B) {
294       return parseOptionalParamOrReturnAttrs(B, true);
295     }
parseOptionalReturnAttrs(AttrBuilder & B)296     bool parseOptionalReturnAttrs(AttrBuilder &B) {
297       return parseOptionalParamOrReturnAttrs(B, false);
298     }
299     bool parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
300                               unsigned &Visibility, unsigned &DLLStorageClass,
301                               bool &DSOLocal);
302     void parseOptionalDSOLocal(bool &DSOLocal);
303     void parseOptionalVisibility(unsigned &Res);
304     void parseOptionalDLLStorageClass(unsigned &Res);
305     bool parseOptionalCallingConv(unsigned &CC);
306     bool parseOptionalAlignment(MaybeAlign &Alignment,
307                                 bool AllowParens = false);
308     bool parseOptionalCodeModel(CodeModel::Model &model);
309     bool parseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
310     bool parseOptionalUWTableKind(UWTableKind &Kind);
311     bool parseAllocKind(AllocFnKind &Kind);
312     std::optional<MemoryEffects> parseMemoryAttr();
313     unsigned parseNoFPClassAttr();
314     bool parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
315                                AtomicOrdering &Ordering);
316     bool parseScope(SyncScope::ID &SSID);
317     bool parseOrdering(AtomicOrdering &Ordering);
318     bool parseOptionalStackAlignment(unsigned &Alignment);
319     bool parseOptionalCommaAlign(MaybeAlign &Alignment, bool &AteExtraComma);
320     bool parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
321                                      bool &AteExtraComma);
322     bool parseAllocSizeArguments(unsigned &BaseSizeArg,
323                                  std::optional<unsigned> &HowManyArg);
324     bool parseVScaleRangeArguments(unsigned &MinValue, unsigned &MaxValue);
325     bool parseIndexList(SmallVectorImpl<unsigned> &Indices,
326                         bool &AteExtraComma);
parseIndexList(SmallVectorImpl<unsigned> & Indices)327     bool parseIndexList(SmallVectorImpl<unsigned> &Indices) {
328       bool AteExtraComma;
329       if (parseIndexList(Indices, AteExtraComma))
330         return true;
331       if (AteExtraComma)
332         return tokError("expected index");
333       return false;
334     }
335 
336     // Top-Level Entities
337     bool parseTopLevelEntities();
338     void dropUnknownMetadataReferences();
339     bool validateEndOfModule(bool UpgradeDebugInfo);
340     bool validateEndOfIndex();
341     bool parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback);
342     bool parseTargetDefinition(std::string &TentativeDLStr, LocTy &DLStrLoc);
343     bool parseModuleAsm();
344     bool parseSourceFileName();
345     bool parseUnnamedType();
346     bool parseNamedType();
347     bool parseDeclare();
348     bool parseDefine();
349 
350     bool parseGlobalType(bool &IsConstant);
351     bool parseUnnamedGlobal();
352     bool parseNamedGlobal();
353     bool parseGlobal(const std::string &Name, unsigned NameID, LocTy NameLoc,
354                      unsigned Linkage, bool HasLinkage, unsigned Visibility,
355                      unsigned DLLStorageClass, bool DSOLocal,
356                      GlobalVariable::ThreadLocalMode TLM,
357                      GlobalVariable::UnnamedAddr UnnamedAddr);
358     bool parseAliasOrIFunc(const std::string &Name, unsigned NameID,
359                            LocTy NameLoc, unsigned L, unsigned Visibility,
360                            unsigned DLLStorageClass, bool DSOLocal,
361                            GlobalVariable::ThreadLocalMode TLM,
362                            GlobalVariable::UnnamedAddr UnnamedAddr);
363     bool parseComdat();
364     bool parseStandaloneMetadata();
365     bool parseNamedMetadata();
366     bool parseMDString(MDString *&Result);
367     bool parseMDNodeID(MDNode *&Result);
368     bool parseUnnamedAttrGrp();
369     bool parseFnAttributeValuePairs(AttrBuilder &B,
370                                     std::vector<unsigned> &FwdRefAttrGrps,
371                                     bool inAttrGrp, LocTy &BuiltinLoc);
372     bool parseRangeAttr(AttrBuilder &B);
373     bool parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
374                                Attribute::AttrKind AttrKind);
375 
376     // Module Summary Index Parsing.
377     bool skipModuleSummaryEntry();
378     bool parseSummaryEntry();
379     bool parseModuleEntry(unsigned ID);
380     bool parseModuleReference(StringRef &ModulePath);
381     bool parseGVReference(ValueInfo &VI, unsigned &GVId);
382     bool parseSummaryIndexFlags();
383     bool parseBlockCount();
384     bool parseGVEntry(unsigned ID);
385     bool parseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
386     bool parseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
387     bool parseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
388     bool parseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
389     bool parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
390     bool parseOptionalFFlags(FunctionSummary::FFlags &FFlags);
391     bool parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls);
392     bool parseHotness(CalleeInfo::HotnessType &Hotness);
393     bool parseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
394     bool parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
395     bool parseVFuncIdList(lltok::Kind Kind,
396                           std::vector<FunctionSummary::VFuncId> &VFuncIdList);
397     bool parseConstVCallList(
398         lltok::Kind Kind,
399         std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
400     using IdToIndexMapType =
401         std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
402     bool parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
403                          IdToIndexMapType &IdToIndexMap, unsigned Index);
404     bool parseVFuncId(FunctionSummary::VFuncId &VFuncId,
405                       IdToIndexMapType &IdToIndexMap, unsigned Index);
406     bool parseOptionalVTableFuncs(VTableFuncList &VTableFuncs);
407     bool parseOptionalParamAccesses(
408         std::vector<FunctionSummary::ParamAccess> &Params);
409     bool parseParamNo(uint64_t &ParamNo);
410     using IdLocListType = std::vector<std::pair<unsigned, LocTy>>;
411     bool parseParamAccess(FunctionSummary::ParamAccess &Param,
412                           IdLocListType &IdLocList);
413     bool parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
414                               IdLocListType &IdLocList);
415     bool parseParamAccessOffset(ConstantRange &Range);
416     bool parseOptionalRefs(std::vector<ValueInfo> &Refs);
417     bool parseTypeIdEntry(unsigned ID);
418     bool parseTypeIdSummary(TypeIdSummary &TIS);
419     bool parseTypeIdCompatibleVtableEntry(unsigned ID);
420     bool parseTypeTestResolution(TypeTestResolution &TTRes);
421     bool parseOptionalWpdResolutions(
422         std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
423     bool parseWpdRes(WholeProgramDevirtResolution &WPDRes);
424     bool parseOptionalResByArg(
425         std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
426             &ResByArg);
427     bool parseArgs(std::vector<uint64_t> &Args);
428     bool addGlobalValueToIndex(std::string Name, GlobalValue::GUID,
429                                GlobalValue::LinkageTypes Linkage, unsigned ID,
430                                std::unique_ptr<GlobalValueSummary> Summary,
431                                LocTy Loc);
432     bool parseOptionalAllocs(std::vector<AllocInfo> &Allocs);
433     bool parseMemProfs(std::vector<MIBInfo> &MIBs);
434     bool parseAllocType(uint8_t &AllocType);
435     bool parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites);
436 
437     // Type Parsing.
438     bool parseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
439     bool parseType(Type *&Result, bool AllowVoid = false) {
440       return parseType(Result, "expected type", AllowVoid);
441     }
442     bool parseType(Type *&Result, const Twine &Msg, LocTy &Loc,
443                    bool AllowVoid = false) {
444       Loc = Lex.getLoc();
445       return parseType(Result, Msg, AllowVoid);
446     }
447     bool parseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
448       Loc = Lex.getLoc();
449       return parseType(Result, AllowVoid);
450     }
451     bool parseAnonStructType(Type *&Result, bool Packed);
452     bool parseStructBody(SmallVectorImpl<Type *> &Body);
453     bool parseStructDefinition(SMLoc TypeLoc, StringRef Name,
454                                std::pair<Type *, LocTy> &Entry,
455                                Type *&ResultTy);
456 
457     bool parseArrayVectorType(Type *&Result, bool IsVector);
458     bool parseFunctionType(Type *&Result);
459     bool parseTargetExtType(Type *&Result);
460 
461     // Function Semantic Analysis.
462     class PerFunctionState {
463       LLParser &P;
464       Function &F;
465       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
466       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
467       NumberedValues<Value *> NumberedVals;
468 
469       /// FunctionNumber - If this is an unnamed function, this is the slot
470       /// number of it, otherwise it is -1.
471       int FunctionNumber;
472 
473     public:
474       PerFunctionState(LLParser &p, Function &f, int functionNumber,
475                        ArrayRef<unsigned> UnnamedArgNums);
476       ~PerFunctionState();
477 
getFunction()478       Function &getFunction() const { return F; }
479 
480       bool finishFunction();
481 
482       /// GetVal - Get a value with the specified name or ID, creating a
483       /// forward reference record if needed.  This can return null if the value
484       /// exists but does not have the right type.
485       Value *getVal(const std::string &Name, Type *Ty, LocTy Loc);
486       Value *getVal(unsigned ID, Type *Ty, LocTy Loc);
487 
488       /// setInstName - After an instruction is parsed and inserted into its
489       /// basic block, this installs its name.
490       bool setInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
491                        Instruction *Inst);
492 
493       /// GetBB - Get a basic block with the specified name or ID, creating a
494       /// forward reference record if needed.  This can return null if the value
495       /// is not a BasicBlock.
496       BasicBlock *getBB(const std::string &Name, LocTy Loc);
497       BasicBlock *getBB(unsigned ID, LocTy Loc);
498 
499       /// DefineBB - Define the specified basic block, which is either named or
500       /// unnamed.  If there is an error, this returns null otherwise it returns
501       /// the block being defined.
502       BasicBlock *defineBB(const std::string &Name, int NameID, LocTy Loc);
503 
504       bool resolveForwardRefBlockAddresses();
505     };
506 
507     bool convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
508                              PerFunctionState *PFS);
509 
510     Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
511                                   Value *Val);
512 
513     bool parseConstantValue(Type *Ty, Constant *&C);
514     bool parseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
parseValue(Type * Ty,Value * & V,PerFunctionState & PFS)515     bool parseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
516       return parseValue(Ty, V, &PFS);
517     }
518 
parseValue(Type * Ty,Value * & V,LocTy & Loc,PerFunctionState & PFS)519     bool parseValue(Type *Ty, Value *&V, LocTy &Loc, PerFunctionState &PFS) {
520       Loc = Lex.getLoc();
521       return parseValue(Ty, V, &PFS);
522     }
523 
524     bool parseTypeAndValue(Value *&V, PerFunctionState *PFS);
parseTypeAndValue(Value * & V,PerFunctionState & PFS)525     bool parseTypeAndValue(Value *&V, PerFunctionState &PFS) {
526       return parseTypeAndValue(V, &PFS);
527     }
parseTypeAndValue(Value * & V,LocTy & Loc,PerFunctionState & PFS)528     bool parseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
529       Loc = Lex.getLoc();
530       return parseTypeAndValue(V, PFS);
531     }
532     bool parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
533                                 PerFunctionState &PFS);
parseTypeAndBasicBlock(BasicBlock * & BB,PerFunctionState & PFS)534     bool parseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
535       LocTy Loc;
536       return parseTypeAndBasicBlock(BB, Loc, PFS);
537     }
538 
539     struct ParamInfo {
540       LocTy Loc;
541       Value *V;
542       AttributeSet Attrs;
ParamInfoParamInfo543       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
544           : Loc(loc), V(v), Attrs(attrs) {}
545     };
546     bool parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
547                             PerFunctionState &PFS, bool IsMustTailCall = false,
548                             bool InVarArgsFunc = false);
549 
550     bool
551     parseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
552                                 PerFunctionState &PFS);
553 
554     bool parseExceptionArgs(SmallVectorImpl<Value *> &Args,
555                             PerFunctionState &PFS);
556 
557     bool resolveFunctionType(Type *RetType,
558                              const SmallVector<ParamInfo, 16> &ArgList,
559                              FunctionType *&FuncTy);
560 
561     // Constant Parsing.
562     bool parseValID(ValID &ID, PerFunctionState *PFS,
563                     Type *ExpectedTy = nullptr);
564     bool parseGlobalValue(Type *Ty, Constant *&C);
565     bool parseGlobalTypeAndValue(Constant *&V);
566     bool parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
567                                 std::optional<unsigned> *InRangeOp = nullptr);
568     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
569     bool parseSanitizer(GlobalVariable *GV);
570     bool parseMetadataAsValue(Value *&V, PerFunctionState &PFS);
571     bool parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
572                               PerFunctionState *PFS);
573     bool parseDIArgList(Metadata *&MD, PerFunctionState *PFS);
574     bool parseMetadata(Metadata *&MD, PerFunctionState *PFS);
575     bool parseMDTuple(MDNode *&MD, bool IsDistinct = false);
576     bool parseMDNode(MDNode *&N);
577     bool parseMDNodeTail(MDNode *&N);
578     bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
579     bool parseMetadataAttachment(unsigned &Kind, MDNode *&MD);
580     bool parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS);
581     bool parseInstructionMetadata(Instruction &Inst);
582     bool parseGlobalObjectMetadataAttachment(GlobalObject &GO);
583     bool parseOptionalFunctionMetadata(Function &F);
584 
585     template <class FieldTy>
586     bool parseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
587     template <class FieldTy> bool parseMDField(StringRef Name, FieldTy &Result);
588     template <class ParserTy> bool parseMDFieldsImplBody(ParserTy ParseField);
589     template <class ParserTy>
590     bool parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc);
591     bool parseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
592 
593 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
594   bool parse##CLASS(MDNode *&Result, bool IsDistinct);
595 #include "llvm/IR/Metadata.def"
596 
597     // Function Parsing.
598     struct ArgInfo {
599       LocTy Loc;
600       Type *Ty;
601       AttributeSet Attrs;
602       std::string Name;
ArgInfoArgInfo603       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
604           : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
605     };
606     bool parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
607                            SmallVectorImpl<unsigned> &UnnamedArgNums,
608                            bool &IsVarArg);
609     bool parseFunctionHeader(Function *&Fn, bool IsDefine,
610                              unsigned &FunctionNumber,
611                              SmallVectorImpl<unsigned> &UnnamedArgNums);
612     bool parseFunctionBody(Function &Fn, unsigned FunctionNumber,
613                            ArrayRef<unsigned> UnnamedArgNums);
614     bool parseBasicBlock(PerFunctionState &PFS);
615 
616     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
617 
618     // Instruction Parsing.  Each instruction parsing routine can return with a
619     // normal result, an error result, or return having eaten an extra comma.
620     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
621     int parseInstruction(Instruction *&Inst, BasicBlock *BB,
622                          PerFunctionState &PFS);
623     bool parseCmpPredicate(unsigned &P, unsigned Opc);
624 
625     bool parseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
626     bool parseBr(Instruction *&Inst, PerFunctionState &PFS);
627     bool parseSwitch(Instruction *&Inst, PerFunctionState &PFS);
628     bool parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
629     bool parseInvoke(Instruction *&Inst, PerFunctionState &PFS);
630     bool parseResume(Instruction *&Inst, PerFunctionState &PFS);
631     bool parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
632     bool parseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
633     bool parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
634     bool parseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
635     bool parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
636     bool parseCallBr(Instruction *&Inst, PerFunctionState &PFS);
637 
638     bool parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
639                       bool IsFP);
640     bool parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
641                          unsigned Opc, bool IsFP);
642     bool parseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
643     bool parseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
644     bool parseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
645     bool parseSelect(Instruction *&Inst, PerFunctionState &PFS);
646     bool parseVAArg(Instruction *&Inst, PerFunctionState &PFS);
647     bool parseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
648     bool parseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
649     bool parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
650     int parsePHI(Instruction *&Inst, PerFunctionState &PFS);
651     bool parseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
652     bool parseCall(Instruction *&Inst, PerFunctionState &PFS,
653                    CallInst::TailCallKind TCK);
654     int parseAlloc(Instruction *&Inst, PerFunctionState &PFS);
655     int parseLoad(Instruction *&Inst, PerFunctionState &PFS);
656     int parseStore(Instruction *&Inst, PerFunctionState &PFS);
657     int parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
658     int parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
659     int parseFence(Instruction *&Inst, PerFunctionState &PFS);
660     int parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
661     int parseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
662     int parseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
663     bool parseFreeze(Instruction *&I, PerFunctionState &PFS);
664 
665     // Use-list order directives.
666     bool parseUseListOrder(PerFunctionState *PFS = nullptr);
667     bool parseUseListOrderBB();
668     bool parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
669     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
670   };
671 } // End llvm namespace
672 
673 #endif
674