Add an inalloca flag to allocas
[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/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/Support/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 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     SmallVector<Instruction*, 64> InstsWithTBAATag;
111
112     // Type resolution handling data structures.  The location is set when we
113     // have processed a use of the type but not a definition yet.
114     StringMap<std::pair<Type*, LocTy> > NamedTypes;
115     std::vector<std::pair<Type*, LocTy> > NumberedTypes;
116
117     std::vector<TrackingVH<MDNode> > NumberedMetadata;
118     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
119
120     // Global Value reference information.
121     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
122     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
123     std::vector<GlobalValue*> NumberedVals;
124
125     // References to blockaddress.  The key is the function ValID, the value is
126     // a list of references to blocks in that function.
127     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >
128       ForwardRefBlockAddresses;
129
130     // Attribute builder reference information.
131     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
132     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
133
134   public:
135     LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) :
136       Context(m->getContext()), Lex(F, SM, Err, m->getContext()),
137       M(m) {}
138     bool Run();
139
140     LLVMContext &getContext() { return Context; }
141
142   private:
143
144     bool Error(LocTy L, const Twine &Msg) const {
145       return Lex.Error(L, Msg);
146     }
147     bool TokError(const Twine &Msg) const {
148       return Error(Lex.getLoc(), Msg);
149     }
150
151     /// GetGlobalVal - Get a value with the specified name or ID, creating a
152     /// forward reference record if needed.  This can return null if the value
153     /// exists but does not have the right type.
154     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
155     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
156
157     // Helper Routines.
158     bool ParseToken(lltok::Kind T, const char *ErrMsg);
159     bool EatIfPresent(lltok::Kind T) {
160       if (Lex.getKind() != T) return false;
161       Lex.Lex();
162       return true;
163     }
164
165     FastMathFlags EatFastMathFlagsIfPresent() {
166       FastMathFlags FMF;
167       while (true)
168         switch (Lex.getKind()) {
169         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
170         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
171         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
172         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
173         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
174         default: return FMF;
175         }
176       return FMF;
177     }
178
179     bool ParseOptionalToken(lltok::Kind T, bool &Present, LocTy *Loc = 0) {
180       if (Lex.getKind() != T) {
181         Present = false;
182       } else {
183         if (Loc)
184           *Loc = Lex.getLoc();
185         Lex.Lex();
186         Present = true;
187       }
188       return false;
189     }
190     bool ParseStringConstant(std::string &Result);
191     bool ParseUInt32(unsigned &Val);
192     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
193       Loc = Lex.getLoc();
194       return ParseUInt32(Val);
195     }
196
197     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
198     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
199     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
200     bool ParseOptionalParamAttrs(AttrBuilder &B);
201     bool ParseOptionalReturnAttrs(AttrBuilder &B);
202     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
203     bool ParseOptionalLinkage(unsigned &Linkage) {
204       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
205     }
206     bool ParseOptionalVisibility(unsigned &Visibility);
207     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
208     bool ParseOptionalCallingConv(CallingConv::ID &CC);
209     bool ParseOptionalAlignment(unsigned &Alignment);
210     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
211                                AtomicOrdering &Ordering);
212     bool ParseOptionalStackAlignment(unsigned &Alignment);
213     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
214     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
215     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
216     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
217       bool AteExtraComma;
218       if (ParseIndexList(Indices, AteExtraComma)) return true;
219       if (AteExtraComma)
220         return TokError("expected index");
221       return false;
222     }
223
224     // Top-Level Entities
225     bool ParseTopLevelEntities();
226     bool ValidateEndOfModule();
227     bool ParseTargetDefinition();
228     bool ParseModuleAsm();
229     bool ParseDepLibs();        // FIXME: Remove in 4.0.
230     bool ParseUnnamedType();
231     bool ParseNamedType();
232     bool ParseDeclare();
233     bool ParseDefine();
234
235     bool ParseGlobalType(bool &IsConstant);
236     bool ParseUnnamedGlobal();
237     bool ParseNamedGlobal();
238     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
239                      bool HasLinkage, unsigned Visibility,
240                      unsigned DLLStorageClass);
241     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility,
242                     unsigned DLLStorageClass);
243     bool ParseStandaloneMetadata();
244     bool ParseNamedMetadata();
245     bool ParseMDString(MDString *&Result);
246     bool ParseMDNodeID(MDNode *&Result);
247     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
248     bool ParseUnnamedAttrGrp();
249     bool ParseFnAttributeValuePairs(AttrBuilder &B,
250                                     std::vector<unsigned> &FwdRefAttrGrps,
251                                     bool inAttrGrp, LocTy &BuiltinLoc);
252
253     // Type Parsing.
254     bool ParseType(Type *&Result, bool AllowVoid = false);
255     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
256       Loc = Lex.getLoc();
257       return ParseType(Result, AllowVoid);
258     }
259     bool ParseAnonStructType(Type *&Result, bool Packed);
260     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
261     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
262                                std::pair<Type*, LocTy> &Entry,
263                                Type *&ResultTy);
264
265     bool ParseArrayVectorType(Type *&Result, bool isVector);
266     bool ParseFunctionType(Type *&Result);
267
268     // Function Semantic Analysis.
269     class PerFunctionState {
270       LLParser &P;
271       Function &F;
272       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
273       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
274       std::vector<Value*> NumberedVals;
275
276       /// FunctionNumber - If this is an unnamed function, this is the slot
277       /// number of it, otherwise it is -1.
278       int FunctionNumber;
279     public:
280       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
281       ~PerFunctionState();
282
283       Function &getFunction() const { return F; }
284
285       bool FinishFunction();
286
287       /// GetVal - Get a value with the specified name or ID, creating a
288       /// forward reference record if needed.  This can return null if the value
289       /// exists but does not have the right type.
290       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
291       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
292
293       /// SetInstName - After an instruction is parsed and inserted into its
294       /// basic block, this installs its name.
295       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
296                        Instruction *Inst);
297
298       /// GetBB - Get a basic block with the specified name or ID, creating a
299       /// forward reference record if needed.  This can return null if the value
300       /// is not a BasicBlock.
301       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
302       BasicBlock *GetBB(unsigned ID, LocTy Loc);
303
304       /// DefineBB - Define the specified basic block, which is either named or
305       /// unnamed.  If there is an error, this returns null otherwise it returns
306       /// the block being defined.
307       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
308     };
309
310     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
311                              PerFunctionState *PFS);
312
313     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
314     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
315       return ParseValue(Ty, V, &PFS);
316     }
317     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
318                     PerFunctionState &PFS) {
319       Loc = Lex.getLoc();
320       return ParseValue(Ty, V, &PFS);
321     }
322
323     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
324     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
325       return ParseTypeAndValue(V, &PFS);
326     }
327     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
328       Loc = Lex.getLoc();
329       return ParseTypeAndValue(V, PFS);
330     }
331     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
332                                 PerFunctionState &PFS);
333     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
334       LocTy Loc;
335       return ParseTypeAndBasicBlock(BB, Loc, PFS);
336     }
337
338
339     struct ParamInfo {
340       LocTy Loc;
341       Value *V;
342       AttributeSet Attrs;
343       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
344         : Loc(loc), V(v), Attrs(attrs) {}
345     };
346     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
347                             PerFunctionState &PFS);
348
349     // Constant Parsing.
350     bool ParseValID(ValID &ID, PerFunctionState *PFS = NULL);
351     bool ParseGlobalValue(Type *Ty, Constant *&V);
352     bool ParseGlobalTypeAndValue(Constant *&V);
353     bool ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts);
354     bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
355     bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
356     bool ParseMDNodeVector(SmallVectorImpl<Value*> &, PerFunctionState *PFS);
357     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
358
359     // Function Parsing.
360     struct ArgInfo {
361       LocTy Loc;
362       Type *Ty;
363       AttributeSet Attrs;
364       std::string Name;
365       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
366         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
367     };
368     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
369     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
370     bool ParseFunctionBody(Function &Fn);
371     bool ParseBasicBlock(PerFunctionState &PFS);
372
373     // Instruction Parsing.  Each instruction parsing routine can return with a
374     // normal result, an error result, or return having eaten an extra comma.
375     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
376     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
377                          PerFunctionState &PFS);
378     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
379
380     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
381     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
382     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
383     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
384     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
385     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
386
387     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
388                          unsigned OperandType);
389     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
390     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
391     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
392     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
393     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
394     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
395     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
396     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
397     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
398     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
399     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
400     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
401     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
402     int ParseStore(Instruction *&I, PerFunctionState &PFS);
403     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
404     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
405     int ParseFence(Instruction *&I, PerFunctionState &PFS);
406     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
407     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
408     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
409
410     bool ResolveForwardRefBlockAddresses(Function *TheFn,
411                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
412                                          PerFunctionState *PFS);
413   };
414 } // End llvm namespace
415
416 #endif