rename MetadataCache -> NumberedMetadata to follow the convention
[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/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/Support/ValueHandle.h"
21 #include <map>
22
23 namespace llvm {
24   class Module;
25   class OpaqueType;
26   class Function;
27   class Value;
28   class BasicBlock;
29   class Instruction;
30   class Constant;
31   class GlobalValue;
32   class MetadataBase;
33   class MDString;
34   class MDNode;
35
36   /// ValID - Represents a reference of a definition of some sort with no type.
37   /// There are several cases where we have to parse the value but where the
38   /// type can depend on later context.  This may either be a numeric reference
39   /// or a symbolic (%var) reference.  This is just a discriminated union.
40   struct ValID {
41     enum {
42       t_LocalID, t_GlobalID,      // ID in UIntVal.
43       t_LocalName, t_GlobalName,  // Name in StrVal.
44       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
45       t_Null, t_Undef, t_Zero,    // No value.
46       t_EmptyArray,               // No value:  []
47       t_Constant,                 // Value in ConstantVal.
48       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
49       t_MDNode,                   // Value in MDNodeVal.
50       t_MDString                  // Value in MDStringVal.
51     } Kind;
52     
53     LLLexer::LocTy Loc;
54     unsigned UIntVal;
55     std::string StrVal, StrVal2;
56     APSInt APSIntVal;
57     APFloat APFloatVal;
58     Constant *ConstantVal;
59     MDNode *MDNodeVal;
60     MDString *MDStringVal;
61     ValID() : APFloatVal(0.0) {}
62     
63     bool operator<(const ValID &RHS) const {
64       if (Kind == t_LocalID || Kind == t_GlobalID)
65         return UIntVal < RHS.UIntVal;
66       assert((Kind == t_LocalName || Kind == t_GlobalName) && 
67              "Ordering not defined for this ValID kind yet");
68       return StrVal < RHS.StrVal;
69     }
70   };
71   
72   class LLParser {
73   public:
74     typedef LLLexer::LocTy LocTy;
75   private:
76     LLVMContext& Context;
77     LLLexer Lex;
78     Module *M;
79
80     // Type resolution handling data structures.
81     std::map<std::string, std::pair<PATypeHolder, LocTy> > ForwardRefTypes;
82     std::map<unsigned, std::pair<PATypeHolder, LocTy> > ForwardRefTypeIDs;
83     std::vector<PATypeHolder> NumberedTypes;
84     std::vector<TrackingVH<MDNode> > NumberedMetadata;
85     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
86     SmallVector<std::pair<unsigned, MDNode *>, 2> MDsOnInst;
87     struct UpRefRecord {
88       /// Loc - This is the location of the upref.
89       LocTy Loc;
90
91       /// NestingLevel - The number of nesting levels that need to be popped
92       /// before this type is resolved.
93       unsigned NestingLevel;
94
95       /// LastContainedTy - This is the type at the current binding level for
96       /// the type.  Every time we reduce the nesting level, this gets updated.
97       const Type *LastContainedTy;
98
99       /// UpRefTy - This is the actual opaque type that the upreference is
100       /// represented with.
101       OpaqueType *UpRefTy;
102
103       UpRefRecord(LocTy L, unsigned NL, OpaqueType *URTy)
104         : Loc(L), NestingLevel(NL), LastContainedTy((Type*)URTy),
105           UpRefTy(URTy) {}
106     };
107     std::vector<UpRefRecord> UpRefs;
108
109     // Global Value reference information.
110     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
111     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
112     std::vector<GlobalValue*> NumberedVals;
113     
114     // References to blockaddress.  The key is the function ValID, the value is
115     // a list of references to blocks in that function.
116     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >
117       ForwardRefBlockAddresses;
118     
119     Function *MallocF;
120   public:
121     LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) : 
122       Context(m->getContext()), Lex(F, SM, Err, m->getContext()),
123       M(m), MallocF(NULL) {}
124     bool Run();
125
126     LLVMContext& getContext() { return Context; }
127
128   private:
129
130     bool Error(LocTy L, const std::string &Msg) const {
131       return Lex.Error(L, Msg);
132     }
133     bool TokError(const std::string &Msg) const {
134       return Error(Lex.getLoc(), Msg);
135     }
136
137     /// GetGlobalVal - Get a value with the specified name or ID, creating a
138     /// forward reference record if needed.  This can return null if the value
139     /// exists but does not have the right type.
140     GlobalValue *GetGlobalVal(const std::string &N, const Type *Ty, LocTy Loc);
141     GlobalValue *GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc);
142
143     // Helper Routines.
144     bool ParseToken(lltok::Kind T, const char *ErrMsg);
145     bool EatIfPresent(lltok::Kind T) {
146       if (Lex.getKind() != T) return false;
147       Lex.Lex();
148       return true;
149     }
150     bool ParseOptionalToken(lltok::Kind T, bool &Present) {
151       if (Lex.getKind() != T) {
152         Present = false;
153       } else {
154         Lex.Lex();
155         Present = true;
156       }
157       return false;
158     }
159     bool ParseStringConstant(std::string &Result);
160     bool ParseUInt32(unsigned &Val);
161     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
162       Loc = Lex.getLoc();
163       return ParseUInt32(Val);
164     }
165     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
166     bool ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind);
167     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
168     bool ParseOptionalLinkage(unsigned &Linkage) {
169       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
170     }
171     bool ParseOptionalVisibility(unsigned &Visibility);
172     bool ParseOptionalCallingConv(CallingConv::ID &CC);
173     bool ParseOptionalAlignment(unsigned &Alignment);
174     bool ParseOptionalCustomMetadata();
175     bool ParseOptionalInfo(unsigned &Alignment);
176     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices);
177
178     // Top-Level Entities
179     bool ParseTopLevelEntities();
180     bool ValidateEndOfModule();
181     bool ParseTargetDefinition();
182     bool ParseDepLibs();
183     bool ParseModuleAsm();
184     bool ParseUnnamedType();
185     bool ParseNamedType();
186     bool ParseDeclare();
187     bool ParseDefine();
188
189     bool ParseGlobalType(bool &IsConstant);
190     bool ParseUnnamedGlobal();
191     bool ParseNamedGlobal();
192     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
193                      bool HasLinkage, unsigned Visibility);
194     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility);
195     bool ParseStandaloneMetadata();
196     bool ParseNamedMetadata();
197     bool ParseMDString(MDString *&Result);
198     bool ParseMDNodeID(MDNode *&Result);
199
200     // Type Parsing.
201     bool ParseType(PATypeHolder &Result, bool AllowVoid = false);
202     bool ParseType(PATypeHolder &Result, LocTy &Loc, bool AllowVoid = false) {
203       Loc = Lex.getLoc();
204       return ParseType(Result, AllowVoid);
205     }
206     bool ParseTypeRec(PATypeHolder &H);
207     bool ParseStructType(PATypeHolder &H, bool Packed);
208     bool ParseArrayVectorType(PATypeHolder &H, bool isVector);
209     bool ParseFunctionType(PATypeHolder &Result);
210     PATypeHolder HandleUpRefs(const Type *Ty);
211
212     // Constants.
213     bool ParseValID(ValID &ID);
214     bool ConvertGlobalValIDToValue(const Type *Ty, ValID &ID, Constant *&V);
215     bool ConvertGlobalOrMetadataValIDToValue(const Type *Ty, ValID &ID,
216                                              Value *&V);
217     bool ParseGlobalValue(const Type *Ty, Constant *&V);
218     bool ParseGlobalTypeAndValue(Constant *&V);
219     bool ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts);
220     bool ParseMDNodeVector(SmallVectorImpl<Value*> &);
221
222
223     // Function Semantic Analysis.
224     class PerFunctionState {
225       LLParser &P;
226       Function &F;
227       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
228       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
229       std::vector<Value*> NumberedVals;
230       
231       /// FunctionNumber - If this is an unnamed function, this is the slot
232       /// number of it, otherwise it is -1.
233       int FunctionNumber;
234     public:
235       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
236       ~PerFunctionState();
237
238       Function &getFunction() const { return F; }
239
240       bool FinishFunction();
241
242       /// GetVal - Get a value with the specified name or ID, creating a
243       /// forward reference record if needed.  This can return null if the value
244       /// exists but does not have the right type.
245       Value *GetVal(const std::string &Name, const Type *Ty, LocTy Loc);
246       Value *GetVal(unsigned ID, const Type *Ty, LocTy Loc);
247
248       /// SetInstName - After an instruction is parsed and inserted into its
249       /// basic block, this installs its name.
250       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
251                        Instruction *Inst);
252
253       /// GetBB - Get a basic block with the specified name or ID, creating a
254       /// forward reference record if needed.  This can return null if the value
255       /// is not a BasicBlock.
256       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
257       BasicBlock *GetBB(unsigned ID, LocTy Loc);
258
259       /// DefineBB - Define the specified basic block, which is either named or
260       /// unnamed.  If there is an error, this returns null otherwise it returns
261       /// the block being defined.
262       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
263     };
264
265     bool ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
266                              PerFunctionState &PFS);
267
268     bool ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS);
269     bool ParseValue(const Type *Ty, Value *&V, LocTy &Loc,
270                     PerFunctionState &PFS) {
271       Loc = Lex.getLoc();
272       return ParseValue(Ty, V, PFS);
273     }
274
275     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS);
276     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
277       Loc = Lex.getLoc();
278       return ParseTypeAndValue(V, PFS);
279     }
280     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
281                                 PerFunctionState &PFS);
282     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
283       LocTy Loc;
284       return ParseTypeAndBasicBlock(BB, Loc, PFS);
285     }
286
287     struct ParamInfo {
288       LocTy Loc;
289       Value *V;
290       unsigned Attrs;
291       ParamInfo(LocTy loc, Value *v, unsigned attrs)
292         : Loc(loc), V(v), Attrs(attrs) {}
293     };
294     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
295                             PerFunctionState &PFS);
296
297     // Function Parsing.
298     struct ArgInfo {
299       LocTy Loc;
300       PATypeHolder Type;
301       unsigned Attrs;
302       std::string Name;
303       ArgInfo(LocTy L, PATypeHolder Ty, unsigned Attr, const std::string &N)
304         : Loc(L), Type(Ty), Attrs(Attr), Name(N) {}
305     };
306     bool ParseArgumentList(std::vector<ArgInfo> &ArgList,
307                            bool &isVarArg, bool inType);
308     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
309     bool ParseFunctionBody(Function &Fn);
310     bool ParseBasicBlock(PerFunctionState &PFS);
311
312     // Instruction Parsing.
313     bool ParseInstruction(Instruction *&Inst, BasicBlock *BB,
314                           PerFunctionState &PFS);
315     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
316
317     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
318     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
319     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
320     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
321     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
322
323     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
324                          unsigned OperandType);
325     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
326     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
327     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
328     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
329     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
330     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
331     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
332     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
333     bool ParsePHI(Instruction *&I, PerFunctionState &PFS);
334     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
335     bool ParseAlloc(Instruction *&I, PerFunctionState &PFS,
336                     BasicBlock *BB = 0, bool isAlloca = true);
337     bool ParseFree(Instruction *&I, PerFunctionState &PFS, BasicBlock *BB);
338     bool ParseLoad(Instruction *&I, PerFunctionState &PFS, bool isVolatile);
339     bool ParseStore(Instruction *&I, PerFunctionState &PFS, bool isVolatile);
340     bool ParseGetResult(Instruction *&I, PerFunctionState &PFS);
341     bool ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
342     bool ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
343     bool ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
344     
345     bool ResolveForwardRefBlockAddresses(Function *TheFn, 
346                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
347                                          PerFunctionState *PFS);
348   };
349 } // End llvm namespace
350
351 #endif