Sort includes for all of the .h files under the 'lib' tree. These were
[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_ASMPARSER_LLPARSER_H
15 #define LLVM_ASMPARSER_LLPARSER_H
16
17 #include "LLLexer.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Attributes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Operator.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/Type.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 MDString;
38   class MDNode;
39   class StructType;
40
41   /// ValID - Represents a reference of a definition of some sort with no type.
42   /// There are several cases where we have to parse the value but where the
43   /// type can depend on later context.  This may either be a numeric reference
44   /// or a symbolic (%var) reference.  This is just a discriminated union.
45   struct ValID {
46     enum {
47       t_LocalID, t_GlobalID,      // ID in UIntVal.
48       t_LocalName, t_GlobalName,  // Name in StrVal.
49       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
50       t_Null, t_Undef, t_Zero,    // No value.
51       t_EmptyArray,               // No value:  []
52       t_Constant,                 // Value in ConstantVal.
53       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
54       t_MDNode,                   // Value in MDNodeVal.
55       t_MDString,                 // Value in MDStringVal.
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     MDNode *MDNodeVal;
67     MDString *MDStringVal;
68     Constant **ConstantStructElts;
69
70     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
71     ~ValID() {
72       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
73         delete [] ConstantStructElts;
74     }
75
76     bool operator<(const ValID &RHS) const {
77       if (Kind == t_LocalID || Kind == t_GlobalID)
78         return UIntVal < RHS.UIntVal;
79       assert((Kind == t_LocalName || Kind == t_GlobalName ||
80               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
81              "Ordering not defined for this ValID kind yet");
82       return StrVal < RHS.StrVal;
83     }
84   };
85
86   class LLParser {
87   public:
88     typedef LLLexer::LocTy LocTy;
89   private:
90     LLVMContext &Context;
91     LLLexer Lex;
92     Module *M;
93
94     // Instruction metadata resolution.  Each instruction can have a list of
95     // MDRef info associated with them.
96     //
97     // The simpler approach of just creating temporary MDNodes and then calling
98     // RAUW on them when the definition is processed doesn't work because some
99     // instruction metadata kinds, such as dbg, get stored in the IR in an
100     // "optimized" format which doesn't participate in the normal value use
101     // lists. This means that RAUW doesn't work, even on temporary MDNodes
102     // which otherwise support RAUW. Instead, we defer resolving MDNode
103     // references until the definitions have been processed.
104     struct MDRef {
105       SMLoc Loc;
106       unsigned MDKind, MDSlot;
107     };
108     DenseMap<Instruction*, std::vector<MDRef> > ForwardRefInstMetadata;
109
110     // Type resolution handling data structures.  The location is set when we
111     // have processed a use of the type but not a definition yet.
112     StringMap<std::pair<Type*, LocTy> > NamedTypes;
113     std::vector<std::pair<Type*, LocTy> > NumberedTypes;
114
115     std::vector<TrackingVH<MDNode> > NumberedMetadata;
116     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
117
118     // Global Value reference information.
119     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
120     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
121     std::vector<GlobalValue*> NumberedVals;
122
123     // References to blockaddress.  The key is the function ValID, the value is
124     // a list of references to blocks in that function.
125     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >
126       ForwardRefBlockAddresses;
127
128   public:
129     LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) :
130       Context(m->getContext()), Lex(F, SM, Err, m->getContext()),
131       M(m) {}
132     bool Run();
133
134     LLVMContext &getContext() { return Context; }
135
136   private:
137
138     bool Error(LocTy L, const Twine &Msg) const {
139       return Lex.Error(L, Msg);
140     }
141     bool TokError(const Twine &Msg) const {
142       return Error(Lex.getLoc(), Msg);
143     }
144
145     /// GetGlobalVal - Get a value with the specified name or ID, creating a
146     /// forward reference record if needed.  This can return null if the value
147     /// exists but does not have the right type.
148     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
149     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
150
151     // Helper Routines.
152     bool ParseToken(lltok::Kind T, const char *ErrMsg);
153     bool EatIfPresent(lltok::Kind T) {
154       if (Lex.getKind() != T) return false;
155       Lex.Lex();
156       return true;
157     }
158
159     FastMathFlags EatFastMathFlagsIfPresent() {
160       FastMathFlags FMF;
161       while (true)
162         switch (Lex.getKind()) {
163         case lltok::kw_fast: FMF.UnsafeAlgebra   = true; Lex.Lex(); continue;
164         case lltok::kw_nnan: FMF.NoNaNs          = true; Lex.Lex(); continue;
165         case lltok::kw_ninf: FMF.NoInfs          = true; Lex.Lex(); continue;
166         case lltok::kw_nsz:  FMF.NoSignedZeros   = true; Lex.Lex(); continue;
167         case lltok::kw_arcp: FMF.AllowReciprocal = true; Lex.Lex(); continue;
168         default: return FMF;
169         }
170       return FMF;
171     }
172
173     bool ParseOptionalToken(lltok::Kind T, bool &Present, LocTy *Loc = 0) {
174       if (Lex.getKind() != T) {
175         Present = false;
176       } else {
177         if (Loc)
178           *Loc = Lex.getLoc();
179         Lex.Lex();
180         Present = true;
181       }
182       return false;
183     }
184     bool ParseStringConstant(std::string &Result);
185     bool ParseUInt32(unsigned &Val);
186     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
187       Loc = Lex.getLoc();
188       return ParseUInt32(Val);
189     }
190
191     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
192     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
193     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
194     bool ParseOptionalAttrs(AttrBuilder &Attrs, unsigned AttrKind);
195     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
196     bool ParseOptionalLinkage(unsigned &Linkage) {
197       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
198     }
199     bool ParseOptionalVisibility(unsigned &Visibility);
200     bool ParseOptionalCallingConv(CallingConv::ID &CC);
201     bool ParseOptionalAlignment(unsigned &Alignment);
202     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
203                                AtomicOrdering &Ordering);
204     bool ParseOptionalStackAlignment(unsigned &Alignment);
205     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
206     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
207     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
208       bool AteExtraComma;
209       if (ParseIndexList(Indices, AteExtraComma)) return true;
210       if (AteExtraComma)
211         return TokError("expected index");
212       return false;
213     }
214
215     // Top-Level Entities
216     bool ParseTopLevelEntities();
217     bool ValidateEndOfModule();
218     bool ParseTargetDefinition();
219     bool ParseModuleAsm();
220     bool ParseDepLibs();        // FIXME: Remove in 4.0.
221     bool ParseUnnamedType();
222     bool ParseNamedType();
223     bool ParseDeclare();
224     bool ParseDefine();
225
226     bool ParseGlobalType(bool &IsConstant);
227     bool ParseUnnamedGlobal();
228     bool ParseNamedGlobal();
229     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
230                      bool HasLinkage, unsigned Visibility);
231     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility);
232     bool ParseStandaloneMetadata();
233     bool ParseNamedMetadata();
234     bool ParseMDString(MDString *&Result);
235     bool ParseMDNodeID(MDNode *&Result);
236     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
237
238     // Type Parsing.
239     bool ParseType(Type *&Result, bool AllowVoid = false);
240     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
241       Loc = Lex.getLoc();
242       return ParseType(Result, AllowVoid);
243     }
244     bool ParseAnonStructType(Type *&Result, bool Packed);
245     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
246     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
247                                std::pair<Type*, LocTy> &Entry,
248                                Type *&ResultTy);
249
250     bool ParseArrayVectorType(Type *&Result, bool isVector);
251     bool ParseFunctionType(Type *&Result);
252
253     // Function Semantic Analysis.
254     class PerFunctionState {
255       LLParser &P;
256       Function &F;
257       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
258       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
259       std::vector<Value*> NumberedVals;
260
261       /// FunctionNumber - If this is an unnamed function, this is the slot
262       /// number of it, otherwise it is -1.
263       int FunctionNumber;
264     public:
265       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
266       ~PerFunctionState();
267
268       Function &getFunction() const { return F; }
269
270       bool FinishFunction();
271
272       /// GetVal - Get a value with the specified name or ID, creating a
273       /// forward reference record if needed.  This can return null if the value
274       /// exists but does not have the right type.
275       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
276       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
277
278       /// SetInstName - After an instruction is parsed and inserted into its
279       /// basic block, this installs its name.
280       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
281                        Instruction *Inst);
282
283       /// GetBB - Get a basic block with the specified name or ID, creating a
284       /// forward reference record if needed.  This can return null if the value
285       /// is not a BasicBlock.
286       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
287       BasicBlock *GetBB(unsigned ID, LocTy Loc);
288
289       /// DefineBB - Define the specified basic block, which is either named or
290       /// unnamed.  If there is an error, this returns null otherwise it returns
291       /// the block being defined.
292       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
293     };
294
295     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
296                              PerFunctionState *PFS);
297
298     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
299     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
300       return ParseValue(Ty, V, &PFS);
301     }
302     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
303                     PerFunctionState &PFS) {
304       Loc = Lex.getLoc();
305       return ParseValue(Ty, V, &PFS);
306     }
307
308     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
309     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
310       return ParseTypeAndValue(V, &PFS);
311     }
312     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
313       Loc = Lex.getLoc();
314       return ParseTypeAndValue(V, PFS);
315     }
316     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
317                                 PerFunctionState &PFS);
318     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
319       LocTy Loc;
320       return ParseTypeAndBasicBlock(BB, Loc, PFS);
321     }
322
323
324     struct ParamInfo {
325       LocTy Loc;
326       Value *V;
327       Attributes Attrs;
328       ParamInfo(LocTy loc, Value *v, Attributes attrs)
329         : Loc(loc), V(v), Attrs(attrs) {}
330     };
331     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
332                             PerFunctionState &PFS);
333
334     // Constant Parsing.
335     bool ParseValID(ValID &ID, PerFunctionState *PFS = NULL);
336     bool ParseGlobalValue(Type *Ty, Constant *&V);
337     bool ParseGlobalTypeAndValue(Constant *&V);
338     bool ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts);
339     bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
340     bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
341     bool ParseMDNodeVector(SmallVectorImpl<Value*> &, PerFunctionState *PFS);
342     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
343
344     // Function Parsing.
345     struct ArgInfo {
346       LocTy Loc;
347       Type *Ty;
348       Attributes Attrs;
349       std::string Name;
350       ArgInfo(LocTy L, Type *ty, Attributes Attr, const std::string &N)
351         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
352     };
353     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
354     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
355     bool ParseFunctionBody(Function &Fn);
356     bool ParseBasicBlock(PerFunctionState &PFS);
357
358     // Instruction Parsing.  Each instruction parsing routine can return with a
359     // normal result, an error result, or return having eaten an extra comma.
360     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
361     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
362                          PerFunctionState &PFS);
363     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
364
365     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
366     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
367     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
368     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
369     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
370     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
371
372     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
373                          unsigned OperandType);
374     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
375     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
376     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
377     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
378     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
379     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
380     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
381     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
382     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
383     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
384     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
385     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
386     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
387     int ParseStore(Instruction *&I, PerFunctionState &PFS);
388     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
389     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
390     int ParseFence(Instruction *&I, PerFunctionState &PFS);
391     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
392     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
393     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
394
395     bool ResolveForwardRefBlockAddresses(Function *TheFn,
396                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
397                                          PerFunctionState *PFS);
398   };
399 } // End llvm namespace
400
401 #endif