LLParser.h revision 360784
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_LIB_ASMPARSER_LLPARSER_H
14#define LLVM_LIB_ASMPARSER_LLPARSER_H
15
16#include "LLLexer.h"
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/StringMap.h"
19#include "llvm/IR/Attributes.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Module.h"
22#include "llvm/IR/ModuleSummaryIndex.h"
23#include "llvm/IR/Operator.h"
24#include "llvm/IR/Type.h"
25#include "llvm/IR/ValueHandle.h"
26#include <map>
27
28namespace llvm {
29  class Module;
30  class OpaqueType;
31  class Function;
32  class Value;
33  class BasicBlock;
34  class Instruction;
35  class Constant;
36  class GlobalValue;
37  class Comdat;
38  class MDString;
39  class MDNode;
40  struct SlotMapping;
41  class StructType;
42
43  /// ValID - Represents a reference of a definition of some sort with no type.
44  /// There are several cases where we have to parse the value but where the
45  /// type can depend on later context.  This may either be a numeric reference
46  /// or a symbolic (%var) reference.  This is just a discriminated union.
47  struct ValID {
48    enum {
49      t_LocalID, t_GlobalID,           // ID in UIntVal.
50      t_LocalName, t_GlobalName,       // Name in StrVal.
51      t_APSInt, t_APFloat,             // Value in APSIntVal/APFloatVal.
52      t_Null, t_Undef, t_Zero, t_None, // No value.
53      t_EmptyArray,                    // No value:  []
54      t_Constant,                      // Value in ConstantVal.
55      t_InlineAsm,                     // Value in FTy/StrVal/StrVal2/UIntVal.
56      t_ConstantStruct,                // Value in ConstantStructElts.
57      t_PackedConstantStruct           // Value in ConstantStructElts.
58    } Kind = t_LocalID;
59
60    LLLexer::LocTy Loc;
61    unsigned UIntVal;
62    FunctionType *FTy = nullptr;
63    std::string StrVal, StrVal2;
64    APSInt APSIntVal;
65    APFloat APFloatVal{0.0};
66    Constant *ConstantVal;
67    std::unique_ptr<Constant *[]> ConstantStructElts;
68
69    ValID() = default;
70    ValID(const ValID &RHS)
71        : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
72          StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
73          APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal) {
74      assert(!RHS.ConstantStructElts);
75    }
76
77    bool operator<(const ValID &RHS) const {
78      if (Kind == t_LocalID || Kind == t_GlobalID)
79        return UIntVal < RHS.UIntVal;
80      assert((Kind == t_LocalName || Kind == t_GlobalName ||
81              Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
82             "Ordering not defined for this ValID kind yet");
83      return StrVal < RHS.StrVal;
84    }
85  };
86
87  class LLParser {
88  public:
89    typedef LLLexer::LocTy LocTy;
90  private:
91    LLVMContext &Context;
92    LLLexer Lex;
93    // Module being parsed, null if we are only parsing summary index.
94    Module *M;
95    // Summary index being parsed, null if we are only parsing Module.
96    ModuleSummaryIndex *Index;
97    SlotMapping *Slots;
98
99    // Instruction metadata resolution.  Each instruction can have a list of
100    // MDRef info associated with them.
101    //
102    // The simpler approach of just creating temporary MDNodes and then calling
103    // RAUW on them when the definition is processed doesn't work because some
104    // instruction metadata kinds, such as dbg, get stored in the IR in an
105    // "optimized" format which doesn't participate in the normal value use
106    // lists. This means that RAUW doesn't work, even on temporary MDNodes
107    // which otherwise support RAUW. Instead, we defer resolving MDNode
108    // references until the definitions have been processed.
109    struct MDRef {
110      SMLoc Loc;
111      unsigned MDKind, MDSlot;
112    };
113
114    SmallVector<Instruction*, 64> InstsWithTBAATag;
115
116    // Type resolution handling data structures.  The location is set when we
117    // have processed a use of the type but not a definition yet.
118    StringMap<std::pair<Type*, LocTy> > NamedTypes;
119    std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
120
121    std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
122    std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
123
124    // Global Value reference information.
125    std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
126    std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
127    std::vector<GlobalValue*> NumberedVals;
128
129    // Comdat forward reference information.
130    std::map<std::string, LocTy> ForwardRefComdats;
131
132    // References to blockaddress.  The key is the function ValID, the value is
133    // a list of references to blocks in that function.
134    std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
135    class PerFunctionState;
136    /// Reference to per-function state to allow basic blocks to be
137    /// forward-referenced by blockaddress instructions within the same
138    /// function.
139    PerFunctionState *BlockAddressPFS;
140
141    // Attribute builder reference information.
142    std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
143    std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
144
145    // Summary global value reference information.
146    std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
147        ForwardRefValueInfos;
148    std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
149        ForwardRefAliasees;
150    std::vector<ValueInfo> NumberedValueInfos;
151
152    // Summary type id reference information.
153    std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
154        ForwardRefTypeIds;
155
156    // Map of module ID to path.
157    std::map<unsigned, StringRef> ModuleIdMap;
158
159    /// Only the llvm-as tool may set this to false to bypass
160    /// UpgradeDebuginfo so it can generate broken bitcode.
161    bool UpgradeDebugInfo;
162
163    /// DataLayout string to override that in LLVM assembly.
164    StringRef DataLayoutStr;
165
166    std::string SourceFileName;
167
168  public:
169    LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
170             ModuleSummaryIndex *Index, LLVMContext &Context,
171             SlotMapping *Slots = nullptr, bool UpgradeDebugInfo = true,
172             StringRef DataLayoutString = "")
173        : Context(Context), Lex(F, SM, Err, Context), M(M), Index(Index),
174          Slots(Slots), BlockAddressPFS(nullptr),
175          UpgradeDebugInfo(UpgradeDebugInfo), DataLayoutStr(DataLayoutString) {
176      if (!DataLayoutStr.empty())
177        M->setDataLayout(DataLayoutStr);
178    }
179    bool Run();
180
181    bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
182
183    bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
184                              const SlotMapping *Slots);
185
186    LLVMContext &getContext() { return Context; }
187
188  private:
189
190    bool Error(LocTy L, const Twine &Msg) const {
191      return Lex.Error(L, Msg);
192    }
193    bool TokError(const Twine &Msg) const {
194      return Error(Lex.getLoc(), Msg);
195    }
196
197    /// Restore the internal name and slot mappings using the mappings that
198    /// were created at an earlier parsing stage.
199    void restoreParsingState(const SlotMapping *Slots);
200
201    /// GetGlobalVal - Get a value with the specified name or ID, creating a
202    /// forward reference record if needed.  This can return null if the value
203    /// exists but does not have the right type.
204    GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc,
205                              bool IsCall);
206    GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
207
208    /// Get a Comdat with the specified name, creating a forward reference
209    /// record if needed.
210    Comdat *getComdat(const std::string &Name, LocTy Loc);
211
212    // Helper Routines.
213    bool ParseToken(lltok::Kind T, const char *ErrMsg);
214    bool EatIfPresent(lltok::Kind T) {
215      if (Lex.getKind() != T) return false;
216      Lex.Lex();
217      return true;
218    }
219
220    FastMathFlags EatFastMathFlagsIfPresent() {
221      FastMathFlags FMF;
222      while (true)
223        switch (Lex.getKind()) {
224        case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
225        case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
226        case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
227        case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
228        case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
229        case lltok::kw_contract:
230          FMF.setAllowContract(true);
231          Lex.Lex();
232          continue;
233        case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
234        case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
235        default: return FMF;
236        }
237      return FMF;
238    }
239
240    bool ParseOptionalToken(lltok::Kind T, bool &Present,
241                            LocTy *Loc = nullptr) {
242      if (Lex.getKind() != T) {
243        Present = false;
244      } else {
245        if (Loc)
246          *Loc = Lex.getLoc();
247        Lex.Lex();
248        Present = true;
249      }
250      return false;
251    }
252    bool ParseStringConstant(std::string &Result);
253    bool ParseUInt32(unsigned &Val);
254    bool ParseUInt32(unsigned &Val, LocTy &Loc) {
255      Loc = Lex.getLoc();
256      return ParseUInt32(Val);
257    }
258    bool ParseUInt64(uint64_t &Val);
259    bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
260      Loc = Lex.getLoc();
261      return ParseUInt64(Val);
262    }
263    bool ParseFlag(unsigned &Val);
264
265    bool ParseStringAttribute(AttrBuilder &B);
266
267    bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
268    bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
269    bool ParseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
270    bool ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
271    bool ParseOptionalProgramAddrSpace(unsigned &AddrSpace) {
272      return ParseOptionalAddrSpace(
273          AddrSpace, M->getDataLayout().getProgramAddressSpace());
274    };
275    bool ParseOptionalParamAttrs(AttrBuilder &B);
276    bool ParseOptionalReturnAttrs(AttrBuilder &B);
277    bool ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
278                              unsigned &Visibility, unsigned &DLLStorageClass,
279                              bool &DSOLocal);
280    void ParseOptionalDSOLocal(bool &DSOLocal);
281    void ParseOptionalVisibility(unsigned &Res);
282    void ParseOptionalDLLStorageClass(unsigned &Res);
283    bool ParseOptionalCallingConv(unsigned &CC);
284    bool ParseOptionalAlignment(MaybeAlign &Alignment);
285    bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
286    bool ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
287                               AtomicOrdering &Ordering);
288    bool ParseScope(SyncScope::ID &SSID);
289    bool ParseOrdering(AtomicOrdering &Ordering);
290    bool ParseOptionalStackAlignment(unsigned &Alignment);
291    bool ParseOptionalCommaAlign(MaybeAlign &Alignment, bool &AteExtraComma);
292    bool ParseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
293                                     bool &AteExtraComma);
294    bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
295    bool parseAllocSizeArguments(unsigned &BaseSizeArg,
296                                 Optional<unsigned> &HowManyArg);
297    bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,
298                        bool &AteExtraComma);
299    bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
300      bool AteExtraComma;
301      if (ParseIndexList(Indices, AteExtraComma)) return true;
302      if (AteExtraComma)
303        return TokError("expected index");
304      return false;
305    }
306
307    // Top-Level Entities
308    bool ParseTopLevelEntities();
309    bool ValidateEndOfModule();
310    bool ValidateEndOfIndex();
311    bool ParseTargetDefinition();
312    bool ParseModuleAsm();
313    bool ParseSourceFileName();
314    bool ParseDepLibs();        // FIXME: Remove in 4.0.
315    bool ParseUnnamedType();
316    bool ParseNamedType();
317    bool ParseDeclare();
318    bool ParseDefine();
319
320    bool ParseGlobalType(bool &IsConstant);
321    bool ParseUnnamedGlobal();
322    bool ParseNamedGlobal();
323    bool ParseGlobal(const std::string &Name, LocTy NameLoc, unsigned Linkage,
324                     bool HasLinkage, unsigned Visibility,
325                     unsigned DLLStorageClass, bool DSOLocal,
326                     GlobalVariable::ThreadLocalMode TLM,
327                     GlobalVariable::UnnamedAddr UnnamedAddr);
328    bool parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
329                             unsigned L, unsigned Visibility,
330                             unsigned DLLStorageClass, bool DSOLocal,
331                             GlobalVariable::ThreadLocalMode TLM,
332                             GlobalVariable::UnnamedAddr UnnamedAddr);
333    bool parseComdat();
334    bool ParseStandaloneMetadata();
335    bool ParseNamedMetadata();
336    bool ParseMDString(MDString *&Result);
337    bool ParseMDNodeID(MDNode *&Result);
338    bool ParseUnnamedAttrGrp();
339    bool ParseFnAttributeValuePairs(AttrBuilder &B,
340                                    std::vector<unsigned> &FwdRefAttrGrps,
341                                    bool inAttrGrp, LocTy &BuiltinLoc);
342    bool ParseByValWithOptionalType(Type *&Result);
343
344    // Module Summary Index Parsing.
345    bool SkipModuleSummaryEntry();
346    bool ParseSummaryEntry();
347    bool ParseModuleEntry(unsigned ID);
348    bool ParseModuleReference(StringRef &ModulePath);
349    bool ParseGVReference(ValueInfo &VI, unsigned &GVId);
350    bool ParseGVEntry(unsigned ID);
351    bool ParseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
352    bool ParseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
353    bool ParseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
354    bool ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
355    bool ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
356    bool ParseOptionalFFlags(FunctionSummary::FFlags &FFlags);
357    bool ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls);
358    bool ParseHotness(CalleeInfo::HotnessType &Hotness);
359    bool ParseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
360    bool ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
361    bool ParseVFuncIdList(lltok::Kind Kind,
362                          std::vector<FunctionSummary::VFuncId> &VFuncIdList);
363    bool ParseConstVCallList(
364        lltok::Kind Kind,
365        std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
366    using IdToIndexMapType =
367        std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
368    bool ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
369                         IdToIndexMapType &IdToIndexMap, unsigned Index);
370    bool ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
371                      IdToIndexMapType &IdToIndexMap, unsigned Index);
372    bool ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs);
373    bool ParseOptionalRefs(std::vector<ValueInfo> &Refs);
374    bool ParseTypeIdEntry(unsigned ID);
375    bool ParseTypeIdSummary(TypeIdSummary &TIS);
376    bool ParseTypeIdCompatibleVtableEntry(unsigned ID);
377    bool ParseTypeTestResolution(TypeTestResolution &TTRes);
378    bool ParseOptionalWpdResolutions(
379        std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
380    bool ParseWpdRes(WholeProgramDevirtResolution &WPDRes);
381    bool ParseOptionalResByArg(
382        std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
383            &ResByArg);
384    bool ParseArgs(std::vector<uint64_t> &Args);
385    void AddGlobalValueToIndex(std::string Name, GlobalValue::GUID,
386                               GlobalValue::LinkageTypes Linkage, unsigned ID,
387                               std::unique_ptr<GlobalValueSummary> Summary);
388
389    // Type Parsing.
390    bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
391    bool ParseType(Type *&Result, bool AllowVoid = false) {
392      return ParseType(Result, "expected type", AllowVoid);
393    }
394    bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
395                   bool AllowVoid = false) {
396      Loc = Lex.getLoc();
397      return ParseType(Result, Msg, AllowVoid);
398    }
399    bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
400      Loc = Lex.getLoc();
401      return ParseType(Result, AllowVoid);
402    }
403    bool ParseAnonStructType(Type *&Result, bool Packed);
404    bool ParseStructBody(SmallVectorImpl<Type*> &Body);
405    bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
406                               std::pair<Type*, LocTy> &Entry,
407                               Type *&ResultTy);
408
409    bool ParseArrayVectorType(Type *&Result, bool isVector);
410    bool ParseFunctionType(Type *&Result);
411
412    // Function Semantic Analysis.
413    class PerFunctionState {
414      LLParser &P;
415      Function &F;
416      std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
417      std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
418      std::vector<Value*> NumberedVals;
419
420      /// FunctionNumber - If this is an unnamed function, this is the slot
421      /// number of it, otherwise it is -1.
422      int FunctionNumber;
423    public:
424      PerFunctionState(LLParser &p, Function &f, int functionNumber);
425      ~PerFunctionState();
426
427      Function &getFunction() const { return F; }
428
429      bool FinishFunction();
430
431      /// GetVal - Get a value with the specified name or ID, creating a
432      /// forward reference record if needed.  This can return null if the value
433      /// exists but does not have the right type.
434      Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc, bool IsCall);
435      Value *GetVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
436
437      /// SetInstName - After an instruction is parsed and inserted into its
438      /// basic block, this installs its name.
439      bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
440                       Instruction *Inst);
441
442      /// GetBB - Get a basic block with the specified name or ID, creating a
443      /// forward reference record if needed.  This can return null if the value
444      /// is not a BasicBlock.
445      BasicBlock *GetBB(const std::string &Name, LocTy Loc);
446      BasicBlock *GetBB(unsigned ID, LocTy Loc);
447
448      /// DefineBB - Define the specified basic block, which is either named or
449      /// unnamed.  If there is an error, this returns null otherwise it returns
450      /// the block being defined.
451      BasicBlock *DefineBB(const std::string &Name, int NameID, LocTy Loc);
452
453      bool resolveForwardRefBlockAddresses();
454    };
455
456    bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
457                             PerFunctionState *PFS, bool IsCall);
458
459    Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
460                                  Value *Val, bool IsCall);
461
462    bool parseConstantValue(Type *Ty, Constant *&C);
463    bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
464    bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
465      return ParseValue(Ty, V, &PFS);
466    }
467
468    bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
469                    PerFunctionState &PFS) {
470      Loc = Lex.getLoc();
471      return ParseValue(Ty, V, &PFS);
472    }
473
474    bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
475    bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
476      return ParseTypeAndValue(V, &PFS);
477    }
478    bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
479      Loc = Lex.getLoc();
480      return ParseTypeAndValue(V, PFS);
481    }
482    bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
483                                PerFunctionState &PFS);
484    bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
485      LocTy Loc;
486      return ParseTypeAndBasicBlock(BB, Loc, PFS);
487    }
488
489
490    struct ParamInfo {
491      LocTy Loc;
492      Value *V;
493      AttributeSet Attrs;
494      ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
495          : Loc(loc), V(v), Attrs(attrs) {}
496    };
497    bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
498                            PerFunctionState &PFS,
499                            bool IsMustTailCall = false,
500                            bool InVarArgsFunc = false);
501
502    bool
503    ParseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
504                                PerFunctionState &PFS);
505
506    bool ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
507                            PerFunctionState &PFS);
508
509    // Constant Parsing.
510    bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
511    bool ParseGlobalValue(Type *Ty, Constant *&C);
512    bool ParseGlobalTypeAndValue(Constant *&V);
513    bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
514                                Optional<unsigned> *InRangeOp = nullptr);
515    bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
516    bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
517    bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
518                              PerFunctionState *PFS);
519    bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
520    bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
521    bool ParseMDNode(MDNode *&N);
522    bool ParseMDNodeTail(MDNode *&N);
523    bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
524    bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
525    bool ParseInstructionMetadata(Instruction &Inst);
526    bool ParseGlobalObjectMetadataAttachment(GlobalObject &GO);
527    bool ParseOptionalFunctionMetadata(Function &F);
528
529    template <class FieldTy>
530    bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
531    template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
532    template <class ParserTy>
533    bool ParseMDFieldsImplBody(ParserTy parseField);
534    template <class ParserTy>
535    bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
536    bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
537
538#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
539  bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
540#include "llvm/IR/Metadata.def"
541
542    // Function Parsing.
543    struct ArgInfo {
544      LocTy Loc;
545      Type *Ty;
546      AttributeSet Attrs;
547      std::string Name;
548      ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
549          : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
550    };
551    bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
552    bool ParseFunctionHeader(Function *&Fn, bool isDefine);
553    bool ParseFunctionBody(Function &Fn);
554    bool ParseBasicBlock(PerFunctionState &PFS);
555
556    enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
557
558    // Instruction Parsing.  Each instruction parsing routine can return with a
559    // normal result, an error result, or return having eaten an extra comma.
560    enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
561    int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
562                         PerFunctionState &PFS);
563    bool ParseCmpPredicate(unsigned &P, unsigned Opc);
564
565    bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
566    bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
567    bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
568    bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
569    bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
570    bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
571    bool ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
572    bool ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
573    bool ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
574    bool ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
575    bool ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
576    bool ParseCallBr(Instruction *&Inst, PerFunctionState &PFS);
577
578    bool ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
579                      bool IsFP);
580    bool ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
581                         bool IsFP);
582    bool ParseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
583    bool ParseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
584    bool ParseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
585    bool ParseSelect(Instruction *&Inst, PerFunctionState &PFS);
586    bool ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS);
587    bool ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
588    bool ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
589    bool ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
590    int ParsePHI(Instruction *&Inst, PerFunctionState &PFS);
591    bool ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
592    bool ParseCall(Instruction *&Inst, PerFunctionState &PFS,
593                   CallInst::TailCallKind TCK);
594    int ParseAlloc(Instruction *&Inst, PerFunctionState &PFS);
595    int ParseLoad(Instruction *&Inst, PerFunctionState &PFS);
596    int ParseStore(Instruction *&Inst, PerFunctionState &PFS);
597    int ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
598    int ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
599    int ParseFence(Instruction *&Inst, PerFunctionState &PFS);
600    int ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
601    int ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
602    int ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
603    bool ParseFreeze(Instruction *&I, PerFunctionState &PFS);
604
605    // Use-list order directives.
606    bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
607    bool ParseUseListOrderBB();
608    bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
609    bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
610  };
611} // End llvm namespace
612
613#endif
614