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/Optional.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, t_None, // 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.
62 FunctionType *FTy = nullptr;
63 std::string StrVal, StrVal2;
65 APFloat APFloatVal{0.0};
66 Constant *ConstantVal;
67 std::unique_ptr<Constant *[]> ConstantStructElts;
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);
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;
89 typedef LLLexer::LocTy LocTy;
96 // Instruction metadata resolution. Each instruction can have a list of
97 // MDRef info associated with them.
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.
108 unsigned MDKind, MDSlot;
111 SmallVector<Instruction*, 64> InstsWithTBAATag;
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;
118 std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
119 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
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;
126 // Comdat forward reference information.
127 std::map<std::string, LocTy> ForwardRefComdats;
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
136 PerFunctionState *BlockAddressPFS;
138 // Attribute builder reference information.
139 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
140 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
142 /// Only the llvm-as tool may set this to false to bypass
143 /// UpgradeDebuginfo so it can generate broken bitcode.
144 bool UpgradeDebugInfo;
146 /// DataLayout string to override that in LLVM assembly.
147 StringRef DataLayoutStr;
150 LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
151 SlotMapping *Slots = nullptr, bool UpgradeDebugInfo = true,
152 StringRef DataLayoutString = "")
153 : Context(M->getContext()), Lex(F, SM, Err, M->getContext()), M(M),
154 Slots(Slots), BlockAddressPFS(nullptr),
155 UpgradeDebugInfo(UpgradeDebugInfo), DataLayoutStr(DataLayoutString) {
156 if (!DataLayoutStr.empty())
157 M->setDataLayout(DataLayoutStr);
161 bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
163 bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
164 const SlotMapping *Slots);
166 LLVMContext &getContext() { return Context; }
170 bool Error(LocTy L, const Twine &Msg) const {
171 return Lex.Error(L, Msg);
173 bool TokError(const Twine &Msg) const {
174 return Error(Lex.getLoc(), Msg);
177 /// Restore the internal name and slot mappings using the mappings that
178 /// were created at an earlier parsing stage.
179 void restoreParsingState(const SlotMapping *Slots);
181 /// GetGlobalVal - Get a value with the specified name or ID, creating a
182 /// forward reference record if needed. This can return null if the value
183 /// exists but does not have the right type.
184 GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
185 GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
187 /// Get a Comdat with the specified name, creating a forward reference
188 /// record if needed.
189 Comdat *getComdat(const std::string &N, LocTy Loc);
192 bool ParseToken(lltok::Kind T, const char *ErrMsg);
193 bool EatIfPresent(lltok::Kind T) {
194 if (Lex.getKind() != T) return false;
199 FastMathFlags EatFastMathFlagsIfPresent() {
202 switch (Lex.getKind()) {
203 case lltok::kw_fast: FMF.setFast(); Lex.Lex(); continue;
204 case lltok::kw_nnan: FMF.setNoNaNs(); Lex.Lex(); continue;
205 case lltok::kw_ninf: FMF.setNoInfs(); Lex.Lex(); continue;
206 case lltok::kw_nsz: FMF.setNoSignedZeros(); Lex.Lex(); continue;
207 case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
208 case lltok::kw_contract:
209 FMF.setAllowContract(true);
212 case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
213 case lltok::kw_afn: FMF.setApproxFunc(); Lex.Lex(); continue;
219 bool ParseOptionalToken(lltok::Kind T, bool &Present,
220 LocTy *Loc = nullptr) {
221 if (Lex.getKind() != T) {
231 bool ParseStringConstant(std::string &Result);
232 bool ParseUInt32(unsigned &Val);
233 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
235 return ParseUInt32(Val);
237 bool ParseUInt64(uint64_t &Val);
238 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
240 return ParseUInt64(Val);
243 bool ParseStringAttribute(AttrBuilder &B);
245 bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
246 bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
247 bool ParseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
248 bool ParseOptionalAddrSpace(unsigned &AddrSpace);
249 bool ParseOptionalParamAttrs(AttrBuilder &B);
250 bool ParseOptionalReturnAttrs(AttrBuilder &B);
251 bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage,
252 unsigned &Visibility, unsigned &DLLStorageClass,
254 void ParseOptionalDSOLocal(bool &DSOLocal);
255 void ParseOptionalVisibility(unsigned &Visibility);
256 void ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
257 bool ParseOptionalCallingConv(unsigned &CC);
258 bool ParseOptionalAlignment(unsigned &Alignment);
259 bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
260 bool ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
261 AtomicOrdering &Ordering);
262 bool ParseScope(SyncScope::ID &SSID);
263 bool ParseOrdering(AtomicOrdering &Ordering);
264 bool ParseOptionalStackAlignment(unsigned &Alignment);
265 bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
266 bool ParseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
267 bool &AteExtraComma);
268 bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
269 bool parseAllocSizeArguments(unsigned &ElemSizeArg,
270 Optional<unsigned> &HowManyArg);
271 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,
272 bool &AteExtraComma);
273 bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
275 if (ParseIndexList(Indices, AteExtraComma)) return true;
277 return TokError("expected index");
281 // Top-Level Entities
282 bool ParseTopLevelEntities();
283 bool ValidateEndOfModule();
284 bool ParseTargetDefinition();
285 bool ParseModuleAsm();
286 bool ParseSourceFileName();
287 bool ParseDepLibs(); // FIXME: Remove in 4.0.
288 bool ParseUnnamedType();
289 bool ParseNamedType();
293 bool ParseGlobalType(bool &IsConstant);
294 bool ParseUnnamedGlobal();
295 bool ParseNamedGlobal();
296 bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
297 bool HasLinkage, unsigned Visibility,
298 unsigned DLLStorageClass, bool DSOLocal,
299 GlobalVariable::ThreadLocalMode TLM,
300 GlobalVariable::UnnamedAddr UnnamedAddr);
301 bool parseIndirectSymbol(const std::string &Name, LocTy Loc,
302 unsigned Linkage, unsigned Visibility,
303 unsigned DLLStorageClass, bool DSOLocal,
304 GlobalVariable::ThreadLocalMode TLM,
305 GlobalVariable::UnnamedAddr UnnamedAddr);
307 bool ParseStandaloneMetadata();
308 bool ParseNamedMetadata();
309 bool ParseMDString(MDString *&Result);
310 bool ParseMDNodeID(MDNode *&Result);
311 bool ParseUnnamedAttrGrp();
312 bool ParseFnAttributeValuePairs(AttrBuilder &B,
313 std::vector<unsigned> &FwdRefAttrGrps,
314 bool inAttrGrp, LocTy &BuiltinLoc);
317 bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
318 bool ParseType(Type *&Result, bool AllowVoid = false) {
319 return ParseType(Result, "expected type", AllowVoid);
321 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
322 bool AllowVoid = false) {
324 return ParseType(Result, Msg, AllowVoid);
326 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
328 return ParseType(Result, AllowVoid);
330 bool ParseAnonStructType(Type *&Result, bool Packed);
331 bool ParseStructBody(SmallVectorImpl<Type*> &Body);
332 bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
333 std::pair<Type*, LocTy> &Entry,
336 bool ParseArrayVectorType(Type *&Result, bool isVector);
337 bool ParseFunctionType(Type *&Result);
339 // Function Semantic Analysis.
340 class PerFunctionState {
343 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
344 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
345 std::vector<Value*> NumberedVals;
347 /// FunctionNumber - If this is an unnamed function, this is the slot
348 /// number of it, otherwise it is -1.
351 PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
354 Function &getFunction() const { return F; }
356 bool FinishFunction();
358 /// GetVal - Get a value with the specified name or ID, creating a
359 /// forward reference record if needed. This can return null if the value
360 /// exists but does not have the right type.
361 Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
362 Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
364 /// SetInstName - After an instruction is parsed and inserted into its
365 /// basic block, this installs its name.
366 bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
369 /// GetBB - Get a basic block with the specified name or ID, creating a
370 /// forward reference record if needed. This can return null if the value
371 /// is not a BasicBlock.
372 BasicBlock *GetBB(const std::string &Name, LocTy Loc);
373 BasicBlock *GetBB(unsigned ID, LocTy Loc);
375 /// DefineBB - Define the specified basic block, which is either named or
376 /// unnamed. If there is an error, this returns null otherwise it returns
377 /// the block being defined.
378 BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
380 bool resolveForwardRefBlockAddresses();
383 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
384 PerFunctionState *PFS);
386 bool parseConstantValue(Type *Ty, Constant *&C);
387 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
388 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
389 return ParseValue(Ty, V, &PFS);
392 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
393 PerFunctionState &PFS) {
395 return ParseValue(Ty, V, &PFS);
398 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
399 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
400 return ParseTypeAndValue(V, &PFS);
402 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
404 return ParseTypeAndValue(V, PFS);
406 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
407 PerFunctionState &PFS);
408 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
410 return ParseTypeAndBasicBlock(BB, Loc, PFS);
418 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
419 : Loc(loc), V(v), Attrs(attrs) {}
421 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
422 PerFunctionState &PFS,
423 bool IsMustTailCall = false,
424 bool InVarArgsFunc = false);
427 ParseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
428 PerFunctionState &PFS);
430 bool ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
431 PerFunctionState &PFS);
434 bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
435 bool ParseGlobalValue(Type *Ty, Constant *&V);
436 bool ParseGlobalTypeAndValue(Constant *&V);
437 bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
438 Optional<unsigned> *InRangeOp = nullptr);
439 bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
440 bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
441 bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
442 PerFunctionState *PFS);
443 bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
444 bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
445 bool ParseMDNode(MDNode *&MD);
446 bool ParseMDNodeTail(MDNode *&MD);
447 bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
448 bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
449 bool ParseInstructionMetadata(Instruction &Inst);
450 bool ParseGlobalObjectMetadataAttachment(GlobalObject &GO);
451 bool ParseOptionalFunctionMetadata(Function &F);
453 template <class FieldTy>
454 bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
455 template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
456 template <class ParserTy>
457 bool ParseMDFieldsImplBody(ParserTy parseField);
458 template <class ParserTy>
459 bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
460 bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
462 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
463 bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
464 #include "llvm/IR/Metadata.def"
472 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
473 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
475 bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
476 bool ParseFunctionHeader(Function *&Fn, bool isDefine);
477 bool ParseFunctionBody(Function &Fn);
478 bool ParseBasicBlock(PerFunctionState &PFS);
480 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
482 // Instruction Parsing. Each instruction parsing routine can return with a
483 // normal result, an error result, or return having eaten an extra comma.
484 enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
485 int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
486 PerFunctionState &PFS);
487 bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
489 bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
490 bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
491 bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
492 bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
493 bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
494 bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
495 bool ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
496 bool ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
497 bool ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
498 bool ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
499 bool ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
501 bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
502 unsigned OperandType);
503 bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
504 bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
505 bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
506 bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
507 bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
508 bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
509 bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
510 bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
511 int ParsePHI(Instruction *&I, PerFunctionState &PFS);
512 bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
513 bool ParseCall(Instruction *&I, PerFunctionState &PFS,
514 CallInst::TailCallKind IsTail);
515 int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
516 int ParseLoad(Instruction *&I, PerFunctionState &PFS);
517 int ParseStore(Instruction *&I, PerFunctionState &PFS);
518 int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
519 int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
520 int ParseFence(Instruction *&I, PerFunctionState &PFS);
521 int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
522 int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
523 int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
525 // Use-list order directives.
526 bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
527 bool ParseUseListOrderBB();
528 bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
529 bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
531 } // End llvm namespace