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