1 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
15 #define LLVM_LIB_ASMPARSER_LLPARSER_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"
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.
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.
61 std::string StrVal, StrVal2;
64 Constant *ConstantVal;
65 Constant **ConstantStructElts;
67 ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
69 if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
70 delete [] ConstantStructElts;
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;
83 /// Structure to represent an optional metadata field.
84 template <class FieldTy> struct MDFieldImpl {
85 typedef MDFieldImpl ImplTy;
89 void assign(FieldTy Val) {
94 explicit MDFieldImpl(FieldTy Default) : Val(Default), Seen(false) {}
96 template <class NumTy> struct MDUnsignedField : public MDFieldImpl<NumTy> {
97 typedef typename MDUnsignedField::ImplTy ImplTy;
100 MDUnsignedField(NumTy Default = 0,
101 NumTy Max = std::numeric_limits<NumTy>::max())
102 : ImplTy(Default), Max(Max) {}
104 struct MDField : public MDFieldImpl<Metadata *> {
105 MDField() : ImplTy(nullptr) {}
110 typedef LLLexer::LocTy LocTy;
112 LLVMContext &Context;
116 // Instruction metadata resolution. Each instruction can have a list of
117 // MDRef info associated with them.
119 // The simpler approach of just creating temporary MDNodes and then calling
120 // RAUW on them when the definition is processed doesn't work because some
121 // instruction metadata kinds, such as dbg, get stored in the IR in an
122 // "optimized" format which doesn't participate in the normal value use
123 // lists. This means that RAUW doesn't work, even on temporary MDNodes
124 // which otherwise support RAUW. Instead, we defer resolving MDNode
125 // references until the definitions have been processed.
128 unsigned MDKind, MDSlot;
131 SmallVector<Instruction*, 64> InstsWithTBAATag;
133 // Type resolution handling data structures. The location is set when we
134 // have processed a use of the type but not a definition yet.
135 StringMap<std::pair<Type*, LocTy> > NamedTypes;
136 std::vector<std::pair<Type*, LocTy> > NumberedTypes;
138 std::vector<TrackingMDNodeRef> NumberedMetadata;
139 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
141 // Global Value reference information.
142 std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
143 std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
144 std::vector<GlobalValue*> NumberedVals;
146 // Comdat forward reference information.
147 std::map<std::string, LocTy> ForwardRefComdats;
149 // References to blockaddress. The key is the function ValID, the value is
150 // a list of references to blocks in that function.
151 std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
152 class PerFunctionState;
153 /// Reference to per-function state to allow basic blocks to be
154 /// forward-referenced by blockaddress instructions within the same
156 PerFunctionState *BlockAddressPFS;
158 // Attribute builder reference information.
159 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
160 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
163 LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *m)
164 : Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m),
165 BlockAddressPFS(nullptr) {}
168 LLVMContext &getContext() { return Context; }
172 bool Error(LocTy L, const Twine &Msg) const {
173 return Lex.Error(L, Msg);
175 bool TokError(const Twine &Msg) const {
176 return Error(Lex.getLoc(), Msg);
179 /// GetGlobalVal - Get a value with the specified name or ID, creating a
180 /// forward reference record if needed. This can return null if the value
181 /// exists but does not have the right type.
182 GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
183 GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
185 /// Get a Comdat with the specified name, creating a forward reference
186 /// record if needed.
187 Comdat *getComdat(const std::string &N, LocTy Loc);
190 bool ParseToken(lltok::Kind T, const char *ErrMsg);
191 bool EatIfPresent(lltok::Kind T) {
192 if (Lex.getKind() != T) return false;
197 FastMathFlags EatFastMathFlagsIfPresent() {
200 switch (Lex.getKind()) {
201 case lltok::kw_fast: FMF.setUnsafeAlgebra(); Lex.Lex(); continue;
202 case lltok::kw_nnan: FMF.setNoNaNs(); Lex.Lex(); continue;
203 case lltok::kw_ninf: FMF.setNoInfs(); Lex.Lex(); continue;
204 case lltok::kw_nsz: FMF.setNoSignedZeros(); Lex.Lex(); continue;
205 case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
211 bool ParseOptionalToken(lltok::Kind T, bool &Present,
212 LocTy *Loc = nullptr) {
213 if (Lex.getKind() != T) {
223 bool ParseStringConstant(std::string &Result);
224 bool ParseUInt32(unsigned &Val);
225 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
227 return ParseUInt32(Val);
229 bool ParseUInt64(uint64_t &Val);
230 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
232 return ParseUInt64(Val);
235 bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
236 bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
237 bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
238 return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
240 bool ParseOptionalAddrSpace(unsigned &AddrSpace);
241 bool ParseOptionalParamAttrs(AttrBuilder &B);
242 bool ParseOptionalReturnAttrs(AttrBuilder &B);
243 bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
244 bool ParseOptionalLinkage(unsigned &Linkage) {
245 bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
247 bool ParseOptionalVisibility(unsigned &Visibility);
248 bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
249 bool ParseOptionalCallingConv(unsigned &CC);
250 bool ParseOptionalAlignment(unsigned &Alignment);
251 bool ParseOptionalDereferenceableBytes(uint64_t &Bytes);
252 bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
253 AtomicOrdering &Ordering);
254 bool ParseOrdering(AtomicOrdering &Ordering);
255 bool ParseOptionalStackAlignment(unsigned &Alignment);
256 bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
257 bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
258 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
259 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
261 if (ParseIndexList(Indices, AteExtraComma)) return true;
263 return TokError("expected index");
267 // Top-Level Entities
268 bool ParseTopLevelEntities();
269 bool ValidateEndOfModule();
270 bool ParseTargetDefinition();
271 bool ParseModuleAsm();
272 bool ParseDepLibs(); // FIXME: Remove in 4.0.
273 bool ParseUnnamedType();
274 bool ParseNamedType();
278 bool ParseGlobalType(bool &IsConstant);
279 bool ParseUnnamedGlobal();
280 bool ParseNamedGlobal();
281 bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
282 bool HasLinkage, unsigned Visibility,
283 unsigned DLLStorageClass,
284 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
285 bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
286 unsigned Visibility, unsigned DLLStorageClass,
287 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
289 bool ParseStandaloneMetadata();
290 bool ParseNamedMetadata();
291 bool ParseMDString(MDString *&Result);
292 bool ParseMDNodeID(MDNode *&Result);
293 bool ParseUnnamedAttrGrp();
294 bool ParseFnAttributeValuePairs(AttrBuilder &B,
295 std::vector<unsigned> &FwdRefAttrGrps,
296 bool inAttrGrp, LocTy &BuiltinLoc);
299 bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
300 bool ParseType(Type *&Result, bool AllowVoid = false) {
301 return ParseType(Result, "expected type", AllowVoid);
303 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
304 bool AllowVoid = false) {
306 return ParseType(Result, Msg, AllowVoid);
308 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
310 return ParseType(Result, AllowVoid);
312 bool ParseAnonStructType(Type *&Result, bool Packed);
313 bool ParseStructBody(SmallVectorImpl<Type*> &Body);
314 bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
315 std::pair<Type*, LocTy> &Entry,
318 bool ParseArrayVectorType(Type *&Result, bool isVector);
319 bool ParseFunctionType(Type *&Result);
321 // Function Semantic Analysis.
322 class PerFunctionState {
325 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
326 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
327 std::vector<Value*> NumberedVals;
329 /// FunctionNumber - If this is an unnamed function, this is the slot
330 /// number of it, otherwise it is -1.
333 PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
336 Function &getFunction() const { return F; }
338 bool FinishFunction();
340 /// GetVal - Get a value with the specified name or ID, creating a
341 /// forward reference record if needed. This can return null if the value
342 /// exists but does not have the right type.
343 Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
344 Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
346 /// SetInstName - After an instruction is parsed and inserted into its
347 /// basic block, this installs its name.
348 bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
351 /// GetBB - Get a basic block with the specified name or ID, creating a
352 /// forward reference record if needed. This can return null if the value
353 /// is not a BasicBlock.
354 BasicBlock *GetBB(const std::string &Name, LocTy Loc);
355 BasicBlock *GetBB(unsigned ID, LocTy Loc);
357 /// DefineBB - Define the specified basic block, which is either named or
358 /// unnamed. If there is an error, this returns null otherwise it returns
359 /// the block being defined.
360 BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
362 bool resolveForwardRefBlockAddresses();
365 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
366 PerFunctionState *PFS);
368 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
369 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
370 return ParseValue(Ty, V, &PFS);
372 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
373 PerFunctionState &PFS) {
375 return ParseValue(Ty, V, &PFS);
378 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
379 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
380 return ParseTypeAndValue(V, &PFS);
382 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
384 return ParseTypeAndValue(V, PFS);
386 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
387 PerFunctionState &PFS);
388 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
390 return ParseTypeAndBasicBlock(BB, Loc, PFS);
398 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
399 : Loc(loc), V(v), Attrs(attrs) {}
401 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
402 PerFunctionState &PFS,
403 bool IsMustTailCall = false,
404 bool InVarArgsFunc = false);
407 bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
408 bool ParseGlobalValue(Type *Ty, Constant *&V);
409 bool ParseGlobalTypeAndValue(Constant *&V);
410 bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
411 bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
412 bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
413 bool ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS);
414 bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
415 bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
416 bool ParseMDNode(MDNode *&MD);
417 bool ParseMDNodeTail(MDNode *&MD);
418 bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
419 bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
421 bool ParseMDField(LocTy Loc, StringRef Name,
422 MDUnsignedField<uint32_t> &Result);
423 bool ParseMDField(LocTy Loc, StringRef Name, MDField &Result);
424 template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
425 template <class ParserTy>
426 bool ParseMDFieldsImplBody(ParserTy parseField);
427 template <class ParserTy>
428 bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
429 bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
430 bool ParseMDLocation(MDNode *&Result, bool IsDistinct);
438 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
439 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
441 bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
442 bool ParseFunctionHeader(Function *&Fn, bool isDefine);
443 bool ParseFunctionBody(Function &Fn);
444 bool ParseBasicBlock(PerFunctionState &PFS);
446 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
448 // Instruction Parsing. Each instruction parsing routine can return with a
449 // normal result, an error result, or return having eaten an extra comma.
450 enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
451 int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
452 PerFunctionState &PFS);
453 bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
455 bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
456 bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
457 bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
458 bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
459 bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
460 bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
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);
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);
492 } // End llvm namespace