unique_ptrify ValID::ConstantStructElts
[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_ConstantStruct,           // Value in ConstantStructElts.
56       t_PackedConstantStruct      // Value in ConstantStructElts.
57     } Kind;
58
59     LLLexer::LocTy Loc;
60     unsigned UIntVal;
61     std::string StrVal, StrVal2;
62     APSInt APSIntVal;
63     APFloat APFloatVal;
64     Constant *ConstantVal;
65     std::unique_ptr<Constant*[]> ConstantStructElts;
66
67     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
68
69     bool operator<(const ValID &RHS) const {
70       if (Kind == t_LocalID || Kind == t_GlobalID)
71         return UIntVal < RHS.UIntVal;
72       assert((Kind == t_LocalName || Kind == t_GlobalName ||
73               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
74              "Ordering not defined for this ValID kind yet");
75       return StrVal < RHS.StrVal;
76     }
77   };
78
79   class LLParser {
80   public:
81     typedef LLLexer::LocTy LocTy;
82   private:
83     LLVMContext &Context;
84     LLLexer Lex;
85     Module *M;
86
87     // Instruction metadata resolution.  Each instruction can have a list of
88     // MDRef info associated with them.
89     //
90     // The simpler approach of just creating temporary MDNodes and then calling
91     // RAUW on them when the definition is processed doesn't work because some
92     // instruction metadata kinds, such as dbg, get stored in the IR in an
93     // "optimized" format which doesn't participate in the normal value use
94     // lists. This means that RAUW doesn't work, even on temporary MDNodes
95     // which otherwise support RAUW. Instead, we defer resolving MDNode
96     // references until the definitions have been processed.
97     struct MDRef {
98       SMLoc Loc;
99       unsigned MDKind, MDSlot;
100     };
101
102     SmallVector<Instruction*, 64> InstsWithTBAATag;
103
104     // Type resolution handling data structures.  The location is set when we
105     // have processed a use of the type but not a definition yet.
106     StringMap<std::pair<Type*, LocTy> > NamedTypes;
107     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
108
109     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
110     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
111
112     // Global Value reference information.
113     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
114     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
115     std::vector<GlobalValue*> NumberedVals;
116
117     // Comdat forward reference information.
118     std::map<std::string, LocTy> ForwardRefComdats;
119
120     // References to blockaddress.  The key is the function ValID, the value is
121     // a list of references to blocks in that function.
122     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
123     class PerFunctionState;
124     /// Reference to per-function state to allow basic blocks to be
125     /// forward-referenced by blockaddress instructions within the same
126     /// function.
127     PerFunctionState *BlockAddressPFS;
128
129     // Attribute builder reference information.
130     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
131     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
132
133   public:
134     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *m)
135         : Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m),
136           BlockAddressPFS(nullptr) {}
137     bool Run();
138
139     LLVMContext &getContext() { return Context; }
140
141   private:
142
143     bool Error(LocTy L, const Twine &Msg) const {
144       return Lex.Error(L, Msg);
145     }
146     bool TokError(const Twine &Msg) const {
147       return Error(Lex.getLoc(), Msg);
148     }
149
150     /// GetGlobalVal - Get a value with the specified name or ID, creating a
151     /// forward reference record if needed.  This can return null if the value
152     /// exists but does not have the right type.
153     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
154     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
155
156     /// Get a Comdat with the specified name, creating a forward reference
157     /// record if needed.
158     Comdat *getComdat(const std::string &N, LocTy Loc);
159
160     // Helper Routines.
161     bool ParseToken(lltok::Kind T, const char *ErrMsg);
162     bool EatIfPresent(lltok::Kind T) {
163       if (Lex.getKind() != T) return false;
164       Lex.Lex();
165       return true;
166     }
167
168     FastMathFlags EatFastMathFlagsIfPresent() {
169       FastMathFlags FMF;
170       while (true)
171         switch (Lex.getKind()) {
172         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
173         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
174         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
175         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
176         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
177         default: return FMF;
178         }
179       return FMF;
180     }
181
182     bool ParseOptionalToken(lltok::Kind T, bool &Present,
183                             LocTy *Loc = nullptr) {
184       if (Lex.getKind() != T) {
185         Present = false;
186       } else {
187         if (Loc)
188           *Loc = Lex.getLoc();
189         Lex.Lex();
190         Present = true;
191       }
192       return false;
193     }
194     bool ParseStringConstant(std::string &Result);
195     bool ParseUInt32(unsigned &Val);
196     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
197       Loc = Lex.getLoc();
198       return ParseUInt32(Val);
199     }
200     bool ParseUInt64(uint64_t &Val);
201     bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
202       Loc = Lex.getLoc();
203       return ParseUInt64(Val);
204     }
205
206     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
207     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
208     bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
209       return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
210     }
211     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
212     bool ParseOptionalParamAttrs(AttrBuilder &B);
213     bool ParseOptionalReturnAttrs(AttrBuilder &B);
214     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
215     bool ParseOptionalLinkage(unsigned &Linkage) {
216       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
217     }
218     bool ParseOptionalVisibility(unsigned &Visibility);
219     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
220     bool ParseOptionalCallingConv(unsigned &CC);
221     bool ParseOptionalAlignment(unsigned &Alignment);
222     bool ParseOptionalDereferenceableBytes(uint64_t &Bytes);
223     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
224                                AtomicOrdering &Ordering);
225     bool ParseOrdering(AtomicOrdering &Ordering);
226     bool ParseOptionalStackAlignment(unsigned &Alignment);
227     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
228     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
229     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
230     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
231       bool AteExtraComma;
232       if (ParseIndexList(Indices, AteExtraComma)) return true;
233       if (AteExtraComma)
234         return TokError("expected index");
235       return false;
236     }
237
238     // Top-Level Entities
239     bool ParseTopLevelEntities();
240     bool ValidateEndOfModule();
241     bool ParseTargetDefinition();
242     bool ParseModuleAsm();
243     bool ParseDepLibs();        // FIXME: Remove in 4.0.
244     bool ParseUnnamedType();
245     bool ParseNamedType();
246     bool ParseDeclare();
247     bool ParseDefine();
248
249     bool ParseGlobalType(bool &IsConstant);
250     bool ParseUnnamedGlobal();
251     bool ParseNamedGlobal();
252     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
253                      bool HasLinkage, unsigned Visibility,
254                      unsigned DLLStorageClass,
255                      GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
256     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
257                     unsigned Visibility, unsigned DLLStorageClass,
258                     GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
259     bool parseComdat();
260     bool ParseStandaloneMetadata();
261     bool ParseNamedMetadata();
262     bool ParseMDString(MDString *&Result);
263     bool ParseMDNodeID(MDNode *&Result);
264     bool ParseUnnamedAttrGrp();
265     bool ParseFnAttributeValuePairs(AttrBuilder &B,
266                                     std::vector<unsigned> &FwdRefAttrGrps,
267                                     bool inAttrGrp, LocTy &BuiltinLoc);
268
269     // Type Parsing.
270     bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
271     bool ParseType(Type *&Result, bool AllowVoid = false) {
272       return ParseType(Result, "expected type", AllowVoid);
273     }
274     bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
275                    bool AllowVoid = false) {
276       Loc = Lex.getLoc();
277       return ParseType(Result, Msg, AllowVoid);
278     }
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(StringRef GlobalName, Comdat *&C);
383     bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
384     bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
385                               PerFunctionState *PFS);
386     bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
387     bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
388     bool ParseMDNode(MDNode *&MD);
389     bool ParseMDNodeTail(MDNode *&MD);
390     bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
391     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
392
393     template <class FieldTy>
394     bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
395     template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
396     template <class ParserTy>
397     bool ParseMDFieldsImplBody(ParserTy parseField);
398     template <class ParserTy>
399     bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
400     bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
401
402 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
403   bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
404 #include "llvm/IR/Metadata.def"
405
406     // Function Parsing.
407     struct ArgInfo {
408       LocTy Loc;
409       Type *Ty;
410       AttributeSet Attrs;
411       std::string Name;
412       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
413         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
414     };
415     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
416     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
417     bool ParseFunctionBody(Function &Fn);
418     bool ParseBasicBlock(PerFunctionState &PFS);
419
420     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
421
422     // Instruction Parsing.  Each instruction parsing routine can return with a
423     // normal result, an error result, or return having eaten an extra comma.
424     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
425     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
426                          PerFunctionState &PFS);
427     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
428
429     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
430     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
431     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
432     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
433     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
434     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
435
436     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
437                          unsigned OperandType);
438     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
439     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
440     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
441     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
442     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
443     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
444     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
445     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
446     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
447     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
448     bool ParseCall(Instruction *&I, PerFunctionState &PFS,
449                    CallInst::TailCallKind IsTail);
450     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
451     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
452     int ParseStore(Instruction *&I, PerFunctionState &PFS);
453     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
454     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
455     int ParseFence(Instruction *&I, PerFunctionState &PFS);
456     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
457     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
458     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
459
460     // Use-list order directives.
461     bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
462     bool ParseUseListOrderBB();
463     bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
464     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
465   };
466 } // End llvm namespace
467
468 #endif