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