IR: Assembly and bitcode for GenericDebugNode
[oota-llvm.git] / lib / AsmParser / LLParser.h
1 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
15 #define LLVM_LIB_ASMPARSER_LLPARSER_H
16
17 #include "LLLexer.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/Type.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include <map>
27
28 namespace 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   class StructType;
41
42   /// ValID - Represents a reference of a definition of some sort with no type.
43   /// There are several cases where we have to parse the value but where the
44   /// type can depend on later context.  This may either be a numeric reference
45   /// or a symbolic (%var) reference.  This is just a discriminated union.
46   struct ValID {
47     enum {
48       t_LocalID, t_GlobalID,      // ID in UIntVal.
49       t_LocalName, t_GlobalName,  // Name in StrVal.
50       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
51       t_Null, t_Undef, t_Zero,    // No value.
52       t_EmptyArray,               // No value:  []
53       t_Constant,                 // Value in ConstantVal.
54       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
55       t_ConstantStruct,           // Value in ConstantStructElts.
56       t_PackedConstantStruct      // Value in ConstantStructElts.
57     } Kind;
58
59     LLLexer::LocTy Loc;
60     unsigned UIntVal;
61     std::string StrVal, StrVal2;
62     APSInt APSIntVal;
63     APFloat APFloatVal;
64     Constant *ConstantVal;
65     Constant **ConstantStructElts;
66
67     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
68     ~ValID() {
69       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
70         delete [] ConstantStructElts;
71     }
72
73     bool operator<(const ValID &RHS) const {
74       if (Kind == t_LocalID || Kind == t_GlobalID)
75         return UIntVal < RHS.UIntVal;
76       assert((Kind == t_LocalName || Kind == t_GlobalName ||
77               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
78              "Ordering not defined for this ValID kind yet");
79       return StrVal < RHS.StrVal;
80     }
81   };
82
83   /// Structure to represent an optional metadata field.
84   template <class FieldTy> struct MDFieldImpl {
85     typedef MDFieldImpl ImplTy;
86     FieldTy Val;
87     bool Seen;
88
89     void assign(FieldTy Val) {
90       Seen = true;
91       this->Val = std::move(Val);
92     }
93
94     explicit MDFieldImpl(FieldTy Default)
95         : Val(std::move(Default)), Seen(false) {}
96   };
97   template <class NumTy> struct MDUnsignedField : public MDFieldImpl<NumTy> {
98     typedef typename MDUnsignedField::ImplTy ImplTy;
99     NumTy Max;
100
101     MDUnsignedField(NumTy Default = 0,
102                     NumTy Max = std::numeric_limits<NumTy>::max())
103         : ImplTy(Default), Max(Max) {}
104   };
105   struct MDField : public MDFieldImpl<Metadata *> {
106     MDField() : ImplTy(nullptr) {}
107   };
108   struct MDStringField : public MDFieldImpl<std::string> {
109     MDStringField() : ImplTy(std::string()) {}
110   };
111   struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
112     MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
113   };
114
115   class LLParser {
116   public:
117     typedef LLLexer::LocTy LocTy;
118   private:
119     LLVMContext &Context;
120     LLLexer Lex;
121     Module *M;
122
123     // Instruction metadata resolution.  Each instruction can have a list of
124     // MDRef info associated with them.
125     //
126     // The simpler approach of just creating temporary MDNodes and then calling
127     // RAUW on them when the definition is processed doesn't work because some
128     // instruction metadata kinds, such as dbg, get stored in the IR in an
129     // "optimized" format which doesn't participate in the normal value use
130     // lists. This means that RAUW doesn't work, even on temporary MDNodes
131     // which otherwise support RAUW. Instead, we defer resolving MDNode
132     // references until the definitions have been processed.
133     struct MDRef {
134       SMLoc Loc;
135       unsigned MDKind, MDSlot;
136     };
137
138     SmallVector<Instruction*, 64> InstsWithTBAATag;
139
140     // Type resolution handling data structures.  The location is set when we
141     // have processed a use of the type but not a definition yet.
142     StringMap<std::pair<Type*, LocTy> > NamedTypes;
143     std::vector<std::pair<Type*, LocTy> > NumberedTypes;
144
145     std::vector<TrackingMDNodeRef> NumberedMetadata;
146     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
147
148     // Global Value reference information.
149     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
150     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
151     std::vector<GlobalValue*> NumberedVals;
152
153     // Comdat forward reference information.
154     std::map<std::string, LocTy> ForwardRefComdats;
155
156     // References to blockaddress.  The key is the function ValID, the value is
157     // a list of references to blocks in that function.
158     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
159     class PerFunctionState;
160     /// Reference to per-function state to allow basic blocks to be
161     /// forward-referenced by blockaddress instructions within the same
162     /// function.
163     PerFunctionState *BlockAddressPFS;
164
165     // Attribute builder reference information.
166     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
167     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
168
169   public:
170     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *m)
171         : Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m),
172           BlockAddressPFS(nullptr) {}
173     bool Run();
174
175     LLVMContext &getContext() { return Context; }
176
177   private:
178
179     bool Error(LocTy L, const Twine &Msg) const {
180       return Lex.Error(L, Msg);
181     }
182     bool TokError(const Twine &Msg) const {
183       return Error(Lex.getLoc(), Msg);
184     }
185
186     /// GetGlobalVal - Get a value with the specified name or ID, creating a
187     /// forward reference record if needed.  This can return null if the value
188     /// exists but does not have the right type.
189     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
190     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
191
192     /// Get a Comdat with the specified name, creating a forward reference
193     /// record if needed.
194     Comdat *getComdat(const std::string &N, LocTy Loc);
195
196     // Helper Routines.
197     bool ParseToken(lltok::Kind T, const char *ErrMsg);
198     bool EatIfPresent(lltok::Kind T) {
199       if (Lex.getKind() != T) return false;
200       Lex.Lex();
201       return true;
202     }
203
204     FastMathFlags EatFastMathFlagsIfPresent() {
205       FastMathFlags FMF;
206       while (true)
207         switch (Lex.getKind()) {
208         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
209         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
210         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
211         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
212         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
213         default: return FMF;
214         }
215       return FMF;
216     }
217
218     bool ParseOptionalToken(lltok::Kind T, bool &Present,
219                             LocTy *Loc = nullptr) {
220       if (Lex.getKind() != T) {
221         Present = false;
222       } else {
223         if (Loc)
224           *Loc = Lex.getLoc();
225         Lex.Lex();
226         Present = true;
227       }
228       return false;
229     }
230     bool ParseStringConstant(std::string &Result);
231     bool ParseUInt32(unsigned &Val);
232     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
233       Loc = Lex.getLoc();
234       return ParseUInt32(Val);
235     }
236     bool ParseUInt64(uint64_t &Val);
237     bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
238       Loc = Lex.getLoc();
239       return ParseUInt64(Val);
240     }
241
242     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
243     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
244     bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
245       return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
246     }
247     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
248     bool ParseOptionalParamAttrs(AttrBuilder &B);
249     bool ParseOptionalReturnAttrs(AttrBuilder &B);
250     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
251     bool ParseOptionalLinkage(unsigned &Linkage) {
252       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
253     }
254     bool ParseOptionalVisibility(unsigned &Visibility);
255     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
256     bool ParseOptionalCallingConv(unsigned &CC);
257     bool ParseOptionalAlignment(unsigned &Alignment);
258     bool ParseOptionalDereferenceableBytes(uint64_t &Bytes);
259     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
260                                AtomicOrdering &Ordering);
261     bool ParseOrdering(AtomicOrdering &Ordering);
262     bool ParseOptionalStackAlignment(unsigned &Alignment);
263     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
264     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
265     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
266     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
267       bool AteExtraComma;
268       if (ParseIndexList(Indices, AteExtraComma)) return true;
269       if (AteExtraComma)
270         return TokError("expected index");
271       return false;
272     }
273
274     // Top-Level Entities
275     bool ParseTopLevelEntities();
276     bool ValidateEndOfModule();
277     bool ParseTargetDefinition();
278     bool ParseModuleAsm();
279     bool ParseDepLibs();        // FIXME: Remove in 4.0.
280     bool ParseUnnamedType();
281     bool ParseNamedType();
282     bool ParseDeclare();
283     bool ParseDefine();
284
285     bool ParseGlobalType(bool &IsConstant);
286     bool ParseUnnamedGlobal();
287     bool ParseNamedGlobal();
288     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
289                      bool HasLinkage, unsigned Visibility,
290                      unsigned DLLStorageClass,
291                      GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
292     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
293                     unsigned Visibility, unsigned DLLStorageClass,
294                     GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
295     bool parseComdat();
296     bool ParseStandaloneMetadata();
297     bool ParseNamedMetadata();
298     bool ParseMDString(MDString *&Result);
299     bool ParseMDNodeID(MDNode *&Result);
300     bool ParseUnnamedAttrGrp();
301     bool ParseFnAttributeValuePairs(AttrBuilder &B,
302                                     std::vector<unsigned> &FwdRefAttrGrps,
303                                     bool inAttrGrp, LocTy &BuiltinLoc);
304
305     // Type Parsing.
306     bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
307     bool ParseType(Type *&Result, bool AllowVoid = false) {
308       return ParseType(Result, "expected type", AllowVoid);
309     }
310     bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
311                    bool AllowVoid = false) {
312       Loc = Lex.getLoc();
313       return ParseType(Result, Msg, AllowVoid);
314     }
315     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
316       Loc = Lex.getLoc();
317       return ParseType(Result, AllowVoid);
318     }
319     bool ParseAnonStructType(Type *&Result, bool Packed);
320     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
321     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
322                                std::pair<Type*, LocTy> &Entry,
323                                Type *&ResultTy);
324
325     bool ParseArrayVectorType(Type *&Result, bool isVector);
326     bool ParseFunctionType(Type *&Result);
327
328     // Function Semantic Analysis.
329     class PerFunctionState {
330       LLParser &P;
331       Function &F;
332       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
333       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
334       std::vector<Value*> NumberedVals;
335
336       /// FunctionNumber - If this is an unnamed function, this is the slot
337       /// number of it, otherwise it is -1.
338       int FunctionNumber;
339     public:
340       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
341       ~PerFunctionState();
342
343       Function &getFunction() const { return F; }
344
345       bool FinishFunction();
346
347       /// GetVal - Get a value with the specified name or ID, creating a
348       /// forward reference record if needed.  This can return null if the value
349       /// exists but does not have the right type.
350       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
351       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
352
353       /// SetInstName - After an instruction is parsed and inserted into its
354       /// basic block, this installs its name.
355       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
356                        Instruction *Inst);
357
358       /// GetBB - Get a basic block with the specified name or ID, creating a
359       /// forward reference record if needed.  This can return null if the value
360       /// is not a BasicBlock.
361       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
362       BasicBlock *GetBB(unsigned ID, LocTy Loc);
363
364       /// DefineBB - Define the specified basic block, which is either named or
365       /// unnamed.  If there is an error, this returns null otherwise it returns
366       /// the block being defined.
367       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
368
369       bool resolveForwardRefBlockAddresses();
370     };
371
372     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
373                              PerFunctionState *PFS);
374
375     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
376     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
377       return ParseValue(Ty, V, &PFS);
378     }
379     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
380                     PerFunctionState &PFS) {
381       Loc = Lex.getLoc();
382       return ParseValue(Ty, V, &PFS);
383     }
384
385     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
386     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
387       return ParseTypeAndValue(V, &PFS);
388     }
389     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
390       Loc = Lex.getLoc();
391       return ParseTypeAndValue(V, PFS);
392     }
393     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
394                                 PerFunctionState &PFS);
395     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
396       LocTy Loc;
397       return ParseTypeAndBasicBlock(BB, Loc, PFS);
398     }
399
400
401     struct ParamInfo {
402       LocTy Loc;
403       Value *V;
404       AttributeSet Attrs;
405       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
406         : Loc(loc), V(v), Attrs(attrs) {}
407     };
408     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
409                             PerFunctionState &PFS,
410                             bool IsMustTailCall = false,
411                             bool InVarArgsFunc = false);
412
413     // Constant Parsing.
414     bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
415     bool ParseGlobalValue(Type *Ty, Constant *&V);
416     bool ParseGlobalTypeAndValue(Constant *&V);
417     bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
418     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
419     bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
420     bool ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS);
421     bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
422     bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
423     bool ParseMDNode(MDNode *&MD);
424     bool ParseMDNodeTail(MDNode *&MD);
425     bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
426     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
427
428     bool ParseMDField(LocTy Loc, StringRef Name,
429                       MDUnsignedField<uint32_t> &Result);
430     bool ParseMDField(LocTy Loc, StringRef Name, MDField &Result);
431     bool ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result);
432     bool ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result);
433     template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
434     template <class ParserTy>
435     bool ParseMDFieldsImplBody(ParserTy parseField);
436     template <class ParserTy>
437     bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
438     bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
439     bool ParseMDLocation(MDNode *&Result, bool IsDistinct);
440     bool ParseGenericDebugNode(MDNode *&Result, bool IsDistinct);
441
442     // Function Parsing.
443     struct ArgInfo {
444       LocTy Loc;
445       Type *Ty;
446       AttributeSet Attrs;
447       std::string Name;
448       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
449         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
450     };
451     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
452     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
453     bool ParseFunctionBody(Function &Fn);
454     bool ParseBasicBlock(PerFunctionState &PFS);
455
456     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
457
458     // Instruction Parsing.  Each instruction parsing routine can return with a
459     // normal result, an error result, or return having eaten an extra comma.
460     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
461     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
462                          PerFunctionState &PFS);
463     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
464
465     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
466     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
467     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
468     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
469     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
470     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
471
472     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
473                          unsigned OperandType);
474     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
475     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
476     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
477     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
478     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
479     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
480     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
481     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
482     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
483     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
484     bool ParseCall(Instruction *&I, PerFunctionState &PFS,
485                    CallInst::TailCallKind IsTail);
486     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
487     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
488     int ParseStore(Instruction *&I, PerFunctionState &PFS);
489     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
490     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
491     int ParseFence(Instruction *&I, PerFunctionState &PFS);
492     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
493     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
494     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
495
496     // Use-list order directives.
497     bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
498     bool ParseUseListOrderBB();
499     bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
500     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
501   };
502 } // End llvm namespace
503
504 #endif