1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
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 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/Dwarf.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
57 static std::string getTypeString(Type *T) {
59 raw_string_ostream Tmp(Result);
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run() {
69 if (Context.shouldDiscardValueNames())
72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
93 restoreParsingState(Slots);
97 SMLoc Start = Lex.getLoc();
101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
122 bool LLParser::ValidateEndOfModule() {
123 // Handle any function attribute group forward references.
124 for (const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
129 for (const auto &Attr : Attrs)
130 B.merge(NumberedAttrBuilders[Attr]);
132 if (Function *Fn = dyn_cast<Function>(V)) {
133 AttributeSet AS = Fn->getAttributes();
134 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
135 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
136 AS.getFnAttributes());
140 // If the alignment was parsed as an attribute, move to the alignment
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
147 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
148 AttributeSet::get(Context,
149 AttributeSet::FunctionIndex,
151 Fn->setAttributes(AS);
152 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
153 AttributeSet AS = CI->getAttributes();
154 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
155 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
156 AS.getFnAttributes());
158 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
159 AttributeSet::get(Context,
160 AttributeSet::FunctionIndex,
162 CI->setAttributes(AS);
163 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
164 AttributeSet AS = II->getAttributes();
165 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
166 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
167 AS.getFnAttributes());
169 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
170 AttributeSet::get(Context,
171 AttributeSet::FunctionIndex,
173 II->setAttributes(AS);
175 llvm_unreachable("invalid object with forward attribute group reference");
179 // If there are entries in ForwardRefBlockAddresses at this point, the
180 // function was never defined.
181 if (!ForwardRefBlockAddresses.empty())
182 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
183 "expected function name in blockaddress");
185 for (const auto &NT : NumberedTypes)
186 if (NT.second.second.isValid())
187 return Error(NT.second.second,
188 "use of undefined type '%" + Twine(NT.first) + "'");
190 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
191 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
192 if (I->second.second.isValid())
193 return Error(I->second.second,
194 "use of undefined type named '" + I->getKey() + "'");
196 if (!ForwardRefComdats.empty())
197 return Error(ForwardRefComdats.begin()->second,
198 "use of undefined comdat '$" +
199 ForwardRefComdats.begin()->first + "'");
201 if (!ForwardRefVals.empty())
202 return Error(ForwardRefVals.begin()->second.second,
203 "use of undefined value '@" + ForwardRefVals.begin()->first +
206 if (!ForwardRefValIDs.empty())
207 return Error(ForwardRefValIDs.begin()->second.second,
208 "use of undefined value '@" +
209 Twine(ForwardRefValIDs.begin()->first) + "'");
211 if (!ForwardRefMDNodes.empty())
212 return Error(ForwardRefMDNodes.begin()->second.second,
213 "use of undefined metadata '!" +
214 Twine(ForwardRefMDNodes.begin()->first) + "'");
216 // Resolve metadata cycles.
217 for (auto &N : NumberedMetadata) {
218 if (N.second && !N.second->isResolved())
219 N.second->resolveCycles();
222 for (auto *Inst : InstsWithTBAATag) {
223 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
224 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
225 auto *UpgradedMD = UpgradeTBAANode(*MD);
226 if (MD != UpgradedMD)
227 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
230 // Look for intrinsic functions and CallInst that need to be upgraded
231 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
232 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
234 // Some types could be renamed during loading if several modules are
235 // loaded in the same LLVMContext (LTO scenario). In this case we should
236 // remangle intrinsics names as well.
237 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
238 Function *F = &*FI++;
239 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
240 F->replaceAllUsesWith(Remangled.getValue());
241 F->eraseFromParent();
245 UpgradeDebugInfo(*M);
247 UpgradeModuleFlags(*M);
251 // Initialize the slot mapping.
252 // Because by this point we've parsed and validated everything, we can "steal"
253 // the mapping from LLParser as it doesn't need it anymore.
254 Slots->GlobalValues = std::move(NumberedVals);
255 Slots->MetadataNodes = std::move(NumberedMetadata);
256 for (const auto &I : NamedTypes)
257 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
258 for (const auto &I : NumberedTypes)
259 Slots->Types.insert(std::make_pair(I.first, I.second.first));
264 //===----------------------------------------------------------------------===//
265 // Top-Level Entities
266 //===----------------------------------------------------------------------===//
268 bool LLParser::ParseTopLevelEntities() {
270 switch (Lex.getKind()) {
271 default: return TokError("expected top-level entity");
272 case lltok::Eof: return false;
273 case lltok::kw_declare: if (ParseDeclare()) return true; break;
274 case lltok::kw_define: if (ParseDefine()) return true; break;
275 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
276 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
277 case lltok::kw_source_filename:
278 if (ParseSourceFileName())
281 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
282 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
283 case lltok::LocalVar: if (ParseNamedType()) return true; break;
284 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
285 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
286 case lltok::ComdatVar: if (parseComdat()) return true; break;
287 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
288 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
289 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
290 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
291 case lltok::kw_uselistorder_bb:
292 if (ParseUseListOrderBB())
300 /// ::= 'module' 'asm' STRINGCONSTANT
301 bool LLParser::ParseModuleAsm() {
302 assert(Lex.getKind() == lltok::kw_module);
306 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
307 ParseStringConstant(AsmStr)) return true;
309 M->appendModuleInlineAsm(AsmStr);
314 /// ::= 'target' 'triple' '=' STRINGCONSTANT
315 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
316 bool LLParser::ParseTargetDefinition() {
317 assert(Lex.getKind() == lltok::kw_target);
320 default: return TokError("unknown target property");
321 case lltok::kw_triple:
323 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
324 ParseStringConstant(Str))
326 M->setTargetTriple(Str);
328 case lltok::kw_datalayout:
330 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
331 ParseStringConstant(Str))
333 M->setDataLayout(Str);
339 /// ::= 'source_filename' '=' STRINGCONSTANT
340 bool LLParser::ParseSourceFileName() {
341 assert(Lex.getKind() == lltok::kw_source_filename);
344 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
345 ParseStringConstant(Str))
347 M->setSourceFileName(Str);
352 /// ::= 'deplibs' '=' '[' ']'
353 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
354 /// FIXME: Remove in 4.0. Currently parse, but ignore.
355 bool LLParser::ParseDepLibs() {
356 assert(Lex.getKind() == lltok::kw_deplibs);
358 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
359 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
362 if (EatIfPresent(lltok::rsquare))
367 if (ParseStringConstant(Str)) return true;
368 } while (EatIfPresent(lltok::comma));
370 return ParseToken(lltok::rsquare, "expected ']' at end of list");
373 /// ParseUnnamedType:
374 /// ::= LocalVarID '=' 'type' type
375 bool LLParser::ParseUnnamedType() {
376 LocTy TypeLoc = Lex.getLoc();
377 unsigned TypeID = Lex.getUIntVal();
378 Lex.Lex(); // eat LocalVarID;
380 if (ParseToken(lltok::equal, "expected '=' after name") ||
381 ParseToken(lltok::kw_type, "expected 'type' after '='"))
384 Type *Result = nullptr;
385 if (ParseStructDefinition(TypeLoc, "",
386 NumberedTypes[TypeID], Result)) return true;
388 if (!isa<StructType>(Result)) {
389 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
391 return Error(TypeLoc, "non-struct types may not be recursive");
392 Entry.first = Result;
393 Entry.second = SMLoc();
400 /// ::= LocalVar '=' 'type' type
401 bool LLParser::ParseNamedType() {
402 std::string Name = Lex.getStrVal();
403 LocTy NameLoc = Lex.getLoc();
404 Lex.Lex(); // eat LocalVar.
406 if (ParseToken(lltok::equal, "expected '=' after name") ||
407 ParseToken(lltok::kw_type, "expected 'type' after name"))
410 Type *Result = nullptr;
411 if (ParseStructDefinition(NameLoc, Name,
412 NamedTypes[Name], Result)) return true;
414 if (!isa<StructType>(Result)) {
415 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
417 return Error(NameLoc, "non-struct types may not be recursive");
418 Entry.first = Result;
419 Entry.second = SMLoc();
426 /// ::= 'declare' FunctionHeader
427 bool LLParser::ParseDeclare() {
428 assert(Lex.getKind() == lltok::kw_declare);
431 std::vector<std::pair<unsigned, MDNode *>> MDs;
432 while (Lex.getKind() == lltok::MetadataVar) {
435 if (ParseMetadataAttachment(MDK, N))
437 MDs.push_back({MDK, N});
441 if (ParseFunctionHeader(F, false))
444 F->addMetadata(MD.first, *MD.second);
449 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
450 bool LLParser::ParseDefine() {
451 assert(Lex.getKind() == lltok::kw_define);
455 return ParseFunctionHeader(F, true) ||
456 ParseOptionalFunctionMetadata(*F) ||
457 ParseFunctionBody(*F);
463 bool LLParser::ParseGlobalType(bool &IsConstant) {
464 if (Lex.getKind() == lltok::kw_constant)
466 else if (Lex.getKind() == lltok::kw_global)
470 return TokError("expected 'global' or 'constant'");
476 bool LLParser::ParseOptionalUnnamedAddr(
477 GlobalVariable::UnnamedAddr &UnnamedAddr) {
478 if (EatIfPresent(lltok::kw_unnamed_addr))
479 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
480 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
481 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
483 UnnamedAddr = GlobalValue::UnnamedAddr::None;
487 /// ParseUnnamedGlobal:
488 /// OptionalVisibility (ALIAS | IFUNC) ...
489 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
490 /// ... -> global variable
491 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
492 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
493 /// ... -> global variable
494 bool LLParser::ParseUnnamedGlobal() {
495 unsigned VarID = NumberedVals.size();
497 LocTy NameLoc = Lex.getLoc();
499 // Handle the GlobalID form.
500 if (Lex.getKind() == lltok::GlobalID) {
501 if (Lex.getUIntVal() != VarID)
502 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
504 Lex.Lex(); // eat GlobalID;
506 if (ParseToken(lltok::equal, "expected '=' after name"))
511 unsigned Linkage, Visibility, DLLStorageClass;
512 GlobalVariable::ThreadLocalMode TLM;
513 GlobalVariable::UnnamedAddr UnnamedAddr;
514 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
515 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
518 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
519 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
520 DLLStorageClass, TLM, UnnamedAddr);
522 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
523 DLLStorageClass, TLM, UnnamedAddr);
526 /// ParseNamedGlobal:
527 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
528 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
529 /// ... -> global variable
530 bool LLParser::ParseNamedGlobal() {
531 assert(Lex.getKind() == lltok::GlobalVar);
532 LocTy NameLoc = Lex.getLoc();
533 std::string Name = Lex.getStrVal();
537 unsigned Linkage, Visibility, DLLStorageClass;
538 GlobalVariable::ThreadLocalMode TLM;
539 GlobalVariable::UnnamedAddr UnnamedAddr;
540 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
541 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
542 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
545 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
546 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
547 DLLStorageClass, TLM, UnnamedAddr);
549 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
550 DLLStorageClass, TLM, UnnamedAddr);
553 bool LLParser::parseComdat() {
554 assert(Lex.getKind() == lltok::ComdatVar);
555 std::string Name = Lex.getStrVal();
556 LocTy NameLoc = Lex.getLoc();
559 if (ParseToken(lltok::equal, "expected '=' here"))
562 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
563 return TokError("expected comdat type");
565 Comdat::SelectionKind SK;
566 switch (Lex.getKind()) {
568 return TokError("unknown selection kind");
572 case lltok::kw_exactmatch:
573 SK = Comdat::ExactMatch;
575 case lltok::kw_largest:
576 SK = Comdat::Largest;
578 case lltok::kw_noduplicates:
579 SK = Comdat::NoDuplicates;
581 case lltok::kw_samesize:
582 SK = Comdat::SameSize;
587 // See if the comdat was forward referenced, if so, use the comdat.
588 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
589 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
590 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
591 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
594 if (I != ComdatSymTab.end())
597 C = M->getOrInsertComdat(Name);
598 C->setSelectionKind(SK);
604 // ::= '!' STRINGCONSTANT
605 bool LLParser::ParseMDString(MDString *&Result) {
607 if (ParseStringConstant(Str)) return true;
608 Result = MDString::get(Context, Str);
613 // ::= '!' MDNodeNumber
614 bool LLParser::ParseMDNodeID(MDNode *&Result) {
615 // !{ ..., !42, ... }
616 LocTy IDLoc = Lex.getLoc();
618 if (ParseUInt32(MID))
621 // If not a forward reference, just return it now.
622 if (NumberedMetadata.count(MID)) {
623 Result = NumberedMetadata[MID];
627 // Otherwise, create MDNode forward reference.
628 auto &FwdRef = ForwardRefMDNodes[MID];
629 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
631 Result = FwdRef.first.get();
632 NumberedMetadata[MID].reset(Result);
636 /// ParseNamedMetadata:
637 /// !foo = !{ !1, !2 }
638 bool LLParser::ParseNamedMetadata() {
639 assert(Lex.getKind() == lltok::MetadataVar);
640 std::string Name = Lex.getStrVal();
643 if (ParseToken(lltok::equal, "expected '=' here") ||
644 ParseToken(lltok::exclaim, "Expected '!' here") ||
645 ParseToken(lltok::lbrace, "Expected '{' here"))
648 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
649 if (Lex.getKind() != lltok::rbrace)
651 if (ParseToken(lltok::exclaim, "Expected '!' here"))
655 if (ParseMDNodeID(N)) return true;
657 } while (EatIfPresent(lltok::comma));
659 return ParseToken(lltok::rbrace, "expected end of metadata node");
662 /// ParseStandaloneMetadata:
664 bool LLParser::ParseStandaloneMetadata() {
665 assert(Lex.getKind() == lltok::exclaim);
667 unsigned MetadataID = 0;
670 if (ParseUInt32(MetadataID) ||
671 ParseToken(lltok::equal, "expected '=' here"))
674 // Detect common error, from old metadata syntax.
675 if (Lex.getKind() == lltok::Type)
676 return TokError("unexpected type in metadata definition");
678 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
679 if (Lex.getKind() == lltok::MetadataVar) {
680 if (ParseSpecializedMDNode(Init, IsDistinct))
682 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
683 ParseMDTuple(Init, IsDistinct))
686 // See if this was forward referenced, if so, handle it.
687 auto FI = ForwardRefMDNodes.find(MetadataID);
688 if (FI != ForwardRefMDNodes.end()) {
689 FI->second.first->replaceAllUsesWith(Init);
690 ForwardRefMDNodes.erase(FI);
692 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
694 if (NumberedMetadata.count(MetadataID))
695 return TokError("Metadata id is already used");
696 NumberedMetadata[MetadataID].reset(Init);
702 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
703 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
704 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
707 /// parseIndirectSymbol:
708 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
709 /// OptionalDLLStorageClass OptionalThreadLocal
710 /// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
715 /// Everything through OptionalUnnamedAddr has already been parsed.
717 bool LLParser::parseIndirectSymbol(
718 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
719 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
720 GlobalVariable::UnnamedAddr UnnamedAddr) {
722 if (Lex.getKind() == lltok::kw_alias)
724 else if (Lex.getKind() == lltok::kw_ifunc)
727 llvm_unreachable("Not an alias or ifunc!");
730 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
732 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
733 return Error(NameLoc, "invalid linkage type for alias");
735 if (!isValidVisibilityForLinkage(Visibility, L))
736 return Error(NameLoc,
737 "symbol with local linkage must have default visibility");
740 LocTy ExplicitTypeLoc = Lex.getLoc();
742 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
746 LocTy AliaseeLoc = Lex.getLoc();
747 if (Lex.getKind() != lltok::kw_bitcast &&
748 Lex.getKind() != lltok::kw_getelementptr &&
749 Lex.getKind() != lltok::kw_addrspacecast &&
750 Lex.getKind() != lltok::kw_inttoptr) {
751 if (ParseGlobalTypeAndValue(Aliasee))
754 // The bitcast dest type is not present, it is implied by the dest type.
758 if (ID.Kind != ValID::t_Constant)
759 return Error(AliaseeLoc, "invalid aliasee");
760 Aliasee = ID.ConstantVal;
763 Type *AliaseeType = Aliasee->getType();
764 auto *PTy = dyn_cast<PointerType>(AliaseeType);
766 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
767 unsigned AddrSpace = PTy->getAddressSpace();
769 if (IsAlias && Ty != PTy->getElementType())
772 "explicit pointee type doesn't match operand's pointee type");
774 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
777 "explicit pointee type should be a function type");
779 GlobalValue *GVal = nullptr;
781 // See if the alias was forward referenced, if so, prepare to replace the
782 // forward reference.
784 GVal = M->getNamedValue(Name);
786 if (!ForwardRefVals.erase(Name))
787 return Error(NameLoc, "redefinition of global '@" + Name + "'");
790 auto I = ForwardRefValIDs.find(NumberedVals.size());
791 if (I != ForwardRefValIDs.end()) {
792 GVal = I->second.first;
793 ForwardRefValIDs.erase(I);
797 // Okay, create the alias but do not insert it into the module yet.
798 std::unique_ptr<GlobalIndirectSymbol> GA;
800 GA.reset(GlobalAlias::create(Ty, AddrSpace,
801 (GlobalValue::LinkageTypes)Linkage, Name,
802 Aliasee, /*Parent*/ nullptr));
804 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
805 (GlobalValue::LinkageTypes)Linkage, Name,
806 Aliasee, /*Parent*/ nullptr));
807 GA->setThreadLocalMode(TLM);
808 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
809 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
810 GA->setUnnamedAddr(UnnamedAddr);
813 NumberedVals.push_back(GA.get());
816 // Verify that types agree.
817 if (GVal->getType() != GA->getType())
820 "forward reference and definition of alias have different types");
822 // If they agree, just RAUW the old value with the alias and remove the
824 GVal->replaceAllUsesWith(GA.get());
825 GVal->eraseFromParent();
828 // Insert into the module, we know its name won't collide now.
830 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
832 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
833 assert(GA->getName() == Name && "Should not be a name conflict!");
835 // The module owns this now
842 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
843 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
844 /// OptionalExternallyInitialized GlobalType Type Const
845 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
846 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
847 /// OptionalExternallyInitialized GlobalType Type Const
849 /// Everything up to and including OptionalUnnamedAddr has been parsed
852 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
853 unsigned Linkage, bool HasLinkage,
854 unsigned Visibility, unsigned DLLStorageClass,
855 GlobalVariable::ThreadLocalMode TLM,
856 GlobalVariable::UnnamedAddr UnnamedAddr) {
857 if (!isValidVisibilityForLinkage(Visibility, Linkage))
858 return Error(NameLoc,
859 "symbol with local linkage must have default visibility");
862 bool IsConstant, IsExternallyInitialized;
863 LocTy IsExternallyInitializedLoc;
867 if (ParseOptionalAddrSpace(AddrSpace) ||
868 ParseOptionalToken(lltok::kw_externally_initialized,
869 IsExternallyInitialized,
870 &IsExternallyInitializedLoc) ||
871 ParseGlobalType(IsConstant) ||
872 ParseType(Ty, TyLoc))
875 // If the linkage is specified and is external, then no initializer is
877 Constant *Init = nullptr;
879 !GlobalValue::isValidDeclarationLinkage(
880 (GlobalValue::LinkageTypes)Linkage)) {
881 if (ParseGlobalValue(Ty, Init))
885 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
886 return Error(TyLoc, "invalid type for global variable");
888 GlobalValue *GVal = nullptr;
890 // See if the global was forward referenced, if so, use the global.
892 GVal = M->getNamedValue(Name);
894 if (!ForwardRefVals.erase(Name))
895 return Error(NameLoc, "redefinition of global '@" + Name + "'");
898 auto I = ForwardRefValIDs.find(NumberedVals.size());
899 if (I != ForwardRefValIDs.end()) {
900 GVal = I->second.first;
901 ForwardRefValIDs.erase(I);
907 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
908 Name, nullptr, GlobalVariable::NotThreadLocal,
911 if (GVal->getValueType() != Ty)
913 "forward reference and definition of global have different types");
915 GV = cast<GlobalVariable>(GVal);
917 // Move the forward-reference to the correct spot in the module.
918 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
922 NumberedVals.push_back(GV);
924 // Set the parsed properties on the global.
926 GV->setInitializer(Init);
927 GV->setConstant(IsConstant);
928 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
929 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
930 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
931 GV->setExternallyInitialized(IsExternallyInitialized);
932 GV->setThreadLocalMode(TLM);
933 GV->setUnnamedAddr(UnnamedAddr);
935 // Parse attributes on the global.
936 while (Lex.getKind() == lltok::comma) {
939 if (Lex.getKind() == lltok::kw_section) {
941 GV->setSection(Lex.getStrVal());
942 if (ParseToken(lltok::StringConstant, "expected global section string"))
944 } else if (Lex.getKind() == lltok::kw_align) {
946 if (ParseOptionalAlignment(Alignment)) return true;
947 GV->setAlignment(Alignment);
948 } else if (Lex.getKind() == lltok::MetadataVar) {
949 if (ParseGlobalObjectMetadataAttachment(*GV))
953 if (parseOptionalComdat(Name, C))
958 return TokError("unknown global variable property!");
965 /// ParseUnnamedAttrGrp
966 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
967 bool LLParser::ParseUnnamedAttrGrp() {
968 assert(Lex.getKind() == lltok::kw_attributes);
969 LocTy AttrGrpLoc = Lex.getLoc();
972 if (Lex.getKind() != lltok::AttrGrpID)
973 return TokError("expected attribute group id");
975 unsigned VarID = Lex.getUIntVal();
976 std::vector<unsigned> unused;
980 if (ParseToken(lltok::equal, "expected '=' here") ||
981 ParseToken(lltok::lbrace, "expected '{' here") ||
982 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
984 ParseToken(lltok::rbrace, "expected end of attribute group"))
987 if (!NumberedAttrBuilders[VarID].hasAttributes())
988 return Error(AttrGrpLoc, "attribute group has no attributes");
993 /// ParseFnAttributeValuePairs
994 /// ::= <attr> | <attr> '=' <value>
995 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
996 std::vector<unsigned> &FwdRefAttrGrps,
997 bool inAttrGrp, LocTy &BuiltinLoc) {
998 bool HaveError = false;
1003 lltok::Kind Token = Lex.getKind();
1004 if (Token == lltok::kw_builtin)
1005 BuiltinLoc = Lex.getLoc();
1008 if (!inAttrGrp) return HaveError;
1009 return Error(Lex.getLoc(), "unterminated attribute group");
1014 case lltok::AttrGrpID: {
1015 // Allow a function to reference an attribute group:
1017 // define void @foo() #1 { ... }
1021 "cannot have an attribute group reference in an attribute group");
1023 unsigned AttrGrpNum = Lex.getUIntVal();
1024 if (inAttrGrp) break;
1026 // Save the reference to the attribute group. We'll fill it in later.
1027 FwdRefAttrGrps.push_back(AttrGrpNum);
1030 // Target-dependent attributes:
1031 case lltok::StringConstant: {
1032 if (ParseStringAttribute(B))
1037 // Target-independent attributes:
1038 case lltok::kw_align: {
1039 // As a hack, we allow function alignment to be initially parsed as an
1040 // attribute on a function declaration/definition or added to an attribute
1041 // group and later moved to the alignment field.
1045 if (ParseToken(lltok::equal, "expected '=' here") ||
1046 ParseUInt32(Alignment))
1049 if (ParseOptionalAlignment(Alignment))
1052 B.addAlignmentAttr(Alignment);
1055 case lltok::kw_alignstack: {
1059 if (ParseToken(lltok::equal, "expected '=' here") ||
1060 ParseUInt32(Alignment))
1063 if (ParseOptionalStackAlignment(Alignment))
1066 B.addStackAlignmentAttr(Alignment);
1069 case lltok::kw_allocsize: {
1070 unsigned ElemSizeArg;
1071 Optional<unsigned> NumElemsArg;
1072 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1073 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1075 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1078 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1079 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1080 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1081 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1082 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1083 case lltok::kw_inaccessiblememonly:
1084 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1085 case lltok::kw_inaccessiblemem_or_argmemonly:
1086 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1087 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1088 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1089 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1090 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1091 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1092 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1093 case lltok::kw_noimplicitfloat:
1094 B.addAttribute(Attribute::NoImplicitFloat); break;
1095 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1096 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1097 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1098 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1099 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1100 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1101 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1102 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1103 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1104 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1105 case lltok::kw_returns_twice:
1106 B.addAttribute(Attribute::ReturnsTwice); break;
1107 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1108 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1109 case lltok::kw_sspstrong:
1110 B.addAttribute(Attribute::StackProtectStrong); break;
1111 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1112 case lltok::kw_sanitize_address:
1113 B.addAttribute(Attribute::SanitizeAddress); break;
1114 case lltok::kw_sanitize_thread:
1115 B.addAttribute(Attribute::SanitizeThread); break;
1116 case lltok::kw_sanitize_memory:
1117 B.addAttribute(Attribute::SanitizeMemory); break;
1118 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1119 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1122 case lltok::kw_inreg:
1123 case lltok::kw_signext:
1124 case lltok::kw_zeroext:
1127 "invalid use of attribute on a function");
1129 case lltok::kw_byval:
1130 case lltok::kw_dereferenceable:
1131 case lltok::kw_dereferenceable_or_null:
1132 case lltok::kw_inalloca:
1133 case lltok::kw_nest:
1134 case lltok::kw_noalias:
1135 case lltok::kw_nocapture:
1136 case lltok::kw_nonnull:
1137 case lltok::kw_returned:
1138 case lltok::kw_sret:
1139 case lltok::kw_swifterror:
1140 case lltok::kw_swiftself:
1143 "invalid use of parameter-only attribute on a function");
1151 //===----------------------------------------------------------------------===//
1152 // GlobalValue Reference/Resolution Routines.
1153 //===----------------------------------------------------------------------===//
1155 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1156 const std::string &Name) {
1157 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1158 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1160 return new GlobalVariable(*M, PTy->getElementType(), false,
1161 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1162 nullptr, GlobalVariable::NotThreadLocal,
1163 PTy->getAddressSpace());
1166 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1167 /// forward reference record if needed. This can return null if the value
1168 /// exists but does not have the right type.
1169 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1171 PointerType *PTy = dyn_cast<PointerType>(Ty);
1173 Error(Loc, "global variable reference must have pointer type");
1177 // Look this name up in the normal function symbol table.
1179 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1181 // If this is a forward reference for the value, see if we already created a
1182 // forward ref record.
1184 auto I = ForwardRefVals.find(Name);
1185 if (I != ForwardRefVals.end())
1186 Val = I->second.first;
1189 // If we have the value in the symbol table or fwd-ref table, return it.
1191 if (Val->getType() == Ty) return Val;
1192 Error(Loc, "'@" + Name + "' defined with type '" +
1193 getTypeString(Val->getType()) + "'");
1197 // Otherwise, create a new forward reference for this value and remember it.
1198 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1199 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1203 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1204 PointerType *PTy = dyn_cast<PointerType>(Ty);
1206 Error(Loc, "global variable reference must have pointer type");
1210 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1212 // If this is a forward reference for the value, see if we already created a
1213 // forward ref record.
1215 auto I = ForwardRefValIDs.find(ID);
1216 if (I != ForwardRefValIDs.end())
1217 Val = I->second.first;
1220 // If we have the value in the symbol table or fwd-ref table, return it.
1222 if (Val->getType() == Ty) return Val;
1223 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1224 getTypeString(Val->getType()) + "'");
1228 // Otherwise, create a new forward reference for this value and remember it.
1229 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1230 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1234 //===----------------------------------------------------------------------===//
1235 // Comdat Reference/Resolution Routines.
1236 //===----------------------------------------------------------------------===//
1238 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1239 // Look this name up in the comdat symbol table.
1240 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1241 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1242 if (I != ComdatSymTab.end())
1245 // Otherwise, create a new forward reference for this value and remember it.
1246 Comdat *C = M->getOrInsertComdat(Name);
1247 ForwardRefComdats[Name] = Loc;
1251 //===----------------------------------------------------------------------===//
1253 //===----------------------------------------------------------------------===//
1255 /// ParseToken - If the current token has the specified kind, eat it and return
1256 /// success. Otherwise, emit the specified error and return failure.
1257 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1258 if (Lex.getKind() != T)
1259 return TokError(ErrMsg);
1264 /// ParseStringConstant
1265 /// ::= StringConstant
1266 bool LLParser::ParseStringConstant(std::string &Result) {
1267 if (Lex.getKind() != lltok::StringConstant)
1268 return TokError("expected string constant");
1269 Result = Lex.getStrVal();
1276 bool LLParser::ParseUInt32(uint32_t &Val) {
1277 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1278 return TokError("expected integer");
1279 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1280 if (Val64 != unsigned(Val64))
1281 return TokError("expected 32-bit integer (too large)");
1289 bool LLParser::ParseUInt64(uint64_t &Val) {
1290 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1291 return TokError("expected integer");
1292 Val = Lex.getAPSIntVal().getLimitedValue();
1298 /// := 'localdynamic'
1299 /// := 'initialexec'
1301 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1302 switch (Lex.getKind()) {
1304 return TokError("expected localdynamic, initialexec or localexec");
1305 case lltok::kw_localdynamic:
1306 TLM = GlobalVariable::LocalDynamicTLSModel;
1308 case lltok::kw_initialexec:
1309 TLM = GlobalVariable::InitialExecTLSModel;
1311 case lltok::kw_localexec:
1312 TLM = GlobalVariable::LocalExecTLSModel;
1320 /// ParseOptionalThreadLocal
1322 /// := 'thread_local'
1323 /// := 'thread_local' '(' tlsmodel ')'
1324 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1325 TLM = GlobalVariable::NotThreadLocal;
1326 if (!EatIfPresent(lltok::kw_thread_local))
1329 TLM = GlobalVariable::GeneralDynamicTLSModel;
1330 if (Lex.getKind() == lltok::lparen) {
1332 return ParseTLSModel(TLM) ||
1333 ParseToken(lltok::rparen, "expected ')' after thread local model");
1338 /// ParseOptionalAddrSpace
1340 /// := 'addrspace' '(' uint32 ')'
1341 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1343 if (!EatIfPresent(lltok::kw_addrspace))
1345 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1346 ParseUInt32(AddrSpace) ||
1347 ParseToken(lltok::rparen, "expected ')' in address space");
1350 /// ParseStringAttribute
1351 /// := StringConstant
1352 /// := StringConstant '=' StringConstant
1353 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1354 std::string Attr = Lex.getStrVal();
1357 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1359 B.addAttribute(Attr, Val);
1363 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1364 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1365 bool HaveError = false;
1370 lltok::Kind Token = Lex.getKind();
1372 default: // End of attributes.
1374 case lltok::StringConstant: {
1375 if (ParseStringAttribute(B))
1379 case lltok::kw_align: {
1381 if (ParseOptionalAlignment(Alignment))
1383 B.addAlignmentAttr(Alignment);
1386 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1387 case lltok::kw_dereferenceable: {
1389 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1391 B.addDereferenceableAttr(Bytes);
1394 case lltok::kw_dereferenceable_or_null: {
1396 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1398 B.addDereferenceableOrNullAttr(Bytes);
1401 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1402 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1403 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1404 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1405 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1406 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1407 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1408 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1409 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1410 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1411 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1412 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1413 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1414 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1415 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1417 case lltok::kw_alignstack:
1418 case lltok::kw_alwaysinline:
1419 case lltok::kw_argmemonly:
1420 case lltok::kw_builtin:
1421 case lltok::kw_inlinehint:
1422 case lltok::kw_jumptable:
1423 case lltok::kw_minsize:
1424 case lltok::kw_naked:
1425 case lltok::kw_nobuiltin:
1426 case lltok::kw_noduplicate:
1427 case lltok::kw_noimplicitfloat:
1428 case lltok::kw_noinline:
1429 case lltok::kw_nonlazybind:
1430 case lltok::kw_noredzone:
1431 case lltok::kw_noreturn:
1432 case lltok::kw_nounwind:
1433 case lltok::kw_optnone:
1434 case lltok::kw_optsize:
1435 case lltok::kw_returns_twice:
1436 case lltok::kw_sanitize_address:
1437 case lltok::kw_sanitize_memory:
1438 case lltok::kw_sanitize_thread:
1440 case lltok::kw_sspreq:
1441 case lltok::kw_sspstrong:
1442 case lltok::kw_safestack:
1443 case lltok::kw_uwtable:
1444 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1452 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1453 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1454 bool HaveError = false;
1459 lltok::Kind Token = Lex.getKind();
1461 default: // End of attributes.
1463 case lltok::StringConstant: {
1464 if (ParseStringAttribute(B))
1468 case lltok::kw_dereferenceable: {
1470 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1472 B.addDereferenceableAttr(Bytes);
1475 case lltok::kw_dereferenceable_or_null: {
1477 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1479 B.addDereferenceableOrNullAttr(Bytes);
1482 case lltok::kw_align: {
1484 if (ParseOptionalAlignment(Alignment))
1486 B.addAlignmentAttr(Alignment);
1489 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1490 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1491 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1492 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1493 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1496 case lltok::kw_byval:
1497 case lltok::kw_inalloca:
1498 case lltok::kw_nest:
1499 case lltok::kw_nocapture:
1500 case lltok::kw_returned:
1501 case lltok::kw_sret:
1502 case lltok::kw_swifterror:
1503 case lltok::kw_swiftself:
1504 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1507 case lltok::kw_alignstack:
1508 case lltok::kw_alwaysinline:
1509 case lltok::kw_argmemonly:
1510 case lltok::kw_builtin:
1511 case lltok::kw_cold:
1512 case lltok::kw_inlinehint:
1513 case lltok::kw_jumptable:
1514 case lltok::kw_minsize:
1515 case lltok::kw_naked:
1516 case lltok::kw_nobuiltin:
1517 case lltok::kw_noduplicate:
1518 case lltok::kw_noimplicitfloat:
1519 case lltok::kw_noinline:
1520 case lltok::kw_nonlazybind:
1521 case lltok::kw_noredzone:
1522 case lltok::kw_noreturn:
1523 case lltok::kw_nounwind:
1524 case lltok::kw_optnone:
1525 case lltok::kw_optsize:
1526 case lltok::kw_returns_twice:
1527 case lltok::kw_sanitize_address:
1528 case lltok::kw_sanitize_memory:
1529 case lltok::kw_sanitize_thread:
1531 case lltok::kw_sspreq:
1532 case lltok::kw_sspstrong:
1533 case lltok::kw_safestack:
1534 case lltok::kw_uwtable:
1535 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1538 case lltok::kw_readnone:
1539 case lltok::kw_readonly:
1540 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1547 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1552 return GlobalValue::ExternalLinkage;
1553 case lltok::kw_private:
1554 return GlobalValue::PrivateLinkage;
1555 case lltok::kw_internal:
1556 return GlobalValue::InternalLinkage;
1557 case lltok::kw_weak:
1558 return GlobalValue::WeakAnyLinkage;
1559 case lltok::kw_weak_odr:
1560 return GlobalValue::WeakODRLinkage;
1561 case lltok::kw_linkonce:
1562 return GlobalValue::LinkOnceAnyLinkage;
1563 case lltok::kw_linkonce_odr:
1564 return GlobalValue::LinkOnceODRLinkage;
1565 case lltok::kw_available_externally:
1566 return GlobalValue::AvailableExternallyLinkage;
1567 case lltok::kw_appending:
1568 return GlobalValue::AppendingLinkage;
1569 case lltok::kw_common:
1570 return GlobalValue::CommonLinkage;
1571 case lltok::kw_extern_weak:
1572 return GlobalValue::ExternalWeakLinkage;
1573 case lltok::kw_external:
1574 return GlobalValue::ExternalLinkage;
1578 /// ParseOptionalLinkage
1585 /// ::= 'linkonce_odr'
1586 /// ::= 'available_externally'
1589 /// ::= 'extern_weak'
1591 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1592 unsigned &Visibility,
1593 unsigned &DLLStorageClass) {
1594 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1597 ParseOptionalVisibility(Visibility);
1598 ParseOptionalDLLStorageClass(DLLStorageClass);
1602 /// ParseOptionalVisibility
1608 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1609 switch (Lex.getKind()) {
1611 Res = GlobalValue::DefaultVisibility;
1613 case lltok::kw_default:
1614 Res = GlobalValue::DefaultVisibility;
1616 case lltok::kw_hidden:
1617 Res = GlobalValue::HiddenVisibility;
1619 case lltok::kw_protected:
1620 Res = GlobalValue::ProtectedVisibility;
1626 /// ParseOptionalDLLStorageClass
1631 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1632 switch (Lex.getKind()) {
1634 Res = GlobalValue::DefaultStorageClass;
1636 case lltok::kw_dllimport:
1637 Res = GlobalValue::DLLImportStorageClass;
1639 case lltok::kw_dllexport:
1640 Res = GlobalValue::DLLExportStorageClass;
1646 /// ParseOptionalCallingConv
1650 /// ::= 'intel_ocl_bicc'
1652 /// ::= 'x86_stdcallcc'
1653 /// ::= 'x86_fastcallcc'
1654 /// ::= 'x86_thiscallcc'
1655 /// ::= 'x86_vectorcallcc'
1656 /// ::= 'arm_apcscc'
1657 /// ::= 'arm_aapcscc'
1658 /// ::= 'arm_aapcs_vfpcc'
1659 /// ::= 'msp430_intrcc'
1660 /// ::= 'avr_intrcc'
1661 /// ::= 'avr_signalcc'
1662 /// ::= 'ptx_kernel'
1663 /// ::= 'ptx_device'
1665 /// ::= 'spir_kernel'
1666 /// ::= 'x86_64_sysvcc'
1667 /// ::= 'x86_64_win64cc'
1668 /// ::= 'webkit_jscc'
1670 /// ::= 'preserve_mostcc'
1671 /// ::= 'preserve_allcc'
1674 /// ::= 'x86_intrcc'
1677 /// ::= 'cxx_fast_tlscc'
1679 /// ::= 'amdgpu_tcs'
1680 /// ::= 'amdgpu_tes'
1684 /// ::= 'amdgpu_kernel'
1687 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1688 switch (Lex.getKind()) {
1689 default: CC = CallingConv::C; return false;
1690 case lltok::kw_ccc: CC = CallingConv::C; break;
1691 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1692 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1693 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1694 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1695 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1696 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1697 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1698 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1699 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1700 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1701 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1702 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1703 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1704 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1705 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1706 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1707 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1708 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1709 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1710 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1711 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1712 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1713 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1714 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1715 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1716 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1717 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1718 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1719 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1720 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1721 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1722 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1723 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1724 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1725 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1726 case lltok::kw_cc: {
1728 return ParseUInt32(CC);
1736 /// ParseMetadataAttachment
1738 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1739 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1741 std::string Name = Lex.getStrVal();
1742 Kind = M->getMDKindID(Name);
1745 return ParseMDNode(MD);
1748 /// ParseInstructionMetadata
1749 /// ::= !dbg !42 (',' !dbg !57)*
1750 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1752 if (Lex.getKind() != lltok::MetadataVar)
1753 return TokError("expected metadata after comma");
1757 if (ParseMetadataAttachment(MDK, N))
1760 Inst.setMetadata(MDK, N);
1761 if (MDK == LLVMContext::MD_tbaa)
1762 InstsWithTBAATag.push_back(&Inst);
1764 // If this is the end of the list, we're done.
1765 } while (EatIfPresent(lltok::comma));
1769 /// ParseGlobalObjectMetadataAttachment
1771 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1774 if (ParseMetadataAttachment(MDK, N))
1777 GO.addMetadata(MDK, *N);
1781 /// ParseOptionalFunctionMetadata
1783 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1784 while (Lex.getKind() == lltok::MetadataVar)
1785 if (ParseGlobalObjectMetadataAttachment(F))
1790 /// ParseOptionalAlignment
1793 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1795 if (!EatIfPresent(lltok::kw_align))
1797 LocTy AlignLoc = Lex.getLoc();
1798 if (ParseUInt32(Alignment)) return true;
1799 if (!isPowerOf2_32(Alignment))
1800 return Error(AlignLoc, "alignment is not a power of two");
1801 if (Alignment > Value::MaximumAlignment)
1802 return Error(AlignLoc, "huge alignments are not supported yet");
1806 /// ParseOptionalDerefAttrBytes
1808 /// ::= AttrKind '(' 4 ')'
1810 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1811 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1813 assert((AttrKind == lltok::kw_dereferenceable ||
1814 AttrKind == lltok::kw_dereferenceable_or_null) &&
1818 if (!EatIfPresent(AttrKind))
1820 LocTy ParenLoc = Lex.getLoc();
1821 if (!EatIfPresent(lltok::lparen))
1822 return Error(ParenLoc, "expected '('");
1823 LocTy DerefLoc = Lex.getLoc();
1824 if (ParseUInt64(Bytes)) return true;
1825 ParenLoc = Lex.getLoc();
1826 if (!EatIfPresent(lltok::rparen))
1827 return Error(ParenLoc, "expected ')'");
1829 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1833 /// ParseOptionalCommaAlign
1837 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1839 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1840 bool &AteExtraComma) {
1841 AteExtraComma = false;
1842 while (EatIfPresent(lltok::comma)) {
1843 // Metadata at the end is an early exit.
1844 if (Lex.getKind() == lltok::MetadataVar) {
1845 AteExtraComma = true;
1849 if (Lex.getKind() != lltok::kw_align)
1850 return Error(Lex.getLoc(), "expected metadata or 'align'");
1852 if (ParseOptionalAlignment(Alignment)) return true;
1858 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1859 Optional<unsigned> &HowManyArg) {
1862 auto StartParen = Lex.getLoc();
1863 if (!EatIfPresent(lltok::lparen))
1864 return Error(StartParen, "expected '('");
1866 if (ParseUInt32(BaseSizeArg))
1869 if (EatIfPresent(lltok::comma)) {
1870 auto HowManyAt = Lex.getLoc();
1872 if (ParseUInt32(HowMany))
1874 if (HowMany == BaseSizeArg)
1875 return Error(HowManyAt,
1876 "'allocsize' indices can't refer to the same parameter");
1877 HowManyArg = HowMany;
1881 auto EndParen = Lex.getLoc();
1882 if (!EatIfPresent(lltok::rparen))
1883 return Error(EndParen, "expected ')'");
1887 /// ParseScopeAndOrdering
1888 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1891 /// This sets Scope and Ordering to the parsed values.
1892 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1893 AtomicOrdering &Ordering) {
1897 Scope = CrossThread;
1898 if (EatIfPresent(lltok::kw_singlethread))
1899 Scope = SingleThread;
1901 return ParseOrdering(Ordering);
1905 /// ::= AtomicOrdering
1907 /// This sets Ordering to the parsed value.
1908 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1909 switch (Lex.getKind()) {
1910 default: return TokError("Expected ordering on atomic instruction");
1911 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1912 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1913 // Not specified yet:
1914 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1915 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1916 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1917 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1918 case lltok::kw_seq_cst:
1919 Ordering = AtomicOrdering::SequentiallyConsistent;
1926 /// ParseOptionalStackAlignment
1928 /// ::= 'alignstack' '(' 4 ')'
1929 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1931 if (!EatIfPresent(lltok::kw_alignstack))
1933 LocTy ParenLoc = Lex.getLoc();
1934 if (!EatIfPresent(lltok::lparen))
1935 return Error(ParenLoc, "expected '('");
1936 LocTy AlignLoc = Lex.getLoc();
1937 if (ParseUInt32(Alignment)) return true;
1938 ParenLoc = Lex.getLoc();
1939 if (!EatIfPresent(lltok::rparen))
1940 return Error(ParenLoc, "expected ')'");
1941 if (!isPowerOf2_32(Alignment))
1942 return Error(AlignLoc, "stack alignment is not a power of two");
1946 /// ParseIndexList - This parses the index list for an insert/extractvalue
1947 /// instruction. This sets AteExtraComma in the case where we eat an extra
1948 /// comma at the end of the line and find that it is followed by metadata.
1949 /// Clients that don't allow metadata can call the version of this function that
1950 /// only takes one argument.
1953 /// ::= (',' uint32)+
1955 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1956 bool &AteExtraComma) {
1957 AteExtraComma = false;
1959 if (Lex.getKind() != lltok::comma)
1960 return TokError("expected ',' as start of index list");
1962 while (EatIfPresent(lltok::comma)) {
1963 if (Lex.getKind() == lltok::MetadataVar) {
1964 if (Indices.empty()) return TokError("expected index");
1965 AteExtraComma = true;
1969 if (ParseUInt32(Idx)) return true;
1970 Indices.push_back(Idx);
1976 //===----------------------------------------------------------------------===//
1978 //===----------------------------------------------------------------------===//
1980 /// ParseType - Parse a type.
1981 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1982 SMLoc TypeLoc = Lex.getLoc();
1983 switch (Lex.getKind()) {
1985 return TokError(Msg);
1987 // Type ::= 'float' | 'void' (etc)
1988 Result = Lex.getTyVal();
1992 // Type ::= StructType
1993 if (ParseAnonStructType(Result, false))
1996 case lltok::lsquare:
1997 // Type ::= '[' ... ']'
1998 Lex.Lex(); // eat the lsquare.
1999 if (ParseArrayVectorType(Result, false))
2002 case lltok::less: // Either vector or packed struct.
2003 // Type ::= '<' ... '>'
2005 if (Lex.getKind() == lltok::lbrace) {
2006 if (ParseAnonStructType(Result, true) ||
2007 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2009 } else if (ParseArrayVectorType(Result, true))
2012 case lltok::LocalVar: {
2014 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2016 // If the type hasn't been defined yet, create a forward definition and
2017 // remember where that forward def'n was seen (in case it never is defined).
2019 Entry.first = StructType::create(Context, Lex.getStrVal());
2020 Entry.second = Lex.getLoc();
2022 Result = Entry.first;
2027 case lltok::LocalVarID: {
2029 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2031 // If the type hasn't been defined yet, create a forward definition and
2032 // remember where that forward def'n was seen (in case it never is defined).
2034 Entry.first = StructType::create(Context);
2035 Entry.second = Lex.getLoc();
2037 Result = Entry.first;
2043 // Parse the type suffixes.
2045 switch (Lex.getKind()) {
2048 if (!AllowVoid && Result->isVoidTy())
2049 return Error(TypeLoc, "void type only allowed for function results");
2052 // Type ::= Type '*'
2054 if (Result->isLabelTy())
2055 return TokError("basic block pointers are invalid");
2056 if (Result->isVoidTy())
2057 return TokError("pointers to void are invalid - use i8* instead");
2058 if (!PointerType::isValidElementType(Result))
2059 return TokError("pointer to this type is invalid");
2060 Result = PointerType::getUnqual(Result);
2064 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2065 case lltok::kw_addrspace: {
2066 if (Result->isLabelTy())
2067 return TokError("basic block pointers are invalid");
2068 if (Result->isVoidTy())
2069 return TokError("pointers to void are invalid; use i8* instead");
2070 if (!PointerType::isValidElementType(Result))
2071 return TokError("pointer to this type is invalid");
2073 if (ParseOptionalAddrSpace(AddrSpace) ||
2074 ParseToken(lltok::star, "expected '*' in address space"))
2077 Result = PointerType::get(Result, AddrSpace);
2081 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2083 if (ParseFunctionType(Result))
2090 /// ParseParameterList
2092 /// ::= '(' Arg (',' Arg)* ')'
2094 /// ::= Type OptionalAttributes Value OptionalAttributes
2095 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2096 PerFunctionState &PFS, bool IsMustTailCall,
2097 bool InVarArgsFunc) {
2098 if (ParseToken(lltok::lparen, "expected '(' in call"))
2101 unsigned AttrIndex = 1;
2102 while (Lex.getKind() != lltok::rparen) {
2103 // If this isn't the first argument, we need a comma.
2104 if (!ArgList.empty() &&
2105 ParseToken(lltok::comma, "expected ',' in argument list"))
2108 // Parse an ellipsis if this is a musttail call in a variadic function.
2109 if (Lex.getKind() == lltok::dotdotdot) {
2110 const char *Msg = "unexpected ellipsis in argument list for ";
2111 if (!IsMustTailCall)
2112 return TokError(Twine(Msg) + "non-musttail call");
2114 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2115 Lex.Lex(); // Lex the '...', it is purely for readability.
2116 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2119 // Parse the argument.
2121 Type *ArgTy = nullptr;
2122 AttrBuilder ArgAttrs;
2124 if (ParseType(ArgTy, ArgLoc))
2127 if (ArgTy->isMetadataTy()) {
2128 if (ParseMetadataAsValue(V, PFS))
2131 // Otherwise, handle normal operands.
2132 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2135 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2140 if (IsMustTailCall && InVarArgsFunc)
2141 return TokError("expected '...' at end of argument list for musttail call "
2142 "in varargs function");
2144 Lex.Lex(); // Lex the ')'.
2148 /// ParseOptionalOperandBundles
2150 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2153 /// ::= bundle-tag '(' ')'
2154 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2156 /// bundle-tag ::= String Constant
2157 bool LLParser::ParseOptionalOperandBundles(
2158 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2159 LocTy BeginLoc = Lex.getLoc();
2160 if (!EatIfPresent(lltok::lsquare))
2163 while (Lex.getKind() != lltok::rsquare) {
2164 // If this isn't the first operand bundle, we need a comma.
2165 if (!BundleList.empty() &&
2166 ParseToken(lltok::comma, "expected ',' in input list"))
2170 if (ParseStringConstant(Tag))
2173 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2176 std::vector<Value *> Inputs;
2177 while (Lex.getKind() != lltok::rparen) {
2178 // If this isn't the first input, we need a comma.
2179 if (!Inputs.empty() &&
2180 ParseToken(lltok::comma, "expected ',' in input list"))
2184 Value *Input = nullptr;
2185 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2187 Inputs.push_back(Input);
2190 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2192 Lex.Lex(); // Lex the ')'.
2195 if (BundleList.empty())
2196 return Error(BeginLoc, "operand bundle set must not be empty");
2198 Lex.Lex(); // Lex the ']'.
2202 /// ParseArgumentList - Parse the argument list for a function type or function
2204 /// ::= '(' ArgTypeListI ')'
2208 /// ::= ArgTypeList ',' '...'
2209 /// ::= ArgType (',' ArgType)*
2211 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2214 assert(Lex.getKind() == lltok::lparen);
2215 Lex.Lex(); // eat the (.
2217 if (Lex.getKind() == lltok::rparen) {
2219 } else if (Lex.getKind() == lltok::dotdotdot) {
2223 LocTy TypeLoc = Lex.getLoc();
2224 Type *ArgTy = nullptr;
2228 if (ParseType(ArgTy) ||
2229 ParseOptionalParamAttrs(Attrs)) return true;
2231 if (ArgTy->isVoidTy())
2232 return Error(TypeLoc, "argument can not have void type");
2234 if (Lex.getKind() == lltok::LocalVar) {
2235 Name = Lex.getStrVal();
2239 if (!FunctionType::isValidArgumentType(ArgTy))
2240 return Error(TypeLoc, "invalid type for function argument");
2242 unsigned AttrIndex = 1;
2243 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2244 AttrIndex++, Attrs),
2247 while (EatIfPresent(lltok::comma)) {
2248 // Handle ... at end of arg list.
2249 if (EatIfPresent(lltok::dotdotdot)) {
2254 // Otherwise must be an argument type.
2255 TypeLoc = Lex.getLoc();
2256 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2258 if (ArgTy->isVoidTy())
2259 return Error(TypeLoc, "argument can not have void type");
2261 if (Lex.getKind() == lltok::LocalVar) {
2262 Name = Lex.getStrVal();
2268 if (!ArgTy->isFirstClassType())
2269 return Error(TypeLoc, "invalid type for function argument");
2271 ArgList.emplace_back(
2273 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2278 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2281 /// ParseFunctionType
2282 /// ::= Type ArgumentList OptionalAttrs
2283 bool LLParser::ParseFunctionType(Type *&Result) {
2284 assert(Lex.getKind() == lltok::lparen);
2286 if (!FunctionType::isValidReturnType(Result))
2287 return TokError("invalid function return type");
2289 SmallVector<ArgInfo, 8> ArgList;
2291 if (ParseArgumentList(ArgList, isVarArg))
2294 // Reject names on the arguments lists.
2295 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2296 if (!ArgList[i].Name.empty())
2297 return Error(ArgList[i].Loc, "argument name invalid in function type");
2298 if (ArgList[i].Attrs.hasAttributes(i + 1))
2299 return Error(ArgList[i].Loc,
2300 "argument attributes invalid in function type");
2303 SmallVector<Type*, 16> ArgListTy;
2304 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2305 ArgListTy.push_back(ArgList[i].Ty);
2307 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2311 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2313 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2314 SmallVector<Type*, 8> Elts;
2315 if (ParseStructBody(Elts)) return true;
2317 Result = StructType::get(Context, Elts, Packed);
2321 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2322 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2323 std::pair<Type*, LocTy> &Entry,
2325 // If the type was already defined, diagnose the redefinition.
2326 if (Entry.first && !Entry.second.isValid())
2327 return Error(TypeLoc, "redefinition of type");
2329 // If we have opaque, just return without filling in the definition for the
2330 // struct. This counts as a definition as far as the .ll file goes.
2331 if (EatIfPresent(lltok::kw_opaque)) {
2332 // This type is being defined, so clear the location to indicate this.
2333 Entry.second = SMLoc();
2335 // If this type number has never been uttered, create it.
2337 Entry.first = StructType::create(Context, Name);
2338 ResultTy = Entry.first;
2342 // If the type starts with '<', then it is either a packed struct or a vector.
2343 bool isPacked = EatIfPresent(lltok::less);
2345 // If we don't have a struct, then we have a random type alias, which we
2346 // accept for compatibility with old files. These types are not allowed to be
2347 // forward referenced and not allowed to be recursive.
2348 if (Lex.getKind() != lltok::lbrace) {
2350 return Error(TypeLoc, "forward references to non-struct type");
2354 return ParseArrayVectorType(ResultTy, true);
2355 return ParseType(ResultTy);
2358 // This type is being defined, so clear the location to indicate this.
2359 Entry.second = SMLoc();
2361 // If this type number has never been uttered, create it.
2363 Entry.first = StructType::create(Context, Name);
2365 StructType *STy = cast<StructType>(Entry.first);
2367 SmallVector<Type*, 8> Body;
2368 if (ParseStructBody(Body) ||
2369 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2372 STy->setBody(Body, isPacked);
2377 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2380 /// ::= '{' Type (',' Type)* '}'
2381 /// ::= '<' '{' '}' '>'
2382 /// ::= '<' '{' Type (',' Type)* '}' '>'
2383 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2384 assert(Lex.getKind() == lltok::lbrace);
2385 Lex.Lex(); // Consume the '{'
2387 // Handle the empty struct.
2388 if (EatIfPresent(lltok::rbrace))
2391 LocTy EltTyLoc = Lex.getLoc();
2393 if (ParseType(Ty)) return true;
2396 if (!StructType::isValidElementType(Ty))
2397 return Error(EltTyLoc, "invalid element type for struct");
2399 while (EatIfPresent(lltok::comma)) {
2400 EltTyLoc = Lex.getLoc();
2401 if (ParseType(Ty)) return true;
2403 if (!StructType::isValidElementType(Ty))
2404 return Error(EltTyLoc, "invalid element type for struct");
2409 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2412 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2413 /// token has already been consumed.
2415 /// ::= '[' APSINTVAL 'x' Types ']'
2416 /// ::= '<' APSINTVAL 'x' Types '>'
2417 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2418 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2419 Lex.getAPSIntVal().getBitWidth() > 64)
2420 return TokError("expected number in address space");
2422 LocTy SizeLoc = Lex.getLoc();
2423 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2426 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2429 LocTy TypeLoc = Lex.getLoc();
2430 Type *EltTy = nullptr;
2431 if (ParseType(EltTy)) return true;
2433 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2434 "expected end of sequential type"))
2439 return Error(SizeLoc, "zero element vector is illegal");
2440 if ((unsigned)Size != Size)
2441 return Error(SizeLoc, "size too large for vector");
2442 if (!VectorType::isValidElementType(EltTy))
2443 return Error(TypeLoc, "invalid vector element type");
2444 Result = VectorType::get(EltTy, unsigned(Size));
2446 if (!ArrayType::isValidElementType(EltTy))
2447 return Error(TypeLoc, "invalid array element type");
2448 Result = ArrayType::get(EltTy, Size);
2453 //===----------------------------------------------------------------------===//
2454 // Function Semantic Analysis.
2455 //===----------------------------------------------------------------------===//
2457 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2459 : P(p), F(f), FunctionNumber(functionNumber) {
2461 // Insert unnamed arguments into the NumberedVals list.
2462 for (Argument &A : F.args())
2464 NumberedVals.push_back(&A);
2467 LLParser::PerFunctionState::~PerFunctionState() {
2468 // If there were any forward referenced non-basicblock values, delete them.
2470 for (const auto &P : ForwardRefVals) {
2471 if (isa<BasicBlock>(P.second.first))
2473 P.second.first->replaceAllUsesWith(
2474 UndefValue::get(P.second.first->getType()));
2475 delete P.second.first;
2478 for (const auto &P : ForwardRefValIDs) {
2479 if (isa<BasicBlock>(P.second.first))
2481 P.second.first->replaceAllUsesWith(
2482 UndefValue::get(P.second.first->getType()));
2483 delete P.second.first;
2487 bool LLParser::PerFunctionState::FinishFunction() {
2488 if (!ForwardRefVals.empty())
2489 return P.Error(ForwardRefVals.begin()->second.second,
2490 "use of undefined value '%" + ForwardRefVals.begin()->first +
2492 if (!ForwardRefValIDs.empty())
2493 return P.Error(ForwardRefValIDs.begin()->second.second,
2494 "use of undefined value '%" +
2495 Twine(ForwardRefValIDs.begin()->first) + "'");
2499 /// GetVal - Get a value with the specified name or ID, creating a
2500 /// forward reference record if needed. This can return null if the value
2501 /// exists but does not have the right type.
2502 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2504 // Look this name up in the normal function symbol table.
2505 Value *Val = F.getValueSymbolTable()->lookup(Name);
2507 // If this is a forward reference for the value, see if we already created a
2508 // forward ref record.
2510 auto I = ForwardRefVals.find(Name);
2511 if (I != ForwardRefVals.end())
2512 Val = I->second.first;
2515 // If we have the value in the symbol table or fwd-ref table, return it.
2517 if (Val->getType() == Ty) return Val;
2518 if (Ty->isLabelTy())
2519 P.Error(Loc, "'%" + Name + "' is not a basic block");
2521 P.Error(Loc, "'%" + Name + "' defined with type '" +
2522 getTypeString(Val->getType()) + "'");
2526 // Don't make placeholders with invalid type.
2527 if (!Ty->isFirstClassType()) {
2528 P.Error(Loc, "invalid use of a non-first-class type");
2532 // Otherwise, create a new forward reference for this value and remember it.
2534 if (Ty->isLabelTy()) {
2535 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2537 FwdVal = new Argument(Ty, Name);
2540 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2544 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2545 // Look this name up in the normal function symbol table.
2546 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2548 // If this is a forward reference for the value, see if we already created a
2549 // forward ref record.
2551 auto I = ForwardRefValIDs.find(ID);
2552 if (I != ForwardRefValIDs.end())
2553 Val = I->second.first;
2556 // If we have the value in the symbol table or fwd-ref table, return it.
2558 if (Val->getType() == Ty) return Val;
2559 if (Ty->isLabelTy())
2560 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2562 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2563 getTypeString(Val->getType()) + "'");
2567 if (!Ty->isFirstClassType()) {
2568 P.Error(Loc, "invalid use of a non-first-class type");
2572 // Otherwise, create a new forward reference for this value and remember it.
2574 if (Ty->isLabelTy()) {
2575 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2577 FwdVal = new Argument(Ty);
2580 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2584 /// SetInstName - After an instruction is parsed and inserted into its
2585 /// basic block, this installs its name.
2586 bool LLParser::PerFunctionState::SetInstName(int NameID,
2587 const std::string &NameStr,
2588 LocTy NameLoc, Instruction *Inst) {
2589 // If this instruction has void type, it cannot have a name or ID specified.
2590 if (Inst->getType()->isVoidTy()) {
2591 if (NameID != -1 || !NameStr.empty())
2592 return P.Error(NameLoc, "instructions returning void cannot have a name");
2596 // If this was a numbered instruction, verify that the instruction is the
2597 // expected value and resolve any forward references.
2598 if (NameStr.empty()) {
2599 // If neither a name nor an ID was specified, just use the next ID.
2601 NameID = NumberedVals.size();
2603 if (unsigned(NameID) != NumberedVals.size())
2604 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2605 Twine(NumberedVals.size()) + "'");
2607 auto FI = ForwardRefValIDs.find(NameID);
2608 if (FI != ForwardRefValIDs.end()) {
2609 Value *Sentinel = FI->second.first;
2610 if (Sentinel->getType() != Inst->getType())
2611 return P.Error(NameLoc, "instruction forward referenced with type '" +
2612 getTypeString(FI->second.first->getType()) + "'");
2614 Sentinel->replaceAllUsesWith(Inst);
2616 ForwardRefValIDs.erase(FI);
2619 NumberedVals.push_back(Inst);
2623 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2624 auto FI = ForwardRefVals.find(NameStr);
2625 if (FI != ForwardRefVals.end()) {
2626 Value *Sentinel = FI->second.first;
2627 if (Sentinel->getType() != Inst->getType())
2628 return P.Error(NameLoc, "instruction forward referenced with type '" +
2629 getTypeString(FI->second.first->getType()) + "'");
2631 Sentinel->replaceAllUsesWith(Inst);
2633 ForwardRefVals.erase(FI);
2636 // Set the name on the instruction.
2637 Inst->setName(NameStr);
2639 if (Inst->getName() != NameStr)
2640 return P.Error(NameLoc, "multiple definition of local value named '" +
2645 /// GetBB - Get a basic block with the specified name or ID, creating a
2646 /// forward reference record if needed.
2647 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2649 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2650 Type::getLabelTy(F.getContext()), Loc));
2653 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2654 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2655 Type::getLabelTy(F.getContext()), Loc));
2658 /// DefineBB - Define the specified basic block, which is either named or
2659 /// unnamed. If there is an error, this returns null otherwise it returns
2660 /// the block being defined.
2661 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2665 BB = GetBB(NumberedVals.size(), Loc);
2667 BB = GetBB(Name, Loc);
2668 if (!BB) return nullptr; // Already diagnosed error.
2670 // Move the block to the end of the function. Forward ref'd blocks are
2671 // inserted wherever they happen to be referenced.
2672 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2674 // Remove the block from forward ref sets.
2676 ForwardRefValIDs.erase(NumberedVals.size());
2677 NumberedVals.push_back(BB);
2679 // BB forward references are already in the function symbol table.
2680 ForwardRefVals.erase(Name);
2686 //===----------------------------------------------------------------------===//
2688 //===----------------------------------------------------------------------===//
2690 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2691 /// type implied. For example, if we parse "4" we don't know what integer type
2692 /// it has. The value will later be combined with its type and checked for
2693 /// sanity. PFS is used to convert function-local operands of metadata (since
2694 /// metadata operands are not just parsed here but also converted to values).
2695 /// PFS can be null when we are not parsing metadata values inside a function.
2696 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2697 ID.Loc = Lex.getLoc();
2698 switch (Lex.getKind()) {
2699 default: return TokError("expected value token");
2700 case lltok::GlobalID: // @42
2701 ID.UIntVal = Lex.getUIntVal();
2702 ID.Kind = ValID::t_GlobalID;
2704 case lltok::GlobalVar: // @foo
2705 ID.StrVal = Lex.getStrVal();
2706 ID.Kind = ValID::t_GlobalName;
2708 case lltok::LocalVarID: // %42
2709 ID.UIntVal = Lex.getUIntVal();
2710 ID.Kind = ValID::t_LocalID;
2712 case lltok::LocalVar: // %foo
2713 ID.StrVal = Lex.getStrVal();
2714 ID.Kind = ValID::t_LocalName;
2717 ID.APSIntVal = Lex.getAPSIntVal();
2718 ID.Kind = ValID::t_APSInt;
2720 case lltok::APFloat:
2721 ID.APFloatVal = Lex.getAPFloatVal();
2722 ID.Kind = ValID::t_APFloat;
2724 case lltok::kw_true:
2725 ID.ConstantVal = ConstantInt::getTrue(Context);
2726 ID.Kind = ValID::t_Constant;
2728 case lltok::kw_false:
2729 ID.ConstantVal = ConstantInt::getFalse(Context);
2730 ID.Kind = ValID::t_Constant;
2732 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2733 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2734 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2735 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2737 case lltok::lbrace: {
2738 // ValID ::= '{' ConstVector '}'
2740 SmallVector<Constant*, 16> Elts;
2741 if (ParseGlobalValueVector(Elts) ||
2742 ParseToken(lltok::rbrace, "expected end of struct constant"))
2745 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2746 ID.UIntVal = Elts.size();
2747 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2748 Elts.size() * sizeof(Elts[0]));
2749 ID.Kind = ValID::t_ConstantStruct;
2753 // ValID ::= '<' ConstVector '>' --> Vector.
2754 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2756 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2758 SmallVector<Constant*, 16> Elts;
2759 LocTy FirstEltLoc = Lex.getLoc();
2760 if (ParseGlobalValueVector(Elts) ||
2762 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2763 ParseToken(lltok::greater, "expected end of constant"))
2766 if (isPackedStruct) {
2767 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2768 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2769 Elts.size() * sizeof(Elts[0]));
2770 ID.UIntVal = Elts.size();
2771 ID.Kind = ValID::t_PackedConstantStruct;
2776 return Error(ID.Loc, "constant vector must not be empty");
2778 if (!Elts[0]->getType()->isIntegerTy() &&
2779 !Elts[0]->getType()->isFloatingPointTy() &&
2780 !Elts[0]->getType()->isPointerTy())
2781 return Error(FirstEltLoc,
2782 "vector elements must have integer, pointer or floating point type");
2784 // Verify that all the vector elements have the same type.
2785 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2786 if (Elts[i]->getType() != Elts[0]->getType())
2787 return Error(FirstEltLoc,
2788 "vector element #" + Twine(i) +
2789 " is not of type '" + getTypeString(Elts[0]->getType()));
2791 ID.ConstantVal = ConstantVector::get(Elts);
2792 ID.Kind = ValID::t_Constant;
2795 case lltok::lsquare: { // Array Constant
2797 SmallVector<Constant*, 16> Elts;
2798 LocTy FirstEltLoc = Lex.getLoc();
2799 if (ParseGlobalValueVector(Elts) ||
2800 ParseToken(lltok::rsquare, "expected end of array constant"))
2803 // Handle empty element.
2805 // Use undef instead of an array because it's inconvenient to determine
2806 // the element type at this point, there being no elements to examine.
2807 ID.Kind = ValID::t_EmptyArray;
2811 if (!Elts[0]->getType()->isFirstClassType())
2812 return Error(FirstEltLoc, "invalid array element type: " +
2813 getTypeString(Elts[0]->getType()));
2815 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2817 // Verify all elements are correct type!
2818 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2819 if (Elts[i]->getType() != Elts[0]->getType())
2820 return Error(FirstEltLoc,
2821 "array element #" + Twine(i) +
2822 " is not of type '" + getTypeString(Elts[0]->getType()));
2825 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2826 ID.Kind = ValID::t_Constant;
2829 case lltok::kw_c: // c "foo"
2831 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2833 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2834 ID.Kind = ValID::t_Constant;
2837 case lltok::kw_asm: {
2838 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2840 bool HasSideEffect, AlignStack, AsmDialect;
2842 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2843 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2844 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2845 ParseStringConstant(ID.StrVal) ||
2846 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2847 ParseToken(lltok::StringConstant, "expected constraint string"))
2849 ID.StrVal2 = Lex.getStrVal();
2850 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2851 (unsigned(AsmDialect)<<2);
2852 ID.Kind = ValID::t_InlineAsm;
2856 case lltok::kw_blockaddress: {
2857 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2862 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2864 ParseToken(lltok::comma, "expected comma in block address expression")||
2865 ParseValID(Label) ||
2866 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2869 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2870 return Error(Fn.Loc, "expected function name in blockaddress");
2871 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2872 return Error(Label.Loc, "expected basic block name in blockaddress");
2874 // Try to find the function (but skip it if it's forward-referenced).
2875 GlobalValue *GV = nullptr;
2876 if (Fn.Kind == ValID::t_GlobalID) {
2877 if (Fn.UIntVal < NumberedVals.size())
2878 GV = NumberedVals[Fn.UIntVal];
2879 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2880 GV = M->getNamedValue(Fn.StrVal);
2882 Function *F = nullptr;
2884 // Confirm that it's actually a function with a definition.
2885 if (!isa<Function>(GV))
2886 return Error(Fn.Loc, "expected function name in blockaddress");
2887 F = cast<Function>(GV);
2888 if (F->isDeclaration())
2889 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2893 // Make a global variable as a placeholder for this reference.
2894 GlobalValue *&FwdRef =
2895 ForwardRefBlockAddresses.insert(std::make_pair(
2897 std::map<ValID, GlobalValue *>()))
2898 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2901 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2902 GlobalValue::InternalLinkage, nullptr, "");
2903 ID.ConstantVal = FwdRef;
2904 ID.Kind = ValID::t_Constant;
2908 // We found the function; now find the basic block. Don't use PFS, since we
2909 // might be inside a constant expression.
2911 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2912 if (Label.Kind == ValID::t_LocalID)
2913 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2915 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2917 return Error(Label.Loc, "referenced value is not a basic block");
2919 if (Label.Kind == ValID::t_LocalID)
2920 return Error(Label.Loc, "cannot take address of numeric label after "
2921 "the function is defined");
2922 BB = dyn_cast_or_null<BasicBlock>(
2923 F->getValueSymbolTable()->lookup(Label.StrVal));
2925 return Error(Label.Loc, "referenced value is not a basic block");
2928 ID.ConstantVal = BlockAddress::get(F, BB);
2929 ID.Kind = ValID::t_Constant;
2933 case lltok::kw_trunc:
2934 case lltok::kw_zext:
2935 case lltok::kw_sext:
2936 case lltok::kw_fptrunc:
2937 case lltok::kw_fpext:
2938 case lltok::kw_bitcast:
2939 case lltok::kw_addrspacecast:
2940 case lltok::kw_uitofp:
2941 case lltok::kw_sitofp:
2942 case lltok::kw_fptoui:
2943 case lltok::kw_fptosi:
2944 case lltok::kw_inttoptr:
2945 case lltok::kw_ptrtoint: {
2946 unsigned Opc = Lex.getUIntVal();
2947 Type *DestTy = nullptr;
2950 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2951 ParseGlobalTypeAndValue(SrcVal) ||
2952 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2953 ParseType(DestTy) ||
2954 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2956 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2957 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2958 getTypeString(SrcVal->getType()) + "' to '" +
2959 getTypeString(DestTy) + "'");
2960 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2962 ID.Kind = ValID::t_Constant;
2965 case lltok::kw_extractvalue: {
2968 SmallVector<unsigned, 4> Indices;
2969 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2970 ParseGlobalTypeAndValue(Val) ||
2971 ParseIndexList(Indices) ||
2972 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2975 if (!Val->getType()->isAggregateType())
2976 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2977 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2978 return Error(ID.Loc, "invalid indices for extractvalue");
2979 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2980 ID.Kind = ValID::t_Constant;
2983 case lltok::kw_insertvalue: {
2985 Constant *Val0, *Val1;
2986 SmallVector<unsigned, 4> Indices;
2987 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2988 ParseGlobalTypeAndValue(Val0) ||
2989 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2990 ParseGlobalTypeAndValue(Val1) ||
2991 ParseIndexList(Indices) ||
2992 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2994 if (!Val0->getType()->isAggregateType())
2995 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2997 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2999 return Error(ID.Loc, "invalid indices for insertvalue");
3000 if (IndexedType != Val1->getType())
3001 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3002 getTypeString(Val1->getType()) +
3003 "' instead of '" + getTypeString(IndexedType) +
3005 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3006 ID.Kind = ValID::t_Constant;
3009 case lltok::kw_icmp:
3010 case lltok::kw_fcmp: {
3011 unsigned PredVal, Opc = Lex.getUIntVal();
3012 Constant *Val0, *Val1;
3014 if (ParseCmpPredicate(PredVal, Opc) ||
3015 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3016 ParseGlobalTypeAndValue(Val0) ||
3017 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3018 ParseGlobalTypeAndValue(Val1) ||
3019 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3022 if (Val0->getType() != Val1->getType())
3023 return Error(ID.Loc, "compare operands must have the same type");
3025 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3027 if (Opc == Instruction::FCmp) {
3028 if (!Val0->getType()->isFPOrFPVectorTy())
3029 return Error(ID.Loc, "fcmp requires floating point operands");
3030 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3032 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3033 if (!Val0->getType()->isIntOrIntVectorTy() &&
3034 !Val0->getType()->getScalarType()->isPointerTy())
3035 return Error(ID.Loc, "icmp requires pointer or integer operands");
3036 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3038 ID.Kind = ValID::t_Constant;
3042 // Binary Operators.
3044 case lltok::kw_fadd:
3046 case lltok::kw_fsub:
3048 case lltok::kw_fmul:
3049 case lltok::kw_udiv:
3050 case lltok::kw_sdiv:
3051 case lltok::kw_fdiv:
3052 case lltok::kw_urem:
3053 case lltok::kw_srem:
3054 case lltok::kw_frem:
3056 case lltok::kw_lshr:
3057 case lltok::kw_ashr: {
3061 unsigned Opc = Lex.getUIntVal();
3062 Constant *Val0, *Val1;
3064 LocTy ModifierLoc = Lex.getLoc();
3065 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3066 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3067 if (EatIfPresent(lltok::kw_nuw))
3069 if (EatIfPresent(lltok::kw_nsw)) {
3071 if (EatIfPresent(lltok::kw_nuw))
3074 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3075 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3076 if (EatIfPresent(lltok::kw_exact))
3079 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3080 ParseGlobalTypeAndValue(Val0) ||
3081 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3082 ParseGlobalTypeAndValue(Val1) ||
3083 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3085 if (Val0->getType() != Val1->getType())
3086 return Error(ID.Loc, "operands of constexpr must have same type");
3087 if (!Val0->getType()->isIntOrIntVectorTy()) {
3089 return Error(ModifierLoc, "nuw only applies to integer operations");
3091 return Error(ModifierLoc, "nsw only applies to integer operations");
3093 // Check that the type is valid for the operator.
3095 case Instruction::Add:
3096 case Instruction::Sub:
3097 case Instruction::Mul:
3098 case Instruction::UDiv:
3099 case Instruction::SDiv:
3100 case Instruction::URem:
3101 case Instruction::SRem:
3102 case Instruction::Shl:
3103 case Instruction::AShr:
3104 case Instruction::LShr:
3105 if (!Val0->getType()->isIntOrIntVectorTy())
3106 return Error(ID.Loc, "constexpr requires integer operands");
3108 case Instruction::FAdd:
3109 case Instruction::FSub:
3110 case Instruction::FMul:
3111 case Instruction::FDiv:
3112 case Instruction::FRem:
3113 if (!Val0->getType()->isFPOrFPVectorTy())
3114 return Error(ID.Loc, "constexpr requires fp operands");
3116 default: llvm_unreachable("Unknown binary operator!");
3119 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3120 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3121 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3122 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3124 ID.Kind = ValID::t_Constant;
3128 // Logical Operations
3131 case lltok::kw_xor: {
3132 unsigned Opc = Lex.getUIntVal();
3133 Constant *Val0, *Val1;
3135 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3136 ParseGlobalTypeAndValue(Val0) ||
3137 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3138 ParseGlobalTypeAndValue(Val1) ||
3139 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3141 if (Val0->getType() != Val1->getType())
3142 return Error(ID.Loc, "operands of constexpr must have same type");
3143 if (!Val0->getType()->isIntOrIntVectorTy())
3144 return Error(ID.Loc,
3145 "constexpr requires integer or integer vector operands");
3146 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3147 ID.Kind = ValID::t_Constant;
3151 case lltok::kw_getelementptr:
3152 case lltok::kw_shufflevector:
3153 case lltok::kw_insertelement:
3154 case lltok::kw_extractelement:
3155 case lltok::kw_select: {
3156 unsigned Opc = Lex.getUIntVal();
3157 SmallVector<Constant*, 16> Elts;
3158 bool InBounds = false;
3162 if (Opc == Instruction::GetElementPtr)
3163 InBounds = EatIfPresent(lltok::kw_inbounds);
3165 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3168 LocTy ExplicitTypeLoc = Lex.getLoc();
3169 if (Opc == Instruction::GetElementPtr) {
3170 if (ParseType(Ty) ||
3171 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3175 Optional<unsigned> InRangeOp;
3176 if (ParseGlobalValueVector(
3177 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3178 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3181 if (Opc == Instruction::GetElementPtr) {
3182 if (Elts.size() == 0 ||
3183 !Elts[0]->getType()->getScalarType()->isPointerTy())
3184 return Error(ID.Loc, "base of getelementptr must be a pointer");
3186 Type *BaseType = Elts[0]->getType();
3187 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3188 if (Ty != BasePointerType->getElementType())
3191 "explicit pointee type doesn't match operand's pointee type");
3194 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3196 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3197 for (Constant *Val : Indices) {
3198 Type *ValTy = Val->getType();
3199 if (!ValTy->getScalarType()->isIntegerTy())
3200 return Error(ID.Loc, "getelementptr index must be an integer");
3201 if (ValTy->isVectorTy()) {
3202 unsigned ValNumEl = ValTy->getVectorNumElements();
3203 if (GEPWidth && (ValNumEl != GEPWidth))
3206 "getelementptr vector index has a wrong number of elements");
3207 // GEPWidth may have been unknown because the base is a scalar,
3208 // but it is known now.
3209 GEPWidth = ValNumEl;
3213 SmallPtrSet<Type*, 4> Visited;
3214 if (!Indices.empty() && !Ty->isSized(&Visited))
3215 return Error(ID.Loc, "base element of getelementptr must be sized");
3217 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3218 return Error(ID.Loc, "invalid getelementptr indices");
3221 if (*InRangeOp == 0)
3222 return Error(ID.Loc,
3223 "inrange keyword may not appear on pointer operand");
3227 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3228 InBounds, InRangeOp);
3229 } else if (Opc == Instruction::Select) {
3230 if (Elts.size() != 3)
3231 return Error(ID.Loc, "expected three operands to select");
3232 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3234 return Error(ID.Loc, Reason);
3235 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3236 } else if (Opc == Instruction::ShuffleVector) {
3237 if (Elts.size() != 3)
3238 return Error(ID.Loc, "expected three operands to shufflevector");
3239 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3240 return Error(ID.Loc, "invalid operands to shufflevector");
3242 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3243 } else if (Opc == Instruction::ExtractElement) {
3244 if (Elts.size() != 2)
3245 return Error(ID.Loc, "expected two operands to extractelement");
3246 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3247 return Error(ID.Loc, "invalid extractelement operands");
3248 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3250 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3251 if (Elts.size() != 3)
3252 return Error(ID.Loc, "expected three operands to insertelement");
3253 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3254 return Error(ID.Loc, "invalid insertelement operands");
3256 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3259 ID.Kind = ValID::t_Constant;
3268 /// ParseGlobalValue - Parse a global value with the specified type.
3269 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3273 bool Parsed = ParseValID(ID) ||
3274 ConvertValIDToValue(Ty, ID, V, nullptr);
3275 if (V && !(C = dyn_cast<Constant>(V)))
3276 return Error(ID.Loc, "global values must be constants");
3280 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3282 return ParseType(Ty) ||
3283 ParseGlobalValue(Ty, V);
3286 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3289 LocTy KwLoc = Lex.getLoc();
3290 if (!EatIfPresent(lltok::kw_comdat))
3293 if (EatIfPresent(lltok::lparen)) {
3294 if (Lex.getKind() != lltok::ComdatVar)
3295 return TokError("expected comdat variable");
3296 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3298 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3301 if (GlobalName.empty())
3302 return TokError("comdat cannot be unnamed");
3303 C = getComdat(GlobalName, KwLoc);
3309 /// ParseGlobalValueVector
3311 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3312 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3313 Optional<unsigned> *InRangeOp) {
3315 if (Lex.getKind() == lltok::rbrace ||
3316 Lex.getKind() == lltok::rsquare ||
3317 Lex.getKind() == lltok::greater ||
3318 Lex.getKind() == lltok::rparen)
3322 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3323 *InRangeOp = Elts.size();
3326 if (ParseGlobalTypeAndValue(C)) return true;
3328 } while (EatIfPresent(lltok::comma));
3333 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3334 SmallVector<Metadata *, 16> Elts;
3335 if (ParseMDNodeVector(Elts))
3338 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3345 /// ::= !DILocation(...)
3346 bool LLParser::ParseMDNode(MDNode *&N) {
3347 if (Lex.getKind() == lltok::MetadataVar)
3348 return ParseSpecializedMDNode(N);
3350 return ParseToken(lltok::exclaim, "expected '!' here") ||
3354 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3356 if (Lex.getKind() == lltok::lbrace)
3357 return ParseMDTuple(N);
3360 return ParseMDNodeID(N);
3365 /// Structure to represent an optional metadata field.
3366 template <class FieldTy> struct MDFieldImpl {
3367 typedef MDFieldImpl ImplTy;
3371 void assign(FieldTy Val) {
3373 this->Val = std::move(Val);
3376 explicit MDFieldImpl(FieldTy Default)
3377 : Val(std::move(Default)), Seen(false) {}
3380 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3383 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3384 : ImplTy(Default), Max(Max) {}
3387 struct LineField : public MDUnsignedField {
3388 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3391 struct ColumnField : public MDUnsignedField {
3392 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3395 struct DwarfTagField : public MDUnsignedField {
3396 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3397 DwarfTagField(dwarf::Tag DefaultTag)
3398 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3401 struct DwarfMacinfoTypeField : public MDUnsignedField {
3402 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3403 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3404 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3407 struct DwarfAttEncodingField : public MDUnsignedField {
3408 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3411 struct DwarfVirtualityField : public MDUnsignedField {
3412 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3415 struct DwarfLangField : public MDUnsignedField {
3416 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3419 struct DwarfCCField : public MDUnsignedField {
3420 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3423 struct EmissionKindField : public MDUnsignedField {
3424 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3427 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3428 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3431 struct MDSignedField : public MDFieldImpl<int64_t> {
3435 MDSignedField(int64_t Default = 0)
3436 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3437 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3438 : ImplTy(Default), Min(Min), Max(Max) {}
3441 struct MDBoolField : public MDFieldImpl<bool> {
3442 MDBoolField(bool Default = false) : ImplTy(Default) {}
3445 struct MDField : public MDFieldImpl<Metadata *> {
3448 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3451 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3452 MDConstant() : ImplTy(nullptr) {}
3455 struct MDStringField : public MDFieldImpl<MDString *> {
3457 MDStringField(bool AllowEmpty = true)
3458 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3461 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3462 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3465 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3466 ChecksumKindField() : ImplTy(DIFile::CSK_None) {}
3467 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3470 } // end anonymous namespace
3475 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3476 MDUnsignedField &Result) {
3477 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3478 return TokError("expected unsigned integer");
3480 auto &U = Lex.getAPSIntVal();
3481 if (U.ugt(Result.Max))
3482 return TokError("value for '" + Name + "' too large, limit is " +
3484 Result.assign(U.getZExtValue());
3485 assert(Result.Val <= Result.Max && "Expected value in range");
3491 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3492 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3495 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3496 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3500 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3501 if (Lex.getKind() == lltok::APSInt)
3502 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3504 if (Lex.getKind() != lltok::DwarfTag)
3505 return TokError("expected DWARF tag");
3507 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3508 if (Tag == dwarf::DW_TAG_invalid)
3509 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3510 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3518 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3519 DwarfMacinfoTypeField &Result) {
3520 if (Lex.getKind() == lltok::APSInt)
3521 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3523 if (Lex.getKind() != lltok::DwarfMacinfo)
3524 return TokError("expected DWARF macinfo type");
3526 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3527 if (Macinfo == dwarf::DW_MACINFO_invalid)
3529 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3530 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3532 Result.assign(Macinfo);
3538 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3539 DwarfVirtualityField &Result) {
3540 if (Lex.getKind() == lltok::APSInt)
3541 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3543 if (Lex.getKind() != lltok::DwarfVirtuality)
3544 return TokError("expected DWARF virtuality code");
3546 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3547 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3548 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3549 Lex.getStrVal() + "'");
3550 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3551 Result.assign(Virtuality);
3557 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3558 if (Lex.getKind() == lltok::APSInt)
3559 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3561 if (Lex.getKind() != lltok::DwarfLang)
3562 return TokError("expected DWARF language");
3564 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3566 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3568 assert(Lang <= Result.Max && "Expected valid DWARF language");
3569 Result.assign(Lang);
3575 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3576 if (Lex.getKind() == lltok::APSInt)
3577 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3579 if (Lex.getKind() != lltok::DwarfCC)
3580 return TokError("expected DWARF calling convention");
3582 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3584 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3586 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3593 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3594 if (Lex.getKind() == lltok::APSInt)
3595 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3597 if (Lex.getKind() != lltok::EmissionKind)
3598 return TokError("expected emission kind");
3600 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3602 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3604 assert(*Kind <= Result.Max && "Expected valid emission kind");
3605 Result.assign(*Kind);
3611 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3612 DwarfAttEncodingField &Result) {
3613 if (Lex.getKind() == lltok::APSInt)
3614 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3616 if (Lex.getKind() != lltok::DwarfAttEncoding)
3617 return TokError("expected DWARF type attribute encoding");
3619 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3621 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3622 Lex.getStrVal() + "'");
3623 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3624 Result.assign(Encoding);
3631 /// ::= DIFlagVector
3632 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3634 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3636 // Parser for a single flag.
3637 auto parseFlag = [&](DINode::DIFlags &Val) {
3638 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
3639 uint32_t TempVal = static_cast<uint32_t>(Val);
3640 bool Res = ParseUInt32(TempVal);
3641 Val = static_cast<DINode::DIFlags>(TempVal);
3645 if (Lex.getKind() != lltok::DIFlag)
3646 return TokError("expected debug info flag");
3648 Val = DINode::getFlag(Lex.getStrVal());
3650 return TokError(Twine("invalid debug info flag flag '") +
3651 Lex.getStrVal() + "'");
3656 // Parse the flags and combine them together.
3657 DINode::DIFlags Combined = DINode::FlagZero;
3659 DINode::DIFlags Val;
3663 } while (EatIfPresent(lltok::bar));
3665 Result.assign(Combined);
3670 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3671 MDSignedField &Result) {
3672 if (Lex.getKind() != lltok::APSInt)
3673 return TokError("expected signed integer");
3675 auto &S = Lex.getAPSIntVal();
3677 return TokError("value for '" + Name + "' too small, limit is " +
3680 return TokError("value for '" + Name + "' too large, limit is " +
3682 Result.assign(S.getExtValue());
3683 assert(Result.Val >= Result.Min && "Expected value in range");
3684 assert(Result.Val <= Result.Max && "Expected value in range");
3690 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3691 switch (Lex.getKind()) {
3693 return TokError("expected 'true' or 'false'");
3694 case lltok::kw_true:
3695 Result.assign(true);
3697 case lltok::kw_false:
3698 Result.assign(false);
3706 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3707 if (Lex.getKind() == lltok::kw_null) {
3708 if (!Result.AllowNull)
3709 return TokError("'" + Name + "' cannot be null");
3711 Result.assign(nullptr);
3716 if (ParseMetadata(MD, nullptr))
3724 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3725 LocTy ValueLoc = Lex.getLoc();
3727 if (ParseStringConstant(S))
3730 if (!Result.AllowEmpty && S.empty())
3731 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3733 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3738 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3739 SmallVector<Metadata *, 4> MDs;
3740 if (ParseMDNodeVector(MDs))
3743 Result.assign(std::move(MDs));
3748 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3749 ChecksumKindField &Result) {
3750 if (Lex.getKind() != lltok::ChecksumKind)
3752 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
3754 DIFile::ChecksumKind CSKind = DIFile::getChecksumKind(Lex.getStrVal());
3756 Result.assign(CSKind);
3761 } // end namespace llvm
3763 template <class ParserTy>
3764 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3766 if (Lex.getKind() != lltok::LabelStr)
3767 return TokError("expected field label here");
3771 } while (EatIfPresent(lltok::comma));
3776 template <class ParserTy>
3777 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3778 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3781 if (ParseToken(lltok::lparen, "expected '(' here"))
3783 if (Lex.getKind() != lltok::rparen)
3784 if (ParseMDFieldsImplBody(parseField))
3787 ClosingLoc = Lex.getLoc();
3788 return ParseToken(lltok::rparen, "expected ')' here");
3791 template <class FieldTy>
3792 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3794 return TokError("field '" + Name + "' cannot be specified more than once");
3796 LocTy Loc = Lex.getLoc();
3798 return ParseMDField(Loc, Name, Result);
3801 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3802 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3804 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3805 if (Lex.getStrVal() == #CLASS) \
3806 return Parse##CLASS(N, IsDistinct);
3807 #include "llvm/IR/Metadata.def"
3809 return TokError("expected metadata type");
3812 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3813 #define NOP_FIELD(NAME, TYPE, INIT)
3814 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3816 return Error(ClosingLoc, "missing required field '" #NAME "'");
3817 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3818 if (Lex.getStrVal() == #NAME) \
3819 return ParseMDField(#NAME, NAME);
3820 #define PARSE_MD_FIELDS() \
3821 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3824 if (ParseMDFieldsImpl([&]() -> bool { \
3825 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3826 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3829 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3831 #define GET_OR_DISTINCT(CLASS, ARGS) \
3832 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3834 /// ParseDILocationFields:
3835 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3836 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3837 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3838 OPTIONAL(line, LineField, ); \
3839 OPTIONAL(column, ColumnField, ); \
3840 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3841 OPTIONAL(inlinedAt, MDField, );
3843 #undef VISIT_MD_FIELDS
3845 Result = GET_OR_DISTINCT(
3846 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3850 /// ParseGenericDINode:
3851 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3852 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3853 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3854 REQUIRED(tag, DwarfTagField, ); \
3855 OPTIONAL(header, MDStringField, ); \
3856 OPTIONAL(operands, MDFieldList, );
3858 #undef VISIT_MD_FIELDS
3860 Result = GET_OR_DISTINCT(GenericDINode,
3861 (Context, tag.Val, header.Val, operands.Val));
3865 /// ParseDISubrange:
3866 /// ::= !DISubrange(count: 30, lowerBound: 2)
3867 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3868 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3869 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3870 OPTIONAL(lowerBound, MDSignedField, );
3872 #undef VISIT_MD_FIELDS
3874 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3878 /// ParseDIEnumerator:
3879 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3880 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3881 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3882 REQUIRED(name, MDStringField, ); \
3883 REQUIRED(value, MDSignedField, );
3885 #undef VISIT_MD_FIELDS
3887 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3891 /// ParseDIBasicType:
3892 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3893 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3894 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3895 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3896 OPTIONAL(name, MDStringField, ); \
3897 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3898 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3899 OPTIONAL(encoding, DwarfAttEncodingField, );
3901 #undef VISIT_MD_FIELDS
3903 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3904 align.Val, encoding.Val));
3908 /// ParseDIDerivedType:
3909 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3910 /// line: 7, scope: !1, baseType: !2, size: 32,
3911 /// align: 32, offset: 0, flags: 0, extraData: !3)
3912 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3913 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3914 REQUIRED(tag, DwarfTagField, ); \
3915 OPTIONAL(name, MDStringField, ); \
3916 OPTIONAL(file, MDField, ); \
3917 OPTIONAL(line, LineField, ); \
3918 OPTIONAL(scope, MDField, ); \
3919 REQUIRED(baseType, MDField, ); \
3920 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3921 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3922 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3923 OPTIONAL(flags, DIFlagField, ); \
3924 OPTIONAL(extraData, MDField, );
3926 #undef VISIT_MD_FIELDS
3928 Result = GET_OR_DISTINCT(DIDerivedType,
3929 (Context, tag.Val, name.Val, file.Val, line.Val,
3930 scope.Val, baseType.Val, size.Val, align.Val,
3931 offset.Val, flags.Val, extraData.Val));
3935 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3936 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3937 REQUIRED(tag, DwarfTagField, ); \
3938 OPTIONAL(name, MDStringField, ); \
3939 OPTIONAL(file, MDField, ); \
3940 OPTIONAL(line, LineField, ); \
3941 OPTIONAL(scope, MDField, ); \
3942 OPTIONAL(baseType, MDField, ); \
3943 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3944 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3945 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3946 OPTIONAL(flags, DIFlagField, ); \
3947 OPTIONAL(elements, MDField, ); \
3948 OPTIONAL(runtimeLang, DwarfLangField, ); \
3949 OPTIONAL(vtableHolder, MDField, ); \
3950 OPTIONAL(templateParams, MDField, ); \
3951 OPTIONAL(identifier, MDStringField, );
3953 #undef VISIT_MD_FIELDS
3955 // If this has an identifier try to build an ODR type.
3957 if (auto *CT = DICompositeType::buildODRType(
3958 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3959 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3960 elements.Val, runtimeLang.Val, vtableHolder.Val,
3961 templateParams.Val)) {
3966 // Create a new node, and save it in the context if it belongs in the type
3968 Result = GET_OR_DISTINCT(
3970 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3971 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3972 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3976 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3977 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3978 OPTIONAL(flags, DIFlagField, ); \
3979 OPTIONAL(cc, DwarfCCField, ); \
3980 REQUIRED(types, MDField, );
3982 #undef VISIT_MD_FIELDS
3984 Result = GET_OR_DISTINCT(DISubroutineType,
3985 (Context, flags.Val, cc.Val, types.Val));
3989 /// ParseDIFileType:
3990 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
3991 /// checksumkind: CSK_MD5,
3992 /// checksum: "000102030405060708090a0b0c0d0e0f")
3993 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3994 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3995 REQUIRED(filename, MDStringField, ); \
3996 REQUIRED(directory, MDStringField, ); \
3997 OPTIONAL(checksumkind, ChecksumKindField, ); \
3998 OPTIONAL(checksum, MDStringField, );
4000 #undef VISIT_MD_FIELDS
4002 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4003 checksumkind.Val, checksum.Val));
4007 /// ParseDICompileUnit:
4008 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4009 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4010 /// splitDebugFilename: "abc.debug",
4011 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4012 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4013 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4015 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4017 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4018 REQUIRED(language, DwarfLangField, ); \
4019 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4020 OPTIONAL(producer, MDStringField, ); \
4021 OPTIONAL(isOptimized, MDBoolField, ); \
4022 OPTIONAL(flags, MDStringField, ); \
4023 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4024 OPTIONAL(splitDebugFilename, MDStringField, ); \
4025 OPTIONAL(emissionKind, EmissionKindField, ); \
4026 OPTIONAL(enums, MDField, ); \
4027 OPTIONAL(retainedTypes, MDField, ); \
4028 OPTIONAL(globals, MDField, ); \
4029 OPTIONAL(imports, MDField, ); \
4030 OPTIONAL(macros, MDField, ); \
4031 OPTIONAL(dwoId, MDUnsignedField, ); \
4032 OPTIONAL(splitDebugInlining, MDBoolField, = true);
4034 #undef VISIT_MD_FIELDS
4036 Result = DICompileUnit::getDistinct(
4037 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4038 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4039 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4040 splitDebugInlining.Val);
4044 /// ParseDISubprogram:
4045 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4046 /// file: !1, line: 7, type: !2, isLocal: false,
4047 /// isDefinition: true, scopeLine: 8, containingType: !3,
4048 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4049 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4050 /// isOptimized: false, templateParams: !4, declaration: !5,
4052 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4053 auto Loc = Lex.getLoc();
4054 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4055 OPTIONAL(scope, MDField, ); \
4056 OPTIONAL(name, MDStringField, ); \
4057 OPTIONAL(linkageName, MDStringField, ); \
4058 OPTIONAL(file, MDField, ); \
4059 OPTIONAL(line, LineField, ); \
4060 OPTIONAL(type, MDField, ); \
4061 OPTIONAL(isLocal, MDBoolField, ); \
4062 OPTIONAL(isDefinition, MDBoolField, (true)); \
4063 OPTIONAL(scopeLine, LineField, ); \
4064 OPTIONAL(containingType, MDField, ); \
4065 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4066 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4067 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4068 OPTIONAL(flags, DIFlagField, ); \
4069 OPTIONAL(isOptimized, MDBoolField, ); \
4070 OPTIONAL(unit, MDField, ); \
4071 OPTIONAL(templateParams, MDField, ); \
4072 OPTIONAL(declaration, MDField, ); \
4073 OPTIONAL(variables, MDField, );
4075 #undef VISIT_MD_FIELDS
4077 if (isDefinition.Val && !IsDistinct)
4080 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4082 Result = GET_OR_DISTINCT(
4083 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4084 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4085 scopeLine.Val, containingType.Val, virtuality.Val,
4086 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4087 isOptimized.Val, unit.Val, templateParams.Val,
4088 declaration.Val, variables.Val));
4092 /// ParseDILexicalBlock:
4093 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4094 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4095 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4096 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4097 OPTIONAL(file, MDField, ); \
4098 OPTIONAL(line, LineField, ); \
4099 OPTIONAL(column, ColumnField, );
4101 #undef VISIT_MD_FIELDS
4103 Result = GET_OR_DISTINCT(
4104 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4108 /// ParseDILexicalBlockFile:
4109 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4110 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4111 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4112 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4113 OPTIONAL(file, MDField, ); \
4114 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4116 #undef VISIT_MD_FIELDS
4118 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4119 (Context, scope.Val, file.Val, discriminator.Val));
4123 /// ParseDINamespace:
4124 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4125 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4126 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4127 REQUIRED(scope, MDField, ); \
4128 OPTIONAL(file, MDField, ); \
4129 OPTIONAL(name, MDStringField, ); \
4130 OPTIONAL(line, LineField, ); \
4131 OPTIONAL(exportSymbols, MDBoolField, );
4133 #undef VISIT_MD_FIELDS
4135 Result = GET_OR_DISTINCT(DINamespace,
4136 (Context, scope.Val, file.Val, name.Val, line.Val, exportSymbols.Val));
4141 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4142 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4143 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4144 REQUIRED(type, DwarfMacinfoTypeField, ); \
4145 OPTIONAL(line, LineField, ); \
4146 REQUIRED(name, MDStringField, ); \
4147 OPTIONAL(value, MDStringField, );
4149 #undef VISIT_MD_FIELDS
4151 Result = GET_OR_DISTINCT(DIMacro,
4152 (Context, type.Val, line.Val, name.Val, value.Val));
4156 /// ParseDIMacroFile:
4157 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4158 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4159 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4160 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4161 OPTIONAL(line, LineField, ); \
4162 REQUIRED(file, MDField, ); \
4163 OPTIONAL(nodes, MDField, );
4165 #undef VISIT_MD_FIELDS
4167 Result = GET_OR_DISTINCT(DIMacroFile,
4168 (Context, type.Val, line.Val, file.Val, nodes.Val));
4173 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4174 /// includePath: "/usr/include", isysroot: "/")
4175 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4176 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4177 REQUIRED(scope, MDField, ); \
4178 REQUIRED(name, MDStringField, ); \
4179 OPTIONAL(configMacros, MDStringField, ); \
4180 OPTIONAL(includePath, MDStringField, ); \
4181 OPTIONAL(isysroot, MDStringField, );
4183 #undef VISIT_MD_FIELDS
4185 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4186 configMacros.Val, includePath.Val, isysroot.Val));
4190 /// ParseDITemplateTypeParameter:
4191 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4192 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4193 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4194 OPTIONAL(name, MDStringField, ); \
4195 REQUIRED(type, MDField, );
4197 #undef VISIT_MD_FIELDS
4200 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4204 /// ParseDITemplateValueParameter:
4205 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4206 /// name: "V", type: !1, value: i32 7)
4207 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4208 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4209 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4210 OPTIONAL(name, MDStringField, ); \
4211 OPTIONAL(type, MDField, ); \
4212 REQUIRED(value, MDField, );
4214 #undef VISIT_MD_FIELDS
4216 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4217 (Context, tag.Val, name.Val, type.Val, value.Val));
4221 /// ParseDIGlobalVariable:
4222 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4223 /// file: !1, line: 7, type: !2, isLocal: false,
4224 /// isDefinition: true, declaration: !3, align: 8)
4225 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4226 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4227 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4228 OPTIONAL(scope, MDField, ); \
4229 OPTIONAL(linkageName, MDStringField, ); \
4230 OPTIONAL(file, MDField, ); \
4231 OPTIONAL(line, LineField, ); \
4232 OPTIONAL(type, MDField, ); \
4233 OPTIONAL(isLocal, MDBoolField, ); \
4234 OPTIONAL(isDefinition, MDBoolField, (true)); \
4235 OPTIONAL(declaration, MDField, ); \
4236 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4238 #undef VISIT_MD_FIELDS
4240 Result = GET_OR_DISTINCT(DIGlobalVariable,
4241 (Context, scope.Val, name.Val, linkageName.Val,
4242 file.Val, line.Val, type.Val, isLocal.Val,
4243 isDefinition.Val, declaration.Val, align.Val));
4247 /// ParseDILocalVariable:
4248 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4249 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4251 /// ::= !DILocalVariable(scope: !0, name: "foo",
4252 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4254 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4255 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4256 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4257 OPTIONAL(name, MDStringField, ); \
4258 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4259 OPTIONAL(file, MDField, ); \
4260 OPTIONAL(line, LineField, ); \
4261 OPTIONAL(type, MDField, ); \
4262 OPTIONAL(flags, DIFlagField, ); \
4263 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4265 #undef VISIT_MD_FIELDS
4267 Result = GET_OR_DISTINCT(DILocalVariable,
4268 (Context, scope.Val, name.Val, file.Val, line.Val,
4269 type.Val, arg.Val, flags.Val, align.Val));
4273 /// ParseDIExpression:
4274 /// ::= !DIExpression(0, 7, -1)
4275 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4276 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4279 if (ParseToken(lltok::lparen, "expected '(' here"))
4282 SmallVector<uint64_t, 8> Elements;
4283 if (Lex.getKind() != lltok::rparen)
4285 if (Lex.getKind() == lltok::DwarfOp) {
4286 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4288 Elements.push_back(Op);
4291 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4294 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4295 return TokError("expected unsigned integer");
4297 auto &U = Lex.getAPSIntVal();
4298 if (U.ugt(UINT64_MAX))
4299 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4300 Elements.push_back(U.getZExtValue());
4302 } while (EatIfPresent(lltok::comma));
4304 if (ParseToken(lltok::rparen, "expected ')' here"))
4307 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4311 /// ParseDIGlobalVariableExpression:
4312 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4313 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4315 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4316 REQUIRED(var, MDField, ); \
4317 OPTIONAL(expr, MDField, );
4319 #undef VISIT_MD_FIELDS
4322 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4326 /// ParseDIObjCProperty:
4327 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4328 /// getter: "getFoo", attributes: 7, type: !2)
4329 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4330 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4331 OPTIONAL(name, MDStringField, ); \
4332 OPTIONAL(file, MDField, ); \
4333 OPTIONAL(line, LineField, ); \
4334 OPTIONAL(setter, MDStringField, ); \
4335 OPTIONAL(getter, MDStringField, ); \
4336 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4337 OPTIONAL(type, MDField, );
4339 #undef VISIT_MD_FIELDS
4341 Result = GET_OR_DISTINCT(DIObjCProperty,
4342 (Context, name.Val, file.Val, line.Val, setter.Val,
4343 getter.Val, attributes.Val, type.Val));
4347 /// ParseDIImportedEntity:
4348 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4349 /// line: 7, name: "foo")
4350 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4351 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4352 REQUIRED(tag, DwarfTagField, ); \
4353 REQUIRED(scope, MDField, ); \
4354 OPTIONAL(entity, MDField, ); \
4355 OPTIONAL(line, LineField, ); \
4356 OPTIONAL(name, MDStringField, );
4358 #undef VISIT_MD_FIELDS
4360 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4361 entity.Val, line.Val, name.Val));
4365 #undef PARSE_MD_FIELD
4367 #undef REQUIRE_FIELD
4368 #undef DECLARE_FIELD
4370 /// ParseMetadataAsValue
4371 /// ::= metadata i32 %local
4372 /// ::= metadata i32 @global
4373 /// ::= metadata i32 7
4375 /// ::= metadata !{...}
4376 /// ::= metadata !"string"
4377 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4378 // Note: the type 'metadata' has already been parsed.
4380 if (ParseMetadata(MD, &PFS))
4383 V = MetadataAsValue::get(Context, MD);
4387 /// ParseValueAsMetadata
4391 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4392 PerFunctionState *PFS) {
4395 if (ParseType(Ty, TypeMsg, Loc))
4397 if (Ty->isMetadataTy())
4398 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4401 if (ParseValue(Ty, V, PFS))
4404 MD = ValueAsMetadata::get(V);
4415 /// ::= !DILocation(...)
4416 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4417 if (Lex.getKind() == lltok::MetadataVar) {
4419 if (ParseSpecializedMDNode(N))
4427 if (Lex.getKind() != lltok::exclaim)
4428 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4431 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4435 // ::= '!' STRINGCONSTANT
4436 if (Lex.getKind() == lltok::StringConstant) {
4438 if (ParseMDString(S))
4448 if (ParseMDNodeTail(N))
4454 //===----------------------------------------------------------------------===//
4455 // Function Parsing.
4456 //===----------------------------------------------------------------------===//
4458 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4459 PerFunctionState *PFS) {
4460 if (Ty->isFunctionTy())
4461 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4464 case ValID::t_LocalID:
4465 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4466 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4467 return V == nullptr;
4468 case ValID::t_LocalName:
4469 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4470 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4471 return V == nullptr;
4472 case ValID::t_InlineAsm: {
4473 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4474 return Error(ID.Loc, "invalid type for inline asm constraint string");
4475 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4476 (ID.UIntVal >> 1) & 1,
4477 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4480 case ValID::t_GlobalName:
4481 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4482 return V == nullptr;
4483 case ValID::t_GlobalID:
4484 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4485 return V == nullptr;
4486 case ValID::t_APSInt:
4487 if (!Ty->isIntegerTy())
4488 return Error(ID.Loc, "integer constant must have integer type");
4489 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4490 V = ConstantInt::get(Context, ID.APSIntVal);
4492 case ValID::t_APFloat:
4493 if (!Ty->isFloatingPointTy() ||
4494 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4495 return Error(ID.Loc, "floating point constant invalid for type");
4497 // The lexer has no type info, so builds all half, float, and double FP
4498 // constants as double. Fix this here. Long double does not need this.
4499 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
4502 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
4504 else if (Ty->isFloatTy())
4505 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
4508 V = ConstantFP::get(Context, ID.APFloatVal);
4510 if (V->getType() != Ty)
4511 return Error(ID.Loc, "floating point constant does not have type '" +
4512 getTypeString(Ty) + "'");
4516 if (!Ty->isPointerTy())
4517 return Error(ID.Loc, "null must be a pointer type");
4518 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4520 case ValID::t_Undef:
4521 // FIXME: LabelTy should not be a first-class type.
4522 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4523 return Error(ID.Loc, "invalid type for undef constant");
4524 V = UndefValue::get(Ty);
4526 case ValID::t_EmptyArray:
4527 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4528 return Error(ID.Loc, "invalid empty array initializer");
4529 V = UndefValue::get(Ty);
4532 // FIXME: LabelTy should not be a first-class type.
4533 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4534 return Error(ID.Loc, "invalid type for null constant");
4535 V = Constant::getNullValue(Ty);
4538 if (!Ty->isTokenTy())
4539 return Error(ID.Loc, "invalid type for none constant");
4540 V = Constant::getNullValue(Ty);
4542 case ValID::t_Constant:
4543 if (ID.ConstantVal->getType() != Ty)
4544 return Error(ID.Loc, "constant expression type mismatch");
4548 case ValID::t_ConstantStruct:
4549 case ValID::t_PackedConstantStruct:
4550 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4551 if (ST->getNumElements() != ID.UIntVal)
4552 return Error(ID.Loc,
4553 "initializer with struct type has wrong # elements");
4554 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4555 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4557 // Verify that the elements are compatible with the structtype.
4558 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4559 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4560 return Error(ID.Loc, "element " + Twine(i) +
4561 " of struct initializer doesn't match struct element type");
4563 V = ConstantStruct::get(
4564 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4566 return Error(ID.Loc, "constant expression type mismatch");
4569 llvm_unreachable("Invalid ValID");
4572 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4575 auto Loc = Lex.getLoc();
4576 if (ParseValID(ID, /*PFS=*/nullptr))
4579 case ValID::t_APSInt:
4580 case ValID::t_APFloat:
4581 case ValID::t_Undef:
4582 case ValID::t_Constant:
4583 case ValID::t_ConstantStruct:
4584 case ValID::t_PackedConstantStruct: {
4586 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4588 assert(isa<Constant>(V) && "Expected a constant value");
4589 C = cast<Constant>(V);
4593 return Error(Loc, "expected a constant value");
4597 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4600 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4603 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4605 return ParseType(Ty) ||
4606 ParseValue(Ty, V, PFS);
4609 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4610 PerFunctionState &PFS) {
4613 if (ParseTypeAndValue(V, PFS)) return true;
4614 if (!isa<BasicBlock>(V))
4615 return Error(Loc, "expected a basic block");
4616 BB = cast<BasicBlock>(V);
4621 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4622 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4623 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4624 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4625 // Parse the linkage.
4626 LocTy LinkageLoc = Lex.getLoc();
4629 unsigned Visibility;
4630 unsigned DLLStorageClass;
4631 AttrBuilder RetAttrs;
4634 Type *RetType = nullptr;
4635 LocTy RetTypeLoc = Lex.getLoc();
4636 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4637 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4638 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4641 // Verify that the linkage is ok.
4642 switch ((GlobalValue::LinkageTypes)Linkage) {
4643 case GlobalValue::ExternalLinkage:
4644 break; // always ok.
4645 case GlobalValue::ExternalWeakLinkage:
4647 return Error(LinkageLoc, "invalid linkage for function definition");
4649 case GlobalValue::PrivateLinkage:
4650 case GlobalValue::InternalLinkage:
4651 case GlobalValue::AvailableExternallyLinkage:
4652 case GlobalValue::LinkOnceAnyLinkage:
4653 case GlobalValue::LinkOnceODRLinkage:
4654 case GlobalValue::WeakAnyLinkage:
4655 case GlobalValue::WeakODRLinkage:
4657 return Error(LinkageLoc, "invalid linkage for function declaration");
4659 case GlobalValue::AppendingLinkage:
4660 case GlobalValue::CommonLinkage:
4661 return Error(LinkageLoc, "invalid function linkage type");
4664 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4665 return Error(LinkageLoc,
4666 "symbol with local linkage must have default visibility");
4668 if (!FunctionType::isValidReturnType(RetType))
4669 return Error(RetTypeLoc, "invalid function return type");
4671 LocTy NameLoc = Lex.getLoc();
4673 std::string FunctionName;
4674 if (Lex.getKind() == lltok::GlobalVar) {
4675 FunctionName = Lex.getStrVal();
4676 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4677 unsigned NameID = Lex.getUIntVal();
4679 if (NameID != NumberedVals.size())
4680 return TokError("function expected to be numbered '%" +
4681 Twine(NumberedVals.size()) + "'");
4683 return TokError("expected function name");
4688 if (Lex.getKind() != lltok::lparen)
4689 return TokError("expected '(' in function argument list");
4691 SmallVector<ArgInfo, 8> ArgList;
4693 AttrBuilder FuncAttrs;
4694 std::vector<unsigned> FwdRefAttrGrps;
4696 std::string Section;
4699 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4700 LocTy UnnamedAddrLoc;
4701 Constant *Prefix = nullptr;
4702 Constant *Prologue = nullptr;
4703 Constant *PersonalityFn = nullptr;
4706 if (ParseArgumentList(ArgList, isVarArg) ||
4707 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4708 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4710 (EatIfPresent(lltok::kw_section) &&
4711 ParseStringConstant(Section)) ||
4712 parseOptionalComdat(FunctionName, C) ||
4713 ParseOptionalAlignment(Alignment) ||
4714 (EatIfPresent(lltok::kw_gc) &&
4715 ParseStringConstant(GC)) ||
4716 (EatIfPresent(lltok::kw_prefix) &&
4717 ParseGlobalTypeAndValue(Prefix)) ||
4718 (EatIfPresent(lltok::kw_prologue) &&
4719 ParseGlobalTypeAndValue(Prologue)) ||
4720 (EatIfPresent(lltok::kw_personality) &&
4721 ParseGlobalTypeAndValue(PersonalityFn)))
4724 if (FuncAttrs.contains(Attribute::Builtin))
4725 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4727 // If the alignment was parsed as an attribute, move to the alignment field.
4728 if (FuncAttrs.hasAlignmentAttr()) {
4729 Alignment = FuncAttrs.getAlignment();
4730 FuncAttrs.removeAttribute(Attribute::Alignment);
4733 // Okay, if we got here, the function is syntactically valid. Convert types
4734 // and do semantic checks.
4735 std::vector<Type*> ParamTypeList;
4736 SmallVector<AttributeSet, 8> Attrs;
4738 if (RetAttrs.hasAttributes())
4739 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4740 AttributeSet::ReturnIndex,
4743 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4744 ParamTypeList.push_back(ArgList[i].Ty);
4745 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4746 AttrBuilder B(ArgList[i].Attrs, i + 1);
4747 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4751 if (FuncAttrs.hasAttributes())
4752 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4753 AttributeSet::FunctionIndex,
4756 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4758 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4759 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4762 FunctionType::get(RetType, ParamTypeList, isVarArg);
4763 PointerType *PFT = PointerType::getUnqual(FT);
4766 if (!FunctionName.empty()) {
4767 // If this was a definition of a forward reference, remove the definition
4768 // from the forward reference table and fill in the forward ref.
4769 auto FRVI = ForwardRefVals.find(FunctionName);
4770 if (FRVI != ForwardRefVals.end()) {
4771 Fn = M->getFunction(FunctionName);
4773 return Error(FRVI->second.second, "invalid forward reference to "
4774 "function as global value!");
4775 if (Fn->getType() != PFT)
4776 return Error(FRVI->second.second, "invalid forward reference to "
4777 "function '" + FunctionName + "' with wrong type!");
4779 ForwardRefVals.erase(FRVI);
4780 } else if ((Fn = M->getFunction(FunctionName))) {
4781 // Reject redefinitions.
4782 return Error(NameLoc, "invalid redefinition of function '" +
4783 FunctionName + "'");
4784 } else if (M->getNamedValue(FunctionName)) {
4785 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4789 // If this is a definition of a forward referenced function, make sure the
4791 auto I = ForwardRefValIDs.find(NumberedVals.size());
4792 if (I != ForwardRefValIDs.end()) {
4793 Fn = cast<Function>(I->second.first);
4794 if (Fn->getType() != PFT)
4795 return Error(NameLoc, "type of definition and forward reference of '@" +
4796 Twine(NumberedVals.size()) + "' disagree");
4797 ForwardRefValIDs.erase(I);
4802 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4803 else // Move the forward-reference to the correct spot in the module.
4804 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4806 if (FunctionName.empty())
4807 NumberedVals.push_back(Fn);
4809 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4810 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4811 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4812 Fn->setCallingConv(CC);
4813 Fn->setAttributes(PAL);
4814 Fn->setUnnamedAddr(UnnamedAddr);
4815 Fn->setAlignment(Alignment);
4816 Fn->setSection(Section);
4818 Fn->setPersonalityFn(PersonalityFn);
4819 if (!GC.empty()) Fn->setGC(GC);
4820 Fn->setPrefixData(Prefix);
4821 Fn->setPrologueData(Prologue);
4822 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4824 // Add all of the arguments we parsed to the function.
4825 Function::arg_iterator ArgIt = Fn->arg_begin();
4826 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4827 // If the argument has a name, insert it into the argument symbol table.
4828 if (ArgList[i].Name.empty()) continue;
4830 // Set the name, if it conflicted, it will be auto-renamed.
4831 ArgIt->setName(ArgList[i].Name);
4833 if (ArgIt->getName() != ArgList[i].Name)
4834 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4835 ArgList[i].Name + "'");
4841 // Check the declaration has no block address forward references.
4843 if (FunctionName.empty()) {
4844 ID.Kind = ValID::t_GlobalID;
4845 ID.UIntVal = NumberedVals.size() - 1;
4847 ID.Kind = ValID::t_GlobalName;
4848 ID.StrVal = FunctionName;
4850 auto Blocks = ForwardRefBlockAddresses.find(ID);
4851 if (Blocks != ForwardRefBlockAddresses.end())
4852 return Error(Blocks->first.Loc,
4853 "cannot take blockaddress inside a declaration");
4857 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4859 if (FunctionNumber == -1) {
4860 ID.Kind = ValID::t_GlobalName;
4861 ID.StrVal = F.getName();
4863 ID.Kind = ValID::t_GlobalID;
4864 ID.UIntVal = FunctionNumber;
4867 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4868 if (Blocks == P.ForwardRefBlockAddresses.end())
4871 for (const auto &I : Blocks->second) {
4872 const ValID &BBID = I.first;
4873 GlobalValue *GV = I.second;
4875 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4876 "Expected local id or name");
4878 if (BBID.Kind == ValID::t_LocalName)
4879 BB = GetBB(BBID.StrVal, BBID.Loc);
4881 BB = GetBB(BBID.UIntVal, BBID.Loc);
4883 return P.Error(BBID.Loc, "referenced value is not a basic block");
4885 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4886 GV->eraseFromParent();
4889 P.ForwardRefBlockAddresses.erase(Blocks);
4893 /// ParseFunctionBody
4894 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4895 bool LLParser::ParseFunctionBody(Function &Fn) {
4896 if (Lex.getKind() != lltok::lbrace)
4897 return TokError("expected '{' in function body");
4898 Lex.Lex(); // eat the {.
4900 int FunctionNumber = -1;
4901 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4903 PerFunctionState PFS(*this, Fn, FunctionNumber);
4905 // Resolve block addresses and allow basic blocks to be forward-declared
4906 // within this function.
4907 if (PFS.resolveForwardRefBlockAddresses())
4909 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4911 // We need at least one basic block.
4912 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4913 return TokError("function body requires at least one basic block");
4915 while (Lex.getKind() != lltok::rbrace &&
4916 Lex.getKind() != lltok::kw_uselistorder)
4917 if (ParseBasicBlock(PFS)) return true;
4919 while (Lex.getKind() != lltok::rbrace)
4920 if (ParseUseListOrder(&PFS))
4926 // Verify function is ok.
4927 return PFS.FinishFunction();
4931 /// ::= LabelStr? Instruction*
4932 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4933 // If this basic block starts out with a name, remember it.
4935 LocTy NameLoc = Lex.getLoc();
4936 if (Lex.getKind() == lltok::LabelStr) {
4937 Name = Lex.getStrVal();
4941 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4943 return Error(NameLoc,
4944 "unable to create block named '" + Name + "'");
4946 std::string NameStr;
4948 // Parse the instructions in this block until we get a terminator.
4951 // This instruction may have three possibilities for a name: a) none
4952 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4953 LocTy NameLoc = Lex.getLoc();
4957 if (Lex.getKind() == lltok::LocalVarID) {
4958 NameID = Lex.getUIntVal();
4960 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4962 } else if (Lex.getKind() == lltok::LocalVar) {
4963 NameStr = Lex.getStrVal();
4965 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4969 switch (ParseInstruction(Inst, BB, PFS)) {
4970 default: llvm_unreachable("Unknown ParseInstruction result!");
4971 case InstError: return true;
4973 BB->getInstList().push_back(Inst);
4975 // With a normal result, we check to see if the instruction is followed by
4976 // a comma and metadata.
4977 if (EatIfPresent(lltok::comma))
4978 if (ParseInstructionMetadata(*Inst))
4981 case InstExtraComma:
4982 BB->getInstList().push_back(Inst);
4984 // If the instruction parser ate an extra comma at the end of it, it
4985 // *must* be followed by metadata.
4986 if (ParseInstructionMetadata(*Inst))
4991 // Set the name on the instruction.
4992 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4993 } while (!isa<TerminatorInst>(Inst));
4998 //===----------------------------------------------------------------------===//
4999 // Instruction Parsing.
5000 //===----------------------------------------------------------------------===//
5002 /// ParseInstruction - Parse one of the many different instructions.
5004 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5005 PerFunctionState &PFS) {
5006 lltok::Kind Token = Lex.getKind();
5007 if (Token == lltok::Eof)
5008 return TokError("found end of file when expecting more instructions");
5009 LocTy Loc = Lex.getLoc();
5010 unsigned KeywordVal = Lex.getUIntVal();
5011 Lex.Lex(); // Eat the keyword.
5014 default: return Error(Loc, "expected instruction opcode");
5015 // Terminator Instructions.
5016 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5017 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5018 case lltok::kw_br: return ParseBr(Inst, PFS);
5019 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5020 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5021 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5022 case lltok::kw_resume: return ParseResume(Inst, PFS);
5023 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5024 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5025 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5026 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5027 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5028 // Binary Operators.
5032 case lltok::kw_shl: {
5033 bool NUW = EatIfPresent(lltok::kw_nuw);
5034 bool NSW = EatIfPresent(lltok::kw_nsw);
5035 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5037 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5039 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5040 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5043 case lltok::kw_fadd:
5044 case lltok::kw_fsub:
5045 case lltok::kw_fmul:
5046 case lltok::kw_fdiv:
5047 case lltok::kw_frem: {
5048 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5049 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5053 Inst->setFastMathFlags(FMF);
5057 case lltok::kw_sdiv:
5058 case lltok::kw_udiv:
5059 case lltok::kw_lshr:
5060 case lltok::kw_ashr: {
5061 bool Exact = EatIfPresent(lltok::kw_exact);
5063 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5064 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5068 case lltok::kw_urem:
5069 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5072 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5073 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5074 case lltok::kw_fcmp: {
5075 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5076 int Res = ParseCompare(Inst, PFS, KeywordVal);
5080 Inst->setFastMathFlags(FMF);
5085 case lltok::kw_trunc:
5086 case lltok::kw_zext:
5087 case lltok::kw_sext:
5088 case lltok::kw_fptrunc:
5089 case lltok::kw_fpext:
5090 case lltok::kw_bitcast:
5091 case lltok::kw_addrspacecast:
5092 case lltok::kw_uitofp:
5093 case lltok::kw_sitofp:
5094 case lltok::kw_fptoui:
5095 case lltok::kw_fptosi:
5096 case lltok::kw_inttoptr:
5097 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5099 case lltok::kw_select: return ParseSelect(Inst, PFS);
5100 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5101 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5102 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5103 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5104 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5105 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5107 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5108 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5109 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5110 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5112 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5113 case lltok::kw_load: return ParseLoad(Inst, PFS);
5114 case lltok::kw_store: return ParseStore(Inst, PFS);
5115 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5116 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5117 case lltok::kw_fence: return ParseFence(Inst, PFS);
5118 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5119 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5120 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5124 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5125 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5126 if (Opc == Instruction::FCmp) {
5127 switch (Lex.getKind()) {
5128 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5129 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5130 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5131 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5132 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5133 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5134 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5135 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5136 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5137 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5138 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5139 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5140 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5141 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5142 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5143 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5144 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5147 switch (Lex.getKind()) {
5148 default: return TokError("expected icmp predicate (e.g. 'eq')");
5149 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5150 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5151 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5152 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5153 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5154 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5155 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5156 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5157 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5158 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5165 //===----------------------------------------------------------------------===//
5166 // Terminator Instructions.
5167 //===----------------------------------------------------------------------===//
5169 /// ParseRet - Parse a return instruction.
5170 /// ::= 'ret' void (',' !dbg, !1)*
5171 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5172 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5173 PerFunctionState &PFS) {
5174 SMLoc TypeLoc = Lex.getLoc();
5176 if (ParseType(Ty, true /*void allowed*/)) return true;
5178 Type *ResType = PFS.getFunction().getReturnType();
5180 if (Ty->isVoidTy()) {
5181 if (!ResType->isVoidTy())
5182 return Error(TypeLoc, "value doesn't match function result type '" +
5183 getTypeString(ResType) + "'");
5185 Inst = ReturnInst::Create(Context);
5190 if (ParseValue(Ty, RV, PFS)) return true;
5192 if (ResType != RV->getType())
5193 return Error(TypeLoc, "value doesn't match function result type '" +
5194 getTypeString(ResType) + "'");
5196 Inst = ReturnInst::Create(Context, RV);
5201 /// ::= 'br' TypeAndValue
5202 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5203 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5206 BasicBlock *Op1, *Op2;
5207 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5209 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5210 Inst = BranchInst::Create(BB);
5214 if (Op0->getType() != Type::getInt1Ty(Context))
5215 return Error(Loc, "branch condition must have 'i1' type");
5217 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5218 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5219 ParseToken(lltok::comma, "expected ',' after true destination") ||
5220 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5223 Inst = BranchInst::Create(Op1, Op2, Op0);
5229 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5231 /// ::= (TypeAndValue ',' TypeAndValue)*
5232 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5233 LocTy CondLoc, BBLoc;
5235 BasicBlock *DefaultBB;
5236 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5237 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5238 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5239 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5242 if (!Cond->getType()->isIntegerTy())
5243 return Error(CondLoc, "switch condition must have integer type");
5245 // Parse the jump table pairs.
5246 SmallPtrSet<Value*, 32> SeenCases;
5247 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5248 while (Lex.getKind() != lltok::rsquare) {
5252 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5253 ParseToken(lltok::comma, "expected ',' after case value") ||
5254 ParseTypeAndBasicBlock(DestBB, PFS))
5257 if (!SeenCases.insert(Constant).second)
5258 return Error(CondLoc, "duplicate case value in switch");
5259 if (!isa<ConstantInt>(Constant))
5260 return Error(CondLoc, "case value is not a constant integer");
5262 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5265 Lex.Lex(); // Eat the ']'.
5267 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5268 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5269 SI->addCase(Table[i].first, Table[i].second);
5276 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5277 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5280 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5281 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5282 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5285 if (!Address->getType()->isPointerTy())
5286 return Error(AddrLoc, "indirectbr address must have pointer type");
5288 // Parse the destination list.
5289 SmallVector<BasicBlock*, 16> DestList;
5291 if (Lex.getKind() != lltok::rsquare) {
5293 if (ParseTypeAndBasicBlock(DestBB, PFS))
5295 DestList.push_back(DestBB);
5297 while (EatIfPresent(lltok::comma)) {
5298 if (ParseTypeAndBasicBlock(DestBB, PFS))
5300 DestList.push_back(DestBB);
5304 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5307 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5308 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5309 IBI->addDestination(DestList[i]);
5315 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5316 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5317 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5318 LocTy CallLoc = Lex.getLoc();
5319 AttrBuilder RetAttrs, FnAttrs;
5320 std::vector<unsigned> FwdRefAttrGrps;
5323 Type *RetType = nullptr;
5326 SmallVector<ParamInfo, 16> ArgList;
5327 SmallVector<OperandBundleDef, 2> BundleList;
5329 BasicBlock *NormalBB, *UnwindBB;
5330 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5331 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5332 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5333 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5335 ParseOptionalOperandBundles(BundleList, PFS) ||
5336 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5337 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5338 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5339 ParseTypeAndBasicBlock(UnwindBB, PFS))
5342 // If RetType is a non-function pointer type, then this is the short syntax
5343 // for the call, which means that RetType is just the return type. Infer the
5344 // rest of the function argument types from the arguments that are present.
5345 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5347 // Pull out the types of all of the arguments...
5348 std::vector<Type*> ParamTypes;
5349 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5350 ParamTypes.push_back(ArgList[i].V->getType());
5352 if (!FunctionType::isValidReturnType(RetType))
5353 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5355 Ty = FunctionType::get(RetType, ParamTypes, false);
5360 // Look up the callee.
5362 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5365 // Set up the Attribute for the function.
5366 SmallVector<AttributeSet, 8> Attrs;
5367 if (RetAttrs.hasAttributes())
5368 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5369 AttributeSet::ReturnIndex,
5372 SmallVector<Value*, 8> Args;
5374 // Loop through FunctionType's arguments and ensure they are specified
5375 // correctly. Also, gather any parameter attributes.
5376 FunctionType::param_iterator I = Ty->param_begin();
5377 FunctionType::param_iterator E = Ty->param_end();
5378 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5379 Type *ExpectedTy = nullptr;
5382 } else if (!Ty->isVarArg()) {
5383 return Error(ArgList[i].Loc, "too many arguments specified");
5386 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5387 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5388 getTypeString(ExpectedTy) + "'");
5389 Args.push_back(ArgList[i].V);
5390 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5391 AttrBuilder B(ArgList[i].Attrs, i + 1);
5392 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5397 return Error(CallLoc, "not enough parameters specified for call");
5399 if (FnAttrs.hasAttributes()) {
5400 if (FnAttrs.hasAlignmentAttr())
5401 return Error(CallLoc, "invoke instructions may not have an alignment");
5403 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5404 AttributeSet::FunctionIndex,
5408 // Finish off the Attribute and check them
5409 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5412 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5413 II->setCallingConv(CC);
5414 II->setAttributes(PAL);
5415 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5421 /// ::= 'resume' TypeAndValue
5422 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5423 Value *Exn; LocTy ExnLoc;
5424 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5427 ResumeInst *RI = ResumeInst::Create(Exn);
5432 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5433 PerFunctionState &PFS) {
5434 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5437 while (Lex.getKind() != lltok::rsquare) {
5438 // If this isn't the first argument, we need a comma.
5439 if (!Args.empty() &&
5440 ParseToken(lltok::comma, "expected ',' in argument list"))
5443 // Parse the argument.
5445 Type *ArgTy = nullptr;
5446 if (ParseType(ArgTy, ArgLoc))
5450 if (ArgTy->isMetadataTy()) {
5451 if (ParseMetadataAsValue(V, PFS))
5454 if (ParseValue(ArgTy, V, PFS))
5460 Lex.Lex(); // Lex the ']'.
5465 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5466 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5467 Value *CleanupPad = nullptr;
5469 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5472 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5475 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5478 BasicBlock *UnwindBB = nullptr;
5479 if (Lex.getKind() == lltok::kw_to) {
5481 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5484 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5489 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5494 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
5495 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5496 Value *CatchPad = nullptr;
5498 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5501 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5505 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5506 ParseTypeAndBasicBlock(BB, PFS))
5509 Inst = CatchReturnInst::Create(CatchPad, BB);
5513 /// ParseCatchSwitch
5514 /// ::= 'catchswitch' within Parent
5515 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5519 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5522 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5523 Lex.getKind() != lltok::LocalVarID)
5524 return TokError("expected scope value for catchswitch");
5526 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5529 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5532 SmallVector<BasicBlock *, 32> Table;
5535 if (ParseTypeAndBasicBlock(DestBB, PFS))
5537 Table.push_back(DestBB);
5538 } while (EatIfPresent(lltok::comma));
5540 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5543 if (ParseToken(lltok::kw_unwind,
5544 "expected 'unwind' after catchswitch scope"))
5547 BasicBlock *UnwindBB = nullptr;
5548 if (EatIfPresent(lltok::kw_to)) {
5549 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5552 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5557 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5558 for (BasicBlock *DestBB : Table)
5559 CatchSwitch->addHandler(DestBB);
5565 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5566 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5567 Value *CatchSwitch = nullptr;
5569 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5572 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5573 return TokError("expected scope value for catchpad");
5575 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5578 SmallVector<Value *, 8> Args;
5579 if (ParseExceptionArgs(Args, PFS))
5582 Inst = CatchPadInst::Create(CatchSwitch, Args);
5587 /// ::= 'cleanuppad' within Parent ParamList
5588 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5589 Value *ParentPad = nullptr;
5591 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5594 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5595 Lex.getKind() != lltok::LocalVarID)
5596 return TokError("expected scope value for cleanuppad");
5598 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5601 SmallVector<Value *, 8> Args;
5602 if (ParseExceptionArgs(Args, PFS))
5605 Inst = CleanupPadInst::Create(ParentPad, Args);
5609 //===----------------------------------------------------------------------===//
5610 // Binary Operators.
5611 //===----------------------------------------------------------------------===//
5614 /// ::= ArithmeticOps TypeAndValue ',' Value
5616 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5617 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5618 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5619 unsigned Opc, unsigned OperandType) {
5620 LocTy Loc; Value *LHS, *RHS;
5621 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5622 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5623 ParseValue(LHS->getType(), RHS, PFS))
5627 switch (OperandType) {
5628 default: llvm_unreachable("Unknown operand type!");
5629 case 0: // int or FP.
5630 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5631 LHS->getType()->isFPOrFPVectorTy();
5633 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5634 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5638 return Error(Loc, "invalid operand type for instruction");
5640 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5645 /// ::= ArithmeticOps TypeAndValue ',' Value {
5646 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5648 LocTy Loc; Value *LHS, *RHS;
5649 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5650 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5651 ParseValue(LHS->getType(), RHS, PFS))
5654 if (!LHS->getType()->isIntOrIntVectorTy())
5655 return Error(Loc,"instruction requires integer or integer vector operands");
5657 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5662 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5663 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5664 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5666 // Parse the integer/fp comparison predicate.
5670 if (ParseCmpPredicate(Pred, Opc) ||
5671 ParseTypeAndValue(LHS, Loc, PFS) ||
5672 ParseToken(lltok::comma, "expected ',' after compare value") ||
5673 ParseValue(LHS->getType(), RHS, PFS))
5676 if (Opc == Instruction::FCmp) {
5677 if (!LHS->getType()->isFPOrFPVectorTy())
5678 return Error(Loc, "fcmp requires floating point operands");
5679 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5681 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5682 if (!LHS->getType()->isIntOrIntVectorTy() &&
5683 !LHS->getType()->getScalarType()->isPointerTy())
5684 return Error(Loc, "icmp requires integer operands");
5685 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5690 //===----------------------------------------------------------------------===//
5691 // Other Instructions.
5692 //===----------------------------------------------------------------------===//
5696 /// ::= CastOpc TypeAndValue 'to' Type
5697 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5701 Type *DestTy = nullptr;
5702 if (ParseTypeAndValue(Op, Loc, PFS) ||
5703 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5707 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5708 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5709 return Error(Loc, "invalid cast opcode for cast from '" +
5710 getTypeString(Op->getType()) + "' to '" +
5711 getTypeString(DestTy) + "'");
5713 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5718 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5719 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5721 Value *Op0, *Op1, *Op2;
5722 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5723 ParseToken(lltok::comma, "expected ',' after select condition") ||
5724 ParseTypeAndValue(Op1, PFS) ||
5725 ParseToken(lltok::comma, "expected ',' after select value") ||
5726 ParseTypeAndValue(Op2, PFS))
5729 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5730 return Error(Loc, Reason);
5732 Inst = SelectInst::Create(Op0, Op1, Op2);
5737 /// ::= 'va_arg' TypeAndValue ',' Type
5738 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5740 Type *EltTy = nullptr;
5742 if (ParseTypeAndValue(Op, PFS) ||
5743 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5744 ParseType(EltTy, TypeLoc))
5747 if (!EltTy->isFirstClassType())
5748 return Error(TypeLoc, "va_arg requires operand with first class type");
5750 Inst = new VAArgInst(Op, EltTy);
5754 /// ParseExtractElement
5755 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5756 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5759 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5760 ParseToken(lltok::comma, "expected ',' after extract value") ||
5761 ParseTypeAndValue(Op1, PFS))
5764 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5765 return Error(Loc, "invalid extractelement operands");
5767 Inst = ExtractElementInst::Create(Op0, Op1);
5771 /// ParseInsertElement
5772 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5773 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5775 Value *Op0, *Op1, *Op2;
5776 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5777 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5778 ParseTypeAndValue(Op1, PFS) ||
5779 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5780 ParseTypeAndValue(Op2, PFS))
5783 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5784 return Error(Loc, "invalid insertelement operands");
5786 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5790 /// ParseShuffleVector
5791 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5792 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5794 Value *Op0, *Op1, *Op2;
5795 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5796 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5797 ParseTypeAndValue(Op1, PFS) ||
5798 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5799 ParseTypeAndValue(Op2, PFS))
5802 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5803 return Error(Loc, "invalid shufflevector operands");
5805 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5810 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5811 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5812 Type *Ty = nullptr; LocTy TypeLoc;
5815 if (ParseType(Ty, TypeLoc) ||
5816 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5817 ParseValue(Ty, Op0, PFS) ||
5818 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5819 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5820 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5823 bool AteExtraComma = false;
5824 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5827 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5829 if (!EatIfPresent(lltok::comma))
5832 if (Lex.getKind() == lltok::MetadataVar) {
5833 AteExtraComma = true;
5837 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5838 ParseValue(Ty, Op0, PFS) ||
5839 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5840 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5841 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5845 if (!Ty->isFirstClassType())
5846 return Error(TypeLoc, "phi node must have first class type");
5848 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5849 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5850 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5852 return AteExtraComma ? InstExtraComma : InstNormal;
5856 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5858 /// ::= 'catch' TypeAndValue
5860 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5861 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5862 Type *Ty = nullptr; LocTy TyLoc;
5864 if (ParseType(Ty, TyLoc))
5867 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5868 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5870 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5871 LandingPadInst::ClauseType CT;
5872 if (EatIfPresent(lltok::kw_catch))
5873 CT = LandingPadInst::Catch;
5874 else if (EatIfPresent(lltok::kw_filter))
5875 CT = LandingPadInst::Filter;
5877 return TokError("expected 'catch' or 'filter' clause type");
5881 if (ParseTypeAndValue(V, VLoc, PFS))
5884 // A 'catch' type expects a non-array constant. A filter clause expects an
5886 if (CT == LandingPadInst::Catch) {
5887 if (isa<ArrayType>(V->getType()))
5888 Error(VLoc, "'catch' clause has an invalid type");
5890 if (!isa<ArrayType>(V->getType()))
5891 Error(VLoc, "'filter' clause has an invalid type");
5894 Constant *CV = dyn_cast<Constant>(V);
5896 return Error(VLoc, "clause argument must be a constant");
5900 Inst = LP.release();
5905 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5906 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5907 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5908 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5909 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5910 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5911 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5912 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5913 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5914 CallInst::TailCallKind TCK) {
5915 AttrBuilder RetAttrs, FnAttrs;
5916 std::vector<unsigned> FwdRefAttrGrps;
5919 Type *RetType = nullptr;
5922 SmallVector<ParamInfo, 16> ArgList;
5923 SmallVector<OperandBundleDef, 2> BundleList;
5924 LocTy CallLoc = Lex.getLoc();
5926 if (TCK != CallInst::TCK_None &&
5927 ParseToken(lltok::kw_call,
5928 "expected 'tail call', 'musttail call', or 'notail call'"))
5931 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5933 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5934 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5935 ParseValID(CalleeID) ||
5936 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5937 PFS.getFunction().isVarArg()) ||
5938 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5939 ParseOptionalOperandBundles(BundleList, PFS))
5942 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5943 return Error(CallLoc, "fast-math-flags specified for call without "
5944 "floating-point scalar or vector return type");
5946 // If RetType is a non-function pointer type, then this is the short syntax
5947 // for the call, which means that RetType is just the return type. Infer the
5948 // rest of the function argument types from the arguments that are present.
5949 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5951 // Pull out the types of all of the arguments...
5952 std::vector<Type*> ParamTypes;
5953 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5954 ParamTypes.push_back(ArgList[i].V->getType());
5956 if (!FunctionType::isValidReturnType(RetType))
5957 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5959 Ty = FunctionType::get(RetType, ParamTypes, false);
5964 // Look up the callee.
5966 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5969 // Set up the Attribute for the function.
5970 SmallVector<AttributeSet, 8> Attrs;
5971 if (RetAttrs.hasAttributes())
5972 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5973 AttributeSet::ReturnIndex,
5976 SmallVector<Value*, 8> Args;
5978 // Loop through FunctionType's arguments and ensure they are specified
5979 // correctly. Also, gather any parameter attributes.
5980 FunctionType::param_iterator I = Ty->param_begin();
5981 FunctionType::param_iterator E = Ty->param_end();
5982 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5983 Type *ExpectedTy = nullptr;
5986 } else if (!Ty->isVarArg()) {
5987 return Error(ArgList[i].Loc, "too many arguments specified");
5990 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5991 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5992 getTypeString(ExpectedTy) + "'");
5993 Args.push_back(ArgList[i].V);
5994 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5995 AttrBuilder B(ArgList[i].Attrs, i + 1);
5996 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
6001 return Error(CallLoc, "not enough parameters specified for call");
6003 if (FnAttrs.hasAttributes()) {
6004 if (FnAttrs.hasAlignmentAttr())
6005 return Error(CallLoc, "call instructions may not have an alignment");
6007 Attrs.push_back(AttributeSet::get(RetType->getContext(),
6008 AttributeSet::FunctionIndex,
6012 // Finish off the Attribute and check them
6013 AttributeSet PAL = AttributeSet::get(Context, Attrs);
6015 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6016 CI->setTailCallKind(TCK);
6017 CI->setCallingConv(CC);
6019 CI->setFastMathFlags(FMF);
6020 CI->setAttributes(PAL);
6021 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6026 //===----------------------------------------------------------------------===//
6027 // Memory Instructions.
6028 //===----------------------------------------------------------------------===//
6031 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6032 /// (',' 'align' i32)?
6033 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6034 Value *Size = nullptr;
6035 LocTy SizeLoc, TyLoc;
6036 unsigned Alignment = 0;
6039 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6040 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6042 if (ParseType(Ty, TyLoc)) return true;
6044 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6045 return Error(TyLoc, "invalid type for alloca");
6047 bool AteExtraComma = false;
6048 if (EatIfPresent(lltok::comma)) {
6049 if (Lex.getKind() == lltok::kw_align) {
6050 if (ParseOptionalAlignment(Alignment)) return true;
6051 } else if (Lex.getKind() == lltok::MetadataVar) {
6052 AteExtraComma = true;
6054 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6055 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6060 if (Size && !Size->getType()->isIntegerTy())
6061 return Error(SizeLoc, "element count must have integer type");
6063 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
6064 AI->setUsedWithInAlloca(IsInAlloca);
6065 AI->setSwiftError(IsSwiftError);
6067 return AteExtraComma ? InstExtraComma : InstNormal;
6071 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6072 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6073 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6074 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6075 Value *Val; LocTy Loc;
6076 unsigned Alignment = 0;
6077 bool AteExtraComma = false;
6078 bool isAtomic = false;
6079 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6080 SynchronizationScope Scope = CrossThread;
6082 if (Lex.getKind() == lltok::kw_atomic) {
6087 bool isVolatile = false;
6088 if (Lex.getKind() == lltok::kw_volatile) {
6094 LocTy ExplicitTypeLoc = Lex.getLoc();
6095 if (ParseType(Ty) ||
6096 ParseToken(lltok::comma, "expected comma after load's type") ||
6097 ParseTypeAndValue(Val, Loc, PFS) ||
6098 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6099 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6102 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6103 return Error(Loc, "load operand must be a pointer to a first class type");
6104 if (isAtomic && !Alignment)
6105 return Error(Loc, "atomic load must have explicit non-zero alignment");
6106 if (Ordering == AtomicOrdering::Release ||
6107 Ordering == AtomicOrdering::AcquireRelease)
6108 return Error(Loc, "atomic load cannot use Release ordering");
6110 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6111 return Error(ExplicitTypeLoc,
6112 "explicit pointee type doesn't match operand's pointee type");
6114 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
6115 return AteExtraComma ? InstExtraComma : InstNormal;
6120 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6121 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6122 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6123 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6124 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6125 unsigned Alignment = 0;
6126 bool AteExtraComma = false;
6127 bool isAtomic = false;
6128 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6129 SynchronizationScope Scope = CrossThread;
6131 if (Lex.getKind() == lltok::kw_atomic) {
6136 bool isVolatile = false;
6137 if (Lex.getKind() == lltok::kw_volatile) {
6142 if (ParseTypeAndValue(Val, Loc, PFS) ||
6143 ParseToken(lltok::comma, "expected ',' after store operand") ||
6144 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6145 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6146 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6149 if (!Ptr->getType()->isPointerTy())
6150 return Error(PtrLoc, "store operand must be a pointer");
6151 if (!Val->getType()->isFirstClassType())
6152 return Error(Loc, "store operand must be a first class value");
6153 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6154 return Error(Loc, "stored value and pointer type do not match");
6155 if (isAtomic && !Alignment)
6156 return Error(Loc, "atomic store must have explicit non-zero alignment");
6157 if (Ordering == AtomicOrdering::Acquire ||
6158 Ordering == AtomicOrdering::AcquireRelease)
6159 return Error(Loc, "atomic store cannot use Acquire ordering");
6161 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6162 return AteExtraComma ? InstExtraComma : InstNormal;
6166 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6167 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6168 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6169 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6170 bool AteExtraComma = false;
6171 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6172 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6173 SynchronizationScope Scope = CrossThread;
6174 bool isVolatile = false;
6175 bool isWeak = false;
6177 if (EatIfPresent(lltok::kw_weak))
6180 if (EatIfPresent(lltok::kw_volatile))
6183 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6184 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6185 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6186 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6187 ParseTypeAndValue(New, NewLoc, PFS) ||
6188 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6189 ParseOrdering(FailureOrdering))
6192 if (SuccessOrdering == AtomicOrdering::Unordered ||
6193 FailureOrdering == AtomicOrdering::Unordered)
6194 return TokError("cmpxchg cannot be unordered");
6195 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6196 return TokError("cmpxchg failure argument shall be no stronger than the "
6197 "success argument");
6198 if (FailureOrdering == AtomicOrdering::Release ||
6199 FailureOrdering == AtomicOrdering::AcquireRelease)
6201 "cmpxchg failure ordering cannot include release semantics");
6202 if (!Ptr->getType()->isPointerTy())
6203 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6204 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6205 return Error(CmpLoc, "compare value and pointer type do not match");
6206 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6207 return Error(NewLoc, "new value and pointer type do not match");
6208 if (!New->getType()->isFirstClassType())
6209 return Error(NewLoc, "cmpxchg operand must be a first class value");
6210 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6211 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6212 CXI->setVolatile(isVolatile);
6213 CXI->setWeak(isWeak);
6215 return AteExtraComma ? InstExtraComma : InstNormal;
6219 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6220 /// 'singlethread'? AtomicOrdering
6221 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6222 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6223 bool AteExtraComma = false;
6224 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6225 SynchronizationScope Scope = CrossThread;
6226 bool isVolatile = false;
6227 AtomicRMWInst::BinOp Operation;
6229 if (EatIfPresent(lltok::kw_volatile))
6232 switch (Lex.getKind()) {
6233 default: return TokError("expected binary operation in atomicrmw");
6234 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6235 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6236 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6237 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6238 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6239 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6240 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6241 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6242 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6243 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6244 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6246 Lex.Lex(); // Eat the operation.
6248 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6249 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6250 ParseTypeAndValue(Val, ValLoc, PFS) ||
6251 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6254 if (Ordering == AtomicOrdering::Unordered)
6255 return TokError("atomicrmw cannot be unordered");
6256 if (!Ptr->getType()->isPointerTy())
6257 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6258 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6259 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6260 if (!Val->getType()->isIntegerTy())
6261 return Error(ValLoc, "atomicrmw operand must be an integer");
6262 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6263 if (Size < 8 || (Size & (Size - 1)))
6264 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6267 AtomicRMWInst *RMWI =
6268 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6269 RMWI->setVolatile(isVolatile);
6271 return AteExtraComma ? InstExtraComma : InstNormal;
6275 /// ::= 'fence' 'singlethread'? AtomicOrdering
6276 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6277 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6278 SynchronizationScope Scope = CrossThread;
6279 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6282 if (Ordering == AtomicOrdering::Unordered)
6283 return TokError("fence cannot be unordered");
6284 if (Ordering == AtomicOrdering::Monotonic)
6285 return TokError("fence cannot be monotonic");
6287 Inst = new FenceInst(Context, Ordering, Scope);
6291 /// ParseGetElementPtr
6292 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6293 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6294 Value *Ptr = nullptr;
6295 Value *Val = nullptr;
6298 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6301 LocTy ExplicitTypeLoc = Lex.getLoc();
6302 if (ParseType(Ty) ||
6303 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6304 ParseTypeAndValue(Ptr, Loc, PFS))
6307 Type *BaseType = Ptr->getType();
6308 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6309 if (!BasePointerType)
6310 return Error(Loc, "base of getelementptr must be a pointer");
6312 if (Ty != BasePointerType->getElementType())
6313 return Error(ExplicitTypeLoc,
6314 "explicit pointee type doesn't match operand's pointee type");
6316 SmallVector<Value*, 16> Indices;
6317 bool AteExtraComma = false;
6318 // GEP returns a vector of pointers if at least one of parameters is a vector.
6319 // All vector parameters should have the same vector width.
6320 unsigned GEPWidth = BaseType->isVectorTy() ?
6321 BaseType->getVectorNumElements() : 0;
6323 while (EatIfPresent(lltok::comma)) {
6324 if (Lex.getKind() == lltok::MetadataVar) {
6325 AteExtraComma = true;
6328 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6329 if (!Val->getType()->getScalarType()->isIntegerTy())
6330 return Error(EltLoc, "getelementptr index must be an integer");
6332 if (Val->getType()->isVectorTy()) {
6333 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6334 if (GEPWidth && GEPWidth != ValNumEl)
6335 return Error(EltLoc,
6336 "getelementptr vector index has a wrong number of elements");
6337 GEPWidth = ValNumEl;
6339 Indices.push_back(Val);
6342 SmallPtrSet<Type*, 4> Visited;
6343 if (!Indices.empty() && !Ty->isSized(&Visited))
6344 return Error(Loc, "base element of getelementptr must be sized");
6346 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6347 return Error(Loc, "invalid getelementptr indices");
6348 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6350 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6351 return AteExtraComma ? InstExtraComma : InstNormal;
6354 /// ParseExtractValue
6355 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6356 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6357 Value *Val; LocTy Loc;
6358 SmallVector<unsigned, 4> Indices;
6360 if (ParseTypeAndValue(Val, Loc, PFS) ||
6361 ParseIndexList(Indices, AteExtraComma))
6364 if (!Val->getType()->isAggregateType())
6365 return Error(Loc, "extractvalue operand must be aggregate type");
6367 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6368 return Error(Loc, "invalid indices for extractvalue");
6369 Inst = ExtractValueInst::Create(Val, Indices);
6370 return AteExtraComma ? InstExtraComma : InstNormal;
6373 /// ParseInsertValue
6374 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6375 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6376 Value *Val0, *Val1; LocTy Loc0, Loc1;
6377 SmallVector<unsigned, 4> Indices;
6379 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6380 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6381 ParseTypeAndValue(Val1, Loc1, PFS) ||
6382 ParseIndexList(Indices, AteExtraComma))
6385 if (!Val0->getType()->isAggregateType())
6386 return Error(Loc0, "insertvalue operand must be aggregate type");
6388 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6390 return Error(Loc0, "invalid indices for insertvalue");
6391 if (IndexedType != Val1->getType())
6392 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6393 getTypeString(Val1->getType()) + "' instead of '" +
6394 getTypeString(IndexedType) + "'");
6395 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6396 return AteExtraComma ? InstExtraComma : InstNormal;
6399 //===----------------------------------------------------------------------===//
6400 // Embedded metadata.
6401 //===----------------------------------------------------------------------===//
6403 /// ParseMDNodeVector
6404 /// ::= { Element (',' Element)* }
6406 /// ::= 'null' | TypeAndValue
6407 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6408 if (ParseToken(lltok::lbrace, "expected '{' here"))
6411 // Check for an empty list.
6412 if (EatIfPresent(lltok::rbrace))
6416 // Null is a special case since it is typeless.
6417 if (EatIfPresent(lltok::kw_null)) {
6418 Elts.push_back(nullptr);
6423 if (ParseMetadata(MD, nullptr))
6426 } while (EatIfPresent(lltok::comma));
6428 return ParseToken(lltok::rbrace, "expected end of metadata node");
6431 //===----------------------------------------------------------------------===//
6432 // Use-list order directives.
6433 //===----------------------------------------------------------------------===//
6434 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6437 return Error(Loc, "value has no uses");
6439 unsigned NumUses = 0;
6440 SmallDenseMap<const Use *, unsigned, 16> Order;
6441 for (const Use &U : V->uses()) {
6442 if (++NumUses > Indexes.size())
6444 Order[&U] = Indexes[NumUses - 1];
6447 return Error(Loc, "value only has one use");
6448 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6449 return Error(Loc, "wrong number of indexes, expected " +
6450 Twine(std::distance(V->use_begin(), V->use_end())));
6452 V->sortUseList([&](const Use &L, const Use &R) {
6453 return Order.lookup(&L) < Order.lookup(&R);
6458 /// ParseUseListOrderIndexes
6459 /// ::= '{' uint32 (',' uint32)+ '}'
6460 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6461 SMLoc Loc = Lex.getLoc();
6462 if (ParseToken(lltok::lbrace, "expected '{' here"))
6464 if (Lex.getKind() == lltok::rbrace)
6465 return Lex.Error("expected non-empty list of uselistorder indexes");
6467 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6468 // indexes should be distinct numbers in the range [0, size-1], and should
6470 unsigned Offset = 0;
6472 bool IsOrdered = true;
6473 assert(Indexes.empty() && "Expected empty order vector");
6476 if (ParseUInt32(Index))
6479 // Update consistency checks.
6480 Offset += Index - Indexes.size();
6481 Max = std::max(Max, Index);
6482 IsOrdered &= Index == Indexes.size();
6484 Indexes.push_back(Index);
6485 } while (EatIfPresent(lltok::comma));
6487 if (ParseToken(lltok::rbrace, "expected '}' here"))
6490 if (Indexes.size() < 2)
6491 return Error(Loc, "expected >= 2 uselistorder indexes");
6492 if (Offset != 0 || Max >= Indexes.size())
6493 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6495 return Error(Loc, "expected uselistorder indexes to change the order");
6500 /// ParseUseListOrder
6501 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6502 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6503 SMLoc Loc = Lex.getLoc();
6504 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6508 SmallVector<unsigned, 16> Indexes;
6509 if (ParseTypeAndValue(V, PFS) ||
6510 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6511 ParseUseListOrderIndexes(Indexes))
6514 return sortUseListOrder(V, Indexes, Loc);
6517 /// ParseUseListOrderBB
6518 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6519 bool LLParser::ParseUseListOrderBB() {
6520 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6521 SMLoc Loc = Lex.getLoc();
6525 SmallVector<unsigned, 16> Indexes;
6526 if (ParseValID(Fn) ||
6527 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6528 ParseValID(Label) ||
6529 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6530 ParseUseListOrderIndexes(Indexes))
6533 // Check the function.
6535 if (Fn.Kind == ValID::t_GlobalName)
6536 GV = M->getNamedValue(Fn.StrVal);
6537 else if (Fn.Kind == ValID::t_GlobalID)
6538 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6540 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6542 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6543 auto *F = dyn_cast<Function>(GV);
6545 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6546 if (F->isDeclaration())
6547 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6549 // Check the basic block.
6550 if (Label.Kind == ValID::t_LocalID)
6551 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6552 if (Label.Kind != ValID::t_LocalName)
6553 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6554 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
6556 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6557 if (!isa<BasicBlock>(V))
6558 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6560 return sortUseListOrder(V, Indexes, Loc);