Revert "-Wdeprecated-clean: Fix cases of violating the rule of 5 in ways that are...
[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   struct SlotMapping;
41   class StructType;
42
43   /// ValID - Represents a reference of a definition of some sort with no type.
44   /// There are several cases where we have to parse the value but where the
45   /// type can depend on later context.  This may either be a numeric reference
46   /// or a symbolic (%var) reference.  This is just a discriminated union.
47   struct ValID {
48     enum {
49       t_LocalID, t_GlobalID,      // ID in UIntVal.
50       t_LocalName, t_GlobalName,  // Name in StrVal.
51       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
52       t_Null, t_Undef, t_Zero,    // No value.
53       t_EmptyArray,               // No value:  []
54       t_Constant,                 // Value in ConstantVal.
55       t_InlineAsm,                // Value in FTy/StrVal/StrVal2/UIntVal.
56       t_ConstantStruct,           // Value in ConstantStructElts.
57       t_PackedConstantStruct      // Value in ConstantStructElts.
58     } Kind;
59
60     LLLexer::LocTy Loc;
61     unsigned UIntVal;
62     FunctionType *FTy;
63     std::string StrVal, StrVal2;
64     APSInt APSIntVal;
65     APFloat APFloatVal;
66     Constant *ConstantVal;
67     Constant **ConstantStructElts;
68
69     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
70     ~ValID() {
71       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
72         delete [] ConstantStructElts;
73     }
74
75     bool operator<(const ValID &RHS) const {
76       if (Kind == t_LocalID || Kind == t_GlobalID)
77         return UIntVal < RHS.UIntVal;
78       assert((Kind == t_LocalName || Kind == t_GlobalName ||
79               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
80              "Ordering not defined for this ValID kind yet");
81       return StrVal < RHS.StrVal;
82     }
83   };
84
85   class LLParser {
86   public:
87     typedef LLLexer::LocTy LocTy;
88   private:
89     LLVMContext &Context;
90     LLLexer Lex;
91     Module *M;
92     SlotMapping *Slots;
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
109     SmallVector<Instruction*, 64> InstsWithTBAATag;
110
111     // Type resolution handling data structures.  The location is set when we
112     // have processed a use of the type but not a definition yet.
113     StringMap<std::pair<Type*, LocTy> > NamedTypes;
114     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
115
116     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
117     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
118
119     // Global Value reference information.
120     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
121     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
122     std::vector<GlobalValue*> NumberedVals;
123
124     // Comdat forward reference information.
125     std::map<std::string, LocTy> ForwardRefComdats;
126
127     // References to blockaddress.  The key is the function ValID, the value is
128     // a list of references to blocks in that function.
129     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
130     class PerFunctionState;
131     /// Reference to per-function state to allow basic blocks to be
132     /// forward-referenced by blockaddress instructions within the same
133     /// function.
134     PerFunctionState *BlockAddressPFS;
135
136     // Attribute builder reference information.
137     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
138     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
139
140   public:
141     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
142              SlotMapping *Slots = nullptr)
143         : Context(M->getContext()), Lex(F, SM, Err, M->getContext()), M(M),
144           Slots(Slots), BlockAddressPFS(nullptr) {}
145     bool Run();
146
147     bool parseStandaloneConstantValue(Constant *&C);
148
149     LLVMContext &getContext() { return Context; }
150
151   private:
152
153     bool Error(LocTy L, const Twine &Msg) const {
154       return Lex.Error(L, Msg);
155     }
156     bool TokError(const Twine &Msg) const {
157       return Error(Lex.getLoc(), Msg);
158     }
159
160     /// GetGlobalVal - Get a value with the specified name or ID, creating a
161     /// forward reference record if needed.  This can return null if the value
162     /// exists but does not have the right type.
163     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
164     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
165
166     /// Get a Comdat with the specified name, creating a forward reference
167     /// record if needed.
168     Comdat *getComdat(const std::string &N, LocTy Loc);
169
170     // Helper Routines.
171     bool ParseToken(lltok::Kind T, const char *ErrMsg);
172     bool EatIfPresent(lltok::Kind T) {
173       if (Lex.getKind() != T) return false;
174       Lex.Lex();
175       return true;
176     }
177
178     FastMathFlags EatFastMathFlagsIfPresent() {
179       FastMathFlags FMF;
180       while (true)
181         switch (Lex.getKind()) {
182         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
183         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
184         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
185         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
186         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
187         default: return FMF;
188         }
189       return FMF;
190     }
191
192     bool ParseOptionalToken(lltok::Kind T, bool &Present,
193                             LocTy *Loc = nullptr) {
194       if (Lex.getKind() != T) {
195         Present = false;
196       } else {
197         if (Loc)
198           *Loc = Lex.getLoc();
199         Lex.Lex();
200         Present = true;
201       }
202       return false;
203     }
204     bool ParseStringConstant(std::string &Result);
205     bool ParseUInt32(unsigned &Val);
206     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
207       Loc = Lex.getLoc();
208       return ParseUInt32(Val);
209     }
210     bool ParseUInt64(uint64_t &Val);
211     bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
212       Loc = Lex.getLoc();
213       return ParseUInt64(Val);
214     }
215
216     bool ParseStringAttribute(AttrBuilder &B);
217
218     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
219     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
220     bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
221       return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
222     }
223     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
224     bool ParseOptionalParamAttrs(AttrBuilder &B);
225     bool ParseOptionalReturnAttrs(AttrBuilder &B);
226     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
227     bool ParseOptionalLinkage(unsigned &Linkage) {
228       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
229     }
230     bool ParseOptionalVisibility(unsigned &Visibility);
231     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
232     bool ParseOptionalCallingConv(unsigned &CC);
233     bool ParseOptionalAlignment(unsigned &Alignment);
234     bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
235     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
236                                AtomicOrdering &Ordering);
237     bool ParseOrdering(AtomicOrdering &Ordering);
238     bool ParseOptionalStackAlignment(unsigned &Alignment);
239     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
240     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
241     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
242     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
243       bool AteExtraComma;
244       if (ParseIndexList(Indices, AteExtraComma)) return true;
245       if (AteExtraComma)
246         return TokError("expected index");
247       return false;
248     }
249
250     // Top-Level Entities
251     bool ParseTopLevelEntities();
252     bool ValidateEndOfModule();
253     bool ParseTargetDefinition();
254     bool ParseModuleAsm();
255     bool ParseDepLibs();        // FIXME: Remove in 4.0.
256     bool ParseUnnamedType();
257     bool ParseNamedType();
258     bool ParseDeclare();
259     bool ParseDefine();
260
261     bool ParseGlobalType(bool &IsConstant);
262     bool ParseUnnamedGlobal();
263     bool ParseNamedGlobal();
264     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
265                      bool HasLinkage, unsigned Visibility,
266                      unsigned DLLStorageClass,
267                      GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
268     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
269                     unsigned Visibility, unsigned DLLStorageClass,
270                     GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
271     bool parseComdat();
272     bool ParseStandaloneMetadata();
273     bool ParseNamedMetadata();
274     bool ParseMDString(MDString *&Result);
275     bool ParseMDNodeID(MDNode *&Result);
276     bool ParseUnnamedAttrGrp();
277     bool ParseFnAttributeValuePairs(AttrBuilder &B,
278                                     std::vector<unsigned> &FwdRefAttrGrps,
279                                     bool inAttrGrp, LocTy &BuiltinLoc);
280
281     // Type Parsing.
282     bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
283     bool ParseType(Type *&Result, bool AllowVoid = false) {
284       return ParseType(Result, "expected type", AllowVoid);
285     }
286     bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
287                    bool AllowVoid = false) {
288       Loc = Lex.getLoc();
289       return ParseType(Result, Msg, AllowVoid);
290     }
291     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
292       Loc = Lex.getLoc();
293       return ParseType(Result, AllowVoid);
294     }
295     bool ParseAnonStructType(Type *&Result, bool Packed);
296     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
297     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
298                                std::pair<Type*, LocTy> &Entry,
299                                Type *&ResultTy);
300
301     bool ParseArrayVectorType(Type *&Result, bool isVector);
302     bool ParseFunctionType(Type *&Result);
303
304     // Function Semantic Analysis.
305     class PerFunctionState {
306       LLParser &P;
307       Function &F;
308       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
309       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
310       std::vector<Value*> NumberedVals;
311
312       /// FunctionNumber - If this is an unnamed function, this is the slot
313       /// number of it, otherwise it is -1.
314       int FunctionNumber;
315     public:
316       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
317       ~PerFunctionState();
318
319       Function &getFunction() const { return F; }
320
321       bool FinishFunction();
322
323       /// GetVal - Get a value with the specified name or ID, creating a
324       /// forward reference record if needed.  This can return null if the value
325       /// exists but does not have the right type.
326       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
327       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
328
329       /// SetInstName - After an instruction is parsed and inserted into its
330       /// basic block, this installs its name.
331       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
332                        Instruction *Inst);
333
334       /// GetBB - Get a basic block with the specified name or ID, creating a
335       /// forward reference record if needed.  This can return null if the value
336       /// is not a BasicBlock.
337       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
338       BasicBlock *GetBB(unsigned ID, LocTy Loc);
339
340       /// DefineBB - Define the specified basic block, which is either named or
341       /// unnamed.  If there is an error, this returns null otherwise it returns
342       /// the block being defined.
343       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
344
345       bool resolveForwardRefBlockAddresses();
346     };
347
348     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
349                              PerFunctionState *PFS);
350
351     bool parseConstantValue(Type *Ty, Constant *&C);
352     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
353     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
354       return ParseValue(Ty, V, &PFS);
355     }
356     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
357                     PerFunctionState &PFS) {
358       Loc = Lex.getLoc();
359       return ParseValue(Ty, V, &PFS);
360     }
361
362     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
363     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
364       return ParseTypeAndValue(V, &PFS);
365     }
366     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
367       Loc = Lex.getLoc();
368       return ParseTypeAndValue(V, PFS);
369     }
370     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
371                                 PerFunctionState &PFS);
372     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
373       LocTy Loc;
374       return ParseTypeAndBasicBlock(BB, Loc, PFS);
375     }
376
377
378     struct ParamInfo {
379       LocTy Loc;
380       Value *V;
381       AttributeSet Attrs;
382       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
383         : Loc(loc), V(v), Attrs(attrs) {}
384     };
385     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
386                             PerFunctionState &PFS,
387                             bool IsMustTailCall = false,
388                             bool InVarArgsFunc = false);
389
390     bool ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
391                             PerFunctionState &PFS);
392
393     // Constant Parsing.
394     bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
395     bool ParseGlobalValue(Type *Ty, Constant *&V);
396     bool ParseGlobalTypeAndValue(Constant *&V);
397     bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
398     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
399     bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
400     bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
401                               PerFunctionState *PFS);
402     bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
403     bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
404     bool ParseMDNode(MDNode *&MD);
405     bool ParseMDNodeTail(MDNode *&MD);
406     bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
407     bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
408     bool ParseInstructionMetadata(Instruction &Inst);
409     bool ParseOptionalFunctionMetadata(Function &F);
410
411     template <class FieldTy>
412     bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
413     template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
414     template <class ParserTy>
415     bool ParseMDFieldsImplBody(ParserTy parseField);
416     template <class ParserTy>
417     bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
418     bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
419
420 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
421   bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
422 #include "llvm/IR/Metadata.def"
423
424     // Function Parsing.
425     struct ArgInfo {
426       LocTy Loc;
427       Type *Ty;
428       AttributeSet Attrs;
429       std::string Name;
430       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
431         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
432     };
433     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
434     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
435     bool ParseFunctionBody(Function &Fn);
436     bool ParseBasicBlock(PerFunctionState &PFS);
437
438     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
439
440     // Instruction Parsing.  Each instruction parsing routine can return with a
441     // normal result, an error result, or return having eaten an extra comma.
442     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
443     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
444                          PerFunctionState &PFS);
445     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
446
447     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
448     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
449     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
450     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
451     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
452     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
453     bool ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
454     bool ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
455     bool ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
456     bool ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS);
457     bool ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
458     bool ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS);
459
460     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
461                          unsigned OperandType);
462     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
463     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
464     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
465     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
466     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
467     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
468     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
469     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
470     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
471     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
472     bool ParseCall(Instruction *&I, PerFunctionState &PFS,
473                    CallInst::TailCallKind IsTail);
474     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
475     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
476     int ParseStore(Instruction *&I, PerFunctionState &PFS);
477     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
478     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
479     int ParseFence(Instruction *&I, PerFunctionState &PFS);
480     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
481     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
482     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
483
484     // Use-list order directives.
485     bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
486     bool ParseUseListOrderBB();
487     bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
488     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
489   };
490 } // End llvm namespace
491
492 #endif