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