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 StrVal/StrVal2/UIntVal.
56 t_ConstantStruct, // Value in ConstantStructElts.
57 t_PackedConstantStruct // Value in ConstantStructElts.
62 std::string StrVal, StrVal2;
65 Constant *ConstantVal;
66 Constant **ConstantStructElts;
68 ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
70 if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
71 delete [] ConstantStructElts;
74 bool operator<(const ValID &RHS) const {
75 if (Kind == t_LocalID || Kind == t_GlobalID)
76 return UIntVal < RHS.UIntVal;
77 assert((Kind == t_LocalName || Kind == t_GlobalName ||
78 Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
79 "Ordering not defined for this ValID kind yet");
80 return StrVal < RHS.StrVal;
86 typedef LLLexer::LocTy LocTy;
93 // Instruction metadata resolution. Each instruction can have a list of
94 // MDRef info associated with them.
96 // The simpler approach of just creating temporary MDNodes and then calling
97 // RAUW on them when the definition is processed doesn't work because some
98 // instruction metadata kinds, such as dbg, get stored in the IR in an
99 // "optimized" format which doesn't participate in the normal value use
100 // lists. This means that RAUW doesn't work, even on temporary MDNodes
101 // which otherwise support RAUW. Instead, we defer resolving MDNode
102 // references until the definitions have been processed.
105 unsigned MDKind, MDSlot;
108 SmallVector<Instruction*, 64> InstsWithTBAATag;
110 // Type resolution handling data structures. The location is set when we
111 // have processed a use of the type but not a definition yet.
112 StringMap<std::pair<Type*, LocTy> > NamedTypes;
113 std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
115 std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
116 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
118 // Global Value reference information.
119 std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
120 std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
121 std::vector<GlobalValue*> NumberedVals;
123 // Comdat forward reference information.
124 std::map<std::string, LocTy> ForwardRefComdats;
126 // References to blockaddress. The key is the function ValID, the value is
127 // a list of references to blocks in that function.
128 std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
129 class PerFunctionState;
130 /// Reference to per-function state to allow basic blocks to be
131 /// forward-referenced by blockaddress instructions within the same
133 PerFunctionState *BlockAddressPFS;
135 // Attribute builder reference information.
136 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
137 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
140 LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
141 SlotMapping *Slots = nullptr)
142 : Context(M->getContext()), Lex(F, SM, Err, M->getContext()), M(M),
143 Slots(Slots), BlockAddressPFS(nullptr) {}
146 bool parseStandaloneConstantValue(Constant *&C);
148 LLVMContext &getContext() { return Context; }
152 bool Error(LocTy L, const Twine &Msg) const {
153 return Lex.Error(L, Msg);
155 bool TokError(const Twine &Msg) const {
156 return Error(Lex.getLoc(), Msg);
159 /// GetGlobalVal - Get a value with the specified name or ID, creating a
160 /// forward reference record if needed. This can return null if the value
161 /// exists but does not have the right type.
162 GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
163 GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
165 /// Get a Comdat with the specified name, creating a forward reference
166 /// record if needed.
167 Comdat *getComdat(const std::string &N, LocTy Loc);
170 bool ParseToken(lltok::Kind T, const char *ErrMsg);
171 bool EatIfPresent(lltok::Kind T) {
172 if (Lex.getKind() != T) return false;
177 FastMathFlags EatFastMathFlagsIfPresent() {
180 switch (Lex.getKind()) {
181 case lltok::kw_fast: FMF.setUnsafeAlgebra(); Lex.Lex(); continue;
182 case lltok::kw_nnan: FMF.setNoNaNs(); Lex.Lex(); continue;
183 case lltok::kw_ninf: FMF.setNoInfs(); Lex.Lex(); continue;
184 case lltok::kw_nsz: FMF.setNoSignedZeros(); Lex.Lex(); continue;
185 case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
191 bool ParseOptionalToken(lltok::Kind T, bool &Present,
192 LocTy *Loc = nullptr) {
193 if (Lex.getKind() != T) {
203 bool ParseStringConstant(std::string &Result);
204 bool ParseUInt32(unsigned &Val);
205 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
207 return ParseUInt32(Val);
209 bool ParseUInt64(uint64_t &Val);
210 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
212 return ParseUInt64(Val);
215 bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
216 bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
217 bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
218 return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
220 bool ParseOptionalAddrSpace(unsigned &AddrSpace);
221 bool ParseOptionalParamAttrs(AttrBuilder &B);
222 bool ParseOptionalReturnAttrs(AttrBuilder &B);
223 bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
224 bool ParseOptionalLinkage(unsigned &Linkage) {
225 bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
227 bool ParseOptionalVisibility(unsigned &Visibility);
228 bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
229 bool ParseOptionalCallingConv(unsigned &CC);
230 bool ParseOptionalAlignment(unsigned &Alignment);
231 bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
232 bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
233 AtomicOrdering &Ordering);
234 bool ParseOrdering(AtomicOrdering &Ordering);
235 bool ParseOptionalStackAlignment(unsigned &Alignment);
236 bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
237 bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
238 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
239 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
241 if (ParseIndexList(Indices, AteExtraComma)) return true;
243 return TokError("expected index");
247 // Top-Level Entities
248 bool ParseTopLevelEntities();
249 bool ValidateEndOfModule();
250 bool ParseTargetDefinition();
251 bool ParseModuleAsm();
252 bool ParseDepLibs(); // FIXME: Remove in 4.0.
253 bool ParseUnnamedType();
254 bool ParseNamedType();
258 bool ParseGlobalType(bool &IsConstant);
259 bool ParseUnnamedGlobal();
260 bool ParseNamedGlobal();
261 bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
262 bool HasLinkage, unsigned Visibility,
263 unsigned DLLStorageClass,
264 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
265 bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
266 unsigned Visibility, unsigned DLLStorageClass,
267 GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
269 bool ParseStandaloneMetadata();
270 bool ParseNamedMetadata();
271 bool ParseMDString(MDString *&Result);
272 bool ParseMDNodeID(MDNode *&Result);
273 bool ParseUnnamedAttrGrp();
274 bool ParseFnAttributeValuePairs(AttrBuilder &B,
275 std::vector<unsigned> &FwdRefAttrGrps,
276 bool inAttrGrp, LocTy &BuiltinLoc);
279 bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
280 bool ParseType(Type *&Result, bool AllowVoid = false) {
281 return ParseType(Result, "expected type", AllowVoid);
283 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
284 bool AllowVoid = false) {
286 return ParseType(Result, Msg, AllowVoid);
288 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
290 return ParseType(Result, AllowVoid);
292 bool ParseAnonStructType(Type *&Result, bool Packed);
293 bool ParseStructBody(SmallVectorImpl<Type*> &Body);
294 bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
295 std::pair<Type*, LocTy> &Entry,
298 bool ParseArrayVectorType(Type *&Result, bool isVector);
299 bool ParseFunctionType(Type *&Result);
301 // Function Semantic Analysis.
302 class PerFunctionState {
305 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
306 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
307 std::vector<Value*> NumberedVals;
309 /// FunctionNumber - If this is an unnamed function, this is the slot
310 /// number of it, otherwise it is -1.
313 PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
316 Function &getFunction() const { return F; }
318 bool FinishFunction();
320 /// GetVal - Get a value with the specified name or ID, creating a
321 /// forward reference record if needed. This can return null if the value
322 /// exists but does not have the right type.
323 Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
324 Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
326 /// SetInstName - After an instruction is parsed and inserted into its
327 /// basic block, this installs its name.
328 bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
331 /// GetBB - Get a basic block with the specified name or ID, creating a
332 /// forward reference record if needed. This can return null if the value
333 /// is not a BasicBlock.
334 BasicBlock *GetBB(const std::string &Name, LocTy Loc);
335 BasicBlock *GetBB(unsigned ID, LocTy Loc);
337 /// DefineBB - Define the specified basic block, which is either named or
338 /// unnamed. If there is an error, this returns null otherwise it returns
339 /// the block being defined.
340 BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
342 bool resolveForwardRefBlockAddresses();
345 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
346 PerFunctionState *PFS);
348 bool parseConstantValue(Type *Ty, Constant *&C);
349 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
350 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
351 return ParseValue(Ty, V, &PFS);
353 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
354 PerFunctionState &PFS) {
356 return ParseValue(Ty, V, &PFS);
359 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
360 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
361 return ParseTypeAndValue(V, &PFS);
363 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
365 return ParseTypeAndValue(V, PFS);
367 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
368 PerFunctionState &PFS);
369 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
371 return ParseTypeAndBasicBlock(BB, Loc, PFS);
379 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
380 : Loc(loc), V(v), Attrs(attrs) {}
382 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
383 PerFunctionState &PFS,
384 bool IsMustTailCall = false,
385 bool InVarArgsFunc = false);
388 bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
389 bool ParseGlobalValue(Type *Ty, Constant *&V);
390 bool ParseGlobalTypeAndValue(Constant *&V);
391 bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
392 bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
393 bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
394 bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
395 PerFunctionState *PFS);
396 bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
397 bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
398 bool ParseMDNode(MDNode *&MD);
399 bool ParseMDNodeTail(MDNode *&MD);
400 bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
401 bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
402 bool ParseInstructionMetadata(Instruction &Inst);
403 bool ParseOptionalFunctionMetadata(Function &F);
405 template <class FieldTy>
406 bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
407 template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
408 template <class ParserTy>
409 bool ParseMDFieldsImplBody(ParserTy parseField);
410 template <class ParserTy>
411 bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
412 bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
414 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
415 bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
416 #include "llvm/IR/Metadata.def"
424 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
425 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
427 bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
428 bool ParseFunctionHeader(Function *&Fn, bool isDefine);
429 bool ParseFunctionBody(Function &Fn);
430 bool ParseBasicBlock(PerFunctionState &PFS);
432 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
434 // Instruction Parsing. Each instruction parsing routine can return with a
435 // normal result, an error result, or return having eaten an extra comma.
436 enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
437 int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
438 PerFunctionState &PFS);
439 bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
441 bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
442 bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
443 bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
444 bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
445 bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
446 bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
448 bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
449 unsigned OperandType);
450 bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
451 bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
452 bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
453 bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
454 bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
455 bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
456 bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
457 bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
458 int ParsePHI(Instruction *&I, PerFunctionState &PFS);
459 bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
460 bool ParseCall(Instruction *&I, PerFunctionState &PFS,
461 CallInst::TailCallKind IsTail);
462 int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
463 int ParseLoad(Instruction *&I, PerFunctionState &PFS);
464 int ParseStore(Instruction *&I, PerFunctionState &PFS);
465 int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
466 int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
467 int ParseFence(Instruction *&I, PerFunctionState &PFS);
468 int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
469 int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
470 int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
472 // Use-list order directives.
473 bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
474 bool ParseUseListOrderBB();
475 bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
476 bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
478 } // End llvm namespace