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