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"
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.
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.
63 std::string StrVal, StrVal2;
66 Constant *ConstantVal;
67 Constant **ConstantStructElts;
69 ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
71 if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
72 delete [] ConstantStructElts;
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;
87 typedef LLLexer::LocTy LocTy;
94 // Instruction metadata resolution. Each instruction can have a list of
95 // MDRef info associated with them.
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.
106 unsigned MDKind, MDSlot;
109 SmallVector<Instruction*, 64> InstsWithTBAATag;
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;
116 std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
117 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
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;
124 // Comdat forward reference information.
125 std::map<std::string, LocTy> ForwardRefComdats;
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
134 PerFunctionState *BlockAddressPFS;
136 // Attribute builder reference information.
137 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
138 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
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) {}
147 bool parseStandaloneConstantValue(Constant *&C);
149 LLVMContext &getContext() { return Context; }
153 bool Error(LocTy L, const Twine &Msg) const {
154 return Lex.Error(L, Msg);
156 bool TokError(const Twine &Msg) const {
157 return Error(Lex.getLoc(), Msg);
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);
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);
171 bool ParseToken(lltok::Kind T, const char *ErrMsg);
172 bool EatIfPresent(lltok::Kind T) {
173 if (Lex.getKind() != T) return false;
178 FastMathFlags EatFastMathFlagsIfPresent() {
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;
192 bool ParseOptionalToken(lltok::Kind T, bool &Present,
193 LocTy *Loc = nullptr) {
194 if (Lex.getKind() != T) {
204 bool ParseStringConstant(std::string &Result);
205 bool ParseUInt32(unsigned &Val);
206 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
208 return ParseUInt32(Val);
210 bool ParseUInt64(uint64_t &Val);
211 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
213 return ParseUInt64(Val);
216 bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
217 bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
218 bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
219 return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
221 bool ParseOptionalAddrSpace(unsigned &AddrSpace);
222 bool ParseOptionalParamAttrs(AttrBuilder &B);
223 bool ParseOptionalReturnAttrs(AttrBuilder &B);
224 bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
225 bool ParseOptionalLinkage(unsigned &Linkage) {
226 bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
228 bool ParseOptionalVisibility(unsigned &Visibility);
229 bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
230 bool ParseOptionalCallingConv(unsigned &CC);
231 bool ParseOptionalAlignment(unsigned &Alignment);
232 bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
233 bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
234 AtomicOrdering &Ordering);
235 bool ParseOrdering(AtomicOrdering &Ordering);
236 bool ParseOptionalStackAlignment(unsigned &Alignment);
237 bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
238 bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
239 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
240 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
242 if (ParseIndexList(Indices, AteExtraComma)) return true;
244 return TokError("expected index");
248 // Top-Level Entities
249 bool ParseTopLevelEntities();
250 bool ValidateEndOfModule();
251 bool ParseTargetDefinition();
252 bool ParseModuleAsm();
253 bool ParseDepLibs(); // FIXME: Remove in 4.0.
254 bool ParseUnnamedType();
255 bool ParseNamedType();
259 bool ParseGlobalType(bool &IsConstant);
260 bool ParseUnnamedGlobal();
261 bool ParseNamedGlobal();
262 bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
263 bool HasLinkage, unsigned Visibility,
264 unsigned DLLStorageClass,
265 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
266 bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
267 unsigned Visibility, unsigned DLLStorageClass,
268 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
270 bool ParseStandaloneMetadata();
271 bool ParseNamedMetadata();
272 bool ParseMDString(MDString *&Result);
273 bool ParseMDNodeID(MDNode *&Result);
274 bool ParseUnnamedAttrGrp();
275 bool ParseFnAttributeValuePairs(AttrBuilder &B,
276 std::vector<unsigned> &FwdRefAttrGrps,
277 bool inAttrGrp, LocTy &BuiltinLoc);
280 bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
281 bool ParseType(Type *&Result, bool AllowVoid = false) {
282 return ParseType(Result, "expected type", AllowVoid);
284 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
285 bool AllowVoid = false) {
287 return ParseType(Result, Msg, AllowVoid);
289 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
291 return ParseType(Result, AllowVoid);
293 bool ParseAnonStructType(Type *&Result, bool Packed);
294 bool ParseStructBody(SmallVectorImpl<Type*> &Body);
295 bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
296 std::pair<Type*, LocTy> &Entry,
299 bool ParseArrayVectorType(Type *&Result, bool isVector);
300 bool ParseFunctionType(Type *&Result);
302 // Function Semantic Analysis.
303 class PerFunctionState {
306 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
307 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
308 std::vector<Value*> NumberedVals;
310 /// FunctionNumber - If this is an unnamed function, this is the slot
311 /// number of it, otherwise it is -1.
314 PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
317 Function &getFunction() const { return F; }
319 bool FinishFunction();
321 /// GetVal - Get a value with the specified name or ID, creating a
322 /// forward reference record if needed. This can return null if the value
323 /// exists but does not have the right type.
324 Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
325 Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
327 /// SetInstName - After an instruction is parsed and inserted into its
328 /// basic block, this installs its name.
329 bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
332 /// GetBB - Get a basic block with the specified name or ID, creating a
333 /// forward reference record if needed. This can return null if the value
334 /// is not a BasicBlock.
335 BasicBlock *GetBB(const std::string &Name, LocTy Loc);
336 BasicBlock *GetBB(unsigned ID, LocTy Loc);
338 /// DefineBB - Define the specified basic block, which is either named or
339 /// unnamed. If there is an error, this returns null otherwise it returns
340 /// the block being defined.
341 BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
343 bool resolveForwardRefBlockAddresses();
346 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
347 PerFunctionState *PFS);
349 bool parseConstantValue(Type *Ty, Constant *&C);
350 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
351 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
352 return ParseValue(Ty, V, &PFS);
354 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
355 PerFunctionState &PFS) {
357 return ParseValue(Ty, V, &PFS);
360 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
361 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
362 return ParseTypeAndValue(V, &PFS);
364 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
366 return ParseTypeAndValue(V, PFS);
368 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
369 PerFunctionState &PFS);
370 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
372 return ParseTypeAndBasicBlock(BB, Loc, PFS);
380 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
381 : Loc(loc), V(v), Attrs(attrs) {}
383 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
384 PerFunctionState &PFS,
385 bool IsMustTailCall = false,
386 bool InVarArgsFunc = false);
389 bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
390 bool ParseGlobalValue(Type *Ty, Constant *&V);
391 bool ParseGlobalTypeAndValue(Constant *&V);
392 bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
393 bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
394 bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
395 bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
396 PerFunctionState *PFS);
397 bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
398 bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
399 bool ParseMDNode(MDNode *&MD);
400 bool ParseMDNodeTail(MDNode *&MD);
401 bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
402 bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
403 bool ParseInstructionMetadata(Instruction &Inst);
404 bool ParseOptionalFunctionMetadata(Function &F);
406 template <class FieldTy>
407 bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
408 template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
409 template <class ParserTy>
410 bool ParseMDFieldsImplBody(ParserTy parseField);
411 template <class ParserTy>
412 bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
413 bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
415 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
416 bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
417 #include "llvm/IR/Metadata.def"
425 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
426 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
428 bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
429 bool ParseFunctionHeader(Function *&Fn, bool isDefine);
430 bool ParseFunctionBody(Function &Fn);
431 bool ParseBasicBlock(PerFunctionState &PFS);
433 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
435 // Instruction Parsing. Each instruction parsing routine can return with a
436 // normal result, an error result, or return having eaten an extra comma.
437 enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
438 int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
439 PerFunctionState &PFS);
440 bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
442 bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
443 bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
444 bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
445 bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
446 bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
447 bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
449 bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
450 unsigned OperandType);
451 bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
452 bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
453 bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
454 bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
455 bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
456 bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
457 bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
458 bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
459 int ParsePHI(Instruction *&I, PerFunctionState &PFS);
460 bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
461 bool ParseCall(Instruction *&I, PerFunctionState &PFS,
462 CallInst::TailCallKind IsTail);
463 int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
464 int ParseLoad(Instruction *&I, PerFunctionState &PFS);
465 int ParseStore(Instruction *&I, PerFunctionState &PFS);
466 int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
467 int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
468 int ParseFence(Instruction *&I, PerFunctionState &PFS);
469 int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
470 int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
471 int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
473 // Use-list order directives.
474 bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
475 bool ParseUseListOrderBB();
476 bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
477 bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
479 } // End llvm namespace