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/SmallPtrSet.h"
16 #include "llvm/AsmParser/SlotMapping.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/CallingConv.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/ValueSymbolTable.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.h"
35 static std::string getTypeString(Type *T) {
37 raw_string_ostream Tmp(Result);
42 /// Run: module ::= toplevelentity*
43 bool LLParser::Run() {
47 return ParseTopLevelEntities() ||
48 ValidateEndOfModule();
51 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
53 bool LLParser::ValidateEndOfModule() {
54 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
55 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
57 // Handle any function attribute group forward references.
58 for (std::map<Value*, std::vector<unsigned> >::iterator
59 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
62 std::vector<unsigned> &Vec = I->second;
65 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
67 B.merge(NumberedAttrBuilders[*VI]);
69 if (Function *Fn = dyn_cast<Function>(V)) {
70 AttributeSet AS = Fn->getAttributes();
71 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
72 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
73 AS.getFnAttributes());
77 // If the alignment was parsed as an attribute, move to the alignment
79 if (FnAttrs.hasAlignmentAttr()) {
80 Fn->setAlignment(FnAttrs.getAlignment());
81 FnAttrs.removeAttribute(Attribute::Alignment);
84 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
85 AttributeSet::get(Context,
86 AttributeSet::FunctionIndex,
88 Fn->setAttributes(AS);
89 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
90 AttributeSet AS = CI->getAttributes();
91 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
92 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
93 AS.getFnAttributes());
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
99 CI->setAttributes(AS);
100 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
101 AttributeSet AS = II->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
110 II->setAttributes(AS);
112 llvm_unreachable("invalid object with forward attribute group reference");
116 // If there are entries in ForwardRefBlockAddresses at this point, the
117 // function was never defined.
118 if (!ForwardRefBlockAddresses.empty())
119 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
120 "expected function name in blockaddress");
122 for (const auto &NT : NumberedTypes)
123 if (NT.second.second.isValid())
124 return Error(NT.second.second,
125 "use of undefined type '%" + Twine(NT.first) + "'");
127 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
128 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
129 if (I->second.second.isValid())
130 return Error(I->second.second,
131 "use of undefined type named '" + I->getKey() + "'");
133 if (!ForwardRefComdats.empty())
134 return Error(ForwardRefComdats.begin()->second,
135 "use of undefined comdat '$" +
136 ForwardRefComdats.begin()->first + "'");
138 if (!ForwardRefVals.empty())
139 return Error(ForwardRefVals.begin()->second.second,
140 "use of undefined value '@" + ForwardRefVals.begin()->first +
143 if (!ForwardRefValIDs.empty())
144 return Error(ForwardRefValIDs.begin()->second.second,
145 "use of undefined value '@" +
146 Twine(ForwardRefValIDs.begin()->first) + "'");
148 if (!ForwardRefMDNodes.empty())
149 return Error(ForwardRefMDNodes.begin()->second.second,
150 "use of undefined metadata '!" +
151 Twine(ForwardRefMDNodes.begin()->first) + "'");
153 // Resolve metadata cycles.
154 for (auto &N : NumberedMetadata) {
155 if (N.second && !N.second->isResolved())
156 N.second->resolveCycles();
159 // Look for intrinsic functions and CallInst that need to be upgraded
160 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
161 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
163 UpgradeDebugInfo(*M);
167 // Initialize the slot mapping.
168 // Because by this point we've parsed and validated everything, we can "steal"
169 // the mapping from LLParser as it doesn't need it anymore.
170 Slots->GlobalValues = std::move(NumberedVals);
171 Slots->MetadataNodes = std::move(NumberedMetadata);
176 //===----------------------------------------------------------------------===//
177 // Top-Level Entities
178 //===----------------------------------------------------------------------===//
180 bool LLParser::ParseTopLevelEntities() {
182 switch (Lex.getKind()) {
183 default: return TokError("expected top-level entity");
184 case lltok::Eof: return false;
185 case lltok::kw_declare: if (ParseDeclare()) return true; break;
186 case lltok::kw_define: if (ParseDefine()) return true; break;
187 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
188 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
189 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
190 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
191 case lltok::LocalVar: if (ParseNamedType()) return true; break;
192 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
193 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
194 case lltok::ComdatVar: if (parseComdat()) return true; break;
195 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
196 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
198 // The Global variable production with no name can have many different
199 // optional leading prefixes, the production is:
200 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
201 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
202 // ('constant'|'global') ...
203 case lltok::kw_private: // OptionalLinkage
204 case lltok::kw_internal: // OptionalLinkage
205 case lltok::kw_weak: // OptionalLinkage
206 case lltok::kw_weak_odr: // OptionalLinkage
207 case lltok::kw_linkonce: // OptionalLinkage
208 case lltok::kw_linkonce_odr: // OptionalLinkage
209 case lltok::kw_appending: // OptionalLinkage
210 case lltok::kw_common: // OptionalLinkage
211 case lltok::kw_extern_weak: // OptionalLinkage
212 case lltok::kw_external: // OptionalLinkage
213 case lltok::kw_default: // OptionalVisibility
214 case lltok::kw_hidden: // OptionalVisibility
215 case lltok::kw_protected: // OptionalVisibility
216 case lltok::kw_dllimport: // OptionalDLLStorageClass
217 case lltok::kw_dllexport: // OptionalDLLStorageClass
218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: { // GlobalType
222 unsigned Linkage, Visibility, DLLStorageClass;
224 GlobalVariable::ThreadLocalMode TLM;
226 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
227 ParseOptionalVisibility(Visibility) ||
228 ParseOptionalDLLStorageClass(DLLStorageClass) ||
229 ParseOptionalThreadLocal(TLM) ||
230 parseOptionalUnnamedAddr(UnnamedAddr) ||
231 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
232 DLLStorageClass, TLM, UnnamedAddr))
237 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
238 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
239 case lltok::kw_uselistorder_bb:
240 if (ParseUseListOrderBB()) return true; break;
247 /// ::= 'module' 'asm' STRINGCONSTANT
248 bool LLParser::ParseModuleAsm() {
249 assert(Lex.getKind() == lltok::kw_module);
253 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
254 ParseStringConstant(AsmStr)) return true;
256 M->appendModuleInlineAsm(AsmStr);
261 /// ::= 'target' 'triple' '=' STRINGCONSTANT
262 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
263 bool LLParser::ParseTargetDefinition() {
264 assert(Lex.getKind() == lltok::kw_target);
267 default: return TokError("unknown target property");
268 case lltok::kw_triple:
270 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271 ParseStringConstant(Str))
273 M->setTargetTriple(Str);
275 case lltok::kw_datalayout:
277 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278 ParseStringConstant(Str))
280 M->setDataLayout(Str);
286 /// ::= 'deplibs' '=' '[' ']'
287 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288 /// FIXME: Remove in 4.0. Currently parse, but ignore.
289 bool LLParser::ParseDepLibs() {
290 assert(Lex.getKind() == lltok::kw_deplibs);
292 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
293 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
296 if (EatIfPresent(lltok::rsquare))
301 if (ParseStringConstant(Str)) return true;
302 } while (EatIfPresent(lltok::comma));
304 return ParseToken(lltok::rsquare, "expected ']' at end of list");
307 /// ParseUnnamedType:
308 /// ::= LocalVarID '=' 'type' type
309 bool LLParser::ParseUnnamedType() {
310 LocTy TypeLoc = Lex.getLoc();
311 unsigned TypeID = Lex.getUIntVal();
312 Lex.Lex(); // eat LocalVarID;
314 if (ParseToken(lltok::equal, "expected '=' after name") ||
315 ParseToken(lltok::kw_type, "expected 'type' after '='"))
318 Type *Result = nullptr;
319 if (ParseStructDefinition(TypeLoc, "",
320 NumberedTypes[TypeID], Result)) return true;
322 if (!isa<StructType>(Result)) {
323 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
325 return Error(TypeLoc, "non-struct types may not be recursive");
326 Entry.first = Result;
327 Entry.second = SMLoc();
335 /// ::= LocalVar '=' 'type' type
336 bool LLParser::ParseNamedType() {
337 std::string Name = Lex.getStrVal();
338 LocTy NameLoc = Lex.getLoc();
339 Lex.Lex(); // eat LocalVar.
341 if (ParseToken(lltok::equal, "expected '=' after name") ||
342 ParseToken(lltok::kw_type, "expected 'type' after name"))
345 Type *Result = nullptr;
346 if (ParseStructDefinition(NameLoc, Name,
347 NamedTypes[Name], Result)) return true;
349 if (!isa<StructType>(Result)) {
350 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
352 return Error(NameLoc, "non-struct types may not be recursive");
353 Entry.first = Result;
354 Entry.second = SMLoc();
362 /// ::= 'declare' FunctionHeader
363 bool LLParser::ParseDeclare() {
364 assert(Lex.getKind() == lltok::kw_declare);
368 return ParseFunctionHeader(F, false);
372 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
373 bool LLParser::ParseDefine() {
374 assert(Lex.getKind() == lltok::kw_define);
378 return ParseFunctionHeader(F, true) ||
379 ParseOptionalFunctionMetadata(*F) ||
380 ParseFunctionBody(*F);
386 bool LLParser::ParseGlobalType(bool &IsConstant) {
387 if (Lex.getKind() == lltok::kw_constant)
389 else if (Lex.getKind() == lltok::kw_global)
393 return TokError("expected 'global' or 'constant'");
399 /// ParseUnnamedGlobal:
400 /// OptionalVisibility ALIAS ...
401 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
402 /// ... -> global variable
403 /// GlobalID '=' OptionalVisibility ALIAS ...
404 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
405 /// ... -> global variable
406 bool LLParser::ParseUnnamedGlobal() {
407 unsigned VarID = NumberedVals.size();
409 LocTy NameLoc = Lex.getLoc();
411 // Handle the GlobalID form.
412 if (Lex.getKind() == lltok::GlobalID) {
413 if (Lex.getUIntVal() != VarID)
414 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
416 Lex.Lex(); // eat GlobalID;
418 if (ParseToken(lltok::equal, "expected '=' after name"))
423 unsigned Linkage, Visibility, DLLStorageClass;
424 GlobalVariable::ThreadLocalMode TLM;
426 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
427 ParseOptionalVisibility(Visibility) ||
428 ParseOptionalDLLStorageClass(DLLStorageClass) ||
429 ParseOptionalThreadLocal(TLM) ||
430 parseOptionalUnnamedAddr(UnnamedAddr))
433 if (Lex.getKind() != lltok::kw_alias)
434 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
435 DLLStorageClass, TLM, UnnamedAddr);
436 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
440 /// ParseNamedGlobal:
441 /// GlobalVar '=' OptionalVisibility ALIAS ...
442 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
443 /// ... -> global variable
444 bool LLParser::ParseNamedGlobal() {
445 assert(Lex.getKind() == lltok::GlobalVar);
446 LocTy NameLoc = Lex.getLoc();
447 std::string Name = Lex.getStrVal();
451 unsigned Linkage, Visibility, DLLStorageClass;
452 GlobalVariable::ThreadLocalMode TLM;
454 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
455 ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility) ||
457 ParseOptionalDLLStorageClass(DLLStorageClass) ||
458 ParseOptionalThreadLocal(TLM) ||
459 parseOptionalUnnamedAddr(UnnamedAddr))
462 if (Lex.getKind() != lltok::kw_alias)
463 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
464 DLLStorageClass, TLM, UnnamedAddr);
466 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
470 bool LLParser::parseComdat() {
471 assert(Lex.getKind() == lltok::ComdatVar);
472 std::string Name = Lex.getStrVal();
473 LocTy NameLoc = Lex.getLoc();
476 if (ParseToken(lltok::equal, "expected '=' here"))
479 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
480 return TokError("expected comdat type");
482 Comdat::SelectionKind SK;
483 switch (Lex.getKind()) {
485 return TokError("unknown selection kind");
489 case lltok::kw_exactmatch:
490 SK = Comdat::ExactMatch;
492 case lltok::kw_largest:
493 SK = Comdat::Largest;
495 case lltok::kw_noduplicates:
496 SK = Comdat::NoDuplicates;
498 case lltok::kw_samesize:
499 SK = Comdat::SameSize;
504 // See if the comdat was forward referenced, if so, use the comdat.
505 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
506 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
507 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
508 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
511 if (I != ComdatSymTab.end())
514 C = M->getOrInsertComdat(Name);
515 C->setSelectionKind(SK);
521 // ::= '!' STRINGCONSTANT
522 bool LLParser::ParseMDString(MDString *&Result) {
524 if (ParseStringConstant(Str)) return true;
525 llvm::UpgradeMDStringConstant(Str);
526 Result = MDString::get(Context, Str);
531 // ::= '!' MDNodeNumber
532 bool LLParser::ParseMDNodeID(MDNode *&Result) {
533 // !{ ..., !42, ... }
535 if (ParseUInt32(MID))
538 // If not a forward reference, just return it now.
539 if (NumberedMetadata.count(MID)) {
540 Result = NumberedMetadata[MID];
544 // Otherwise, create MDNode forward reference.
545 auto &FwdRef = ForwardRefMDNodes[MID];
546 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
548 Result = FwdRef.first.get();
549 NumberedMetadata[MID].reset(Result);
553 /// ParseNamedMetadata:
554 /// !foo = !{ !1, !2 }
555 bool LLParser::ParseNamedMetadata() {
556 assert(Lex.getKind() == lltok::MetadataVar);
557 std::string Name = Lex.getStrVal();
560 if (ParseToken(lltok::equal, "expected '=' here") ||
561 ParseToken(lltok::exclaim, "Expected '!' here") ||
562 ParseToken(lltok::lbrace, "Expected '{' here"))
565 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
566 if (Lex.getKind() != lltok::rbrace)
568 if (ParseToken(lltok::exclaim, "Expected '!' here"))
572 if (ParseMDNodeID(N)) return true;
574 } while (EatIfPresent(lltok::comma));
576 return ParseToken(lltok::rbrace, "expected end of metadata node");
579 /// ParseStandaloneMetadata:
581 bool LLParser::ParseStandaloneMetadata() {
582 assert(Lex.getKind() == lltok::exclaim);
584 unsigned MetadataID = 0;
587 if (ParseUInt32(MetadataID) ||
588 ParseToken(lltok::equal, "expected '=' here"))
591 // Detect common error, from old metadata syntax.
592 if (Lex.getKind() == lltok::Type)
593 return TokError("unexpected type in metadata definition");
595 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
596 if (Lex.getKind() == lltok::MetadataVar) {
597 if (ParseSpecializedMDNode(Init, IsDistinct))
599 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
600 ParseMDTuple(Init, IsDistinct))
603 // See if this was forward referenced, if so, handle it.
604 auto FI = ForwardRefMDNodes.find(MetadataID);
605 if (FI != ForwardRefMDNodes.end()) {
606 FI->second.first->replaceAllUsesWith(Init);
607 ForwardRefMDNodes.erase(FI);
609 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
611 if (NumberedMetadata.count(MetadataID))
612 return TokError("Metadata id is already used");
613 NumberedMetadata[MetadataID].reset(Init);
619 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
620 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
621 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
625 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
626 /// OptionalDLLStorageClass OptionalThreadLocal
627 /// OptionalUnnamedAddr 'alias' Aliasee
632 /// Everything through OptionalUnnamedAddr has already been parsed.
634 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
635 unsigned Visibility, unsigned DLLStorageClass,
636 GlobalVariable::ThreadLocalMode TLM,
638 assert(Lex.getKind() == lltok::kw_alias);
641 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
643 if(!GlobalAlias::isValidLinkage(Linkage))
644 return Error(NameLoc, "invalid linkage type for alias");
646 if (!isValidVisibilityForLinkage(Visibility, L))
647 return Error(NameLoc,
648 "symbol with local linkage must have default visibility");
651 LocTy AliaseeLoc = Lex.getLoc();
652 if (Lex.getKind() != lltok::kw_bitcast &&
653 Lex.getKind() != lltok::kw_getelementptr &&
654 Lex.getKind() != lltok::kw_addrspacecast &&
655 Lex.getKind() != lltok::kw_inttoptr) {
656 if (ParseGlobalTypeAndValue(Aliasee))
659 // The bitcast dest type is not present, it is implied by the dest type.
663 if (ID.Kind != ValID::t_Constant)
664 return Error(AliaseeLoc, "invalid aliasee");
665 Aliasee = ID.ConstantVal;
668 Type *AliaseeType = Aliasee->getType();
669 auto *PTy = dyn_cast<PointerType>(AliaseeType);
671 return Error(AliaseeLoc, "An alias must have pointer type");
673 // Okay, create the alias but do not insert it into the module yet.
674 std::unique_ptr<GlobalAlias> GA(
675 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
676 Aliasee, /*Parent*/ nullptr));
677 GA->setThreadLocalMode(TLM);
678 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
679 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
680 GA->setUnnamedAddr(UnnamedAddr);
683 NumberedVals.push_back(GA.get());
685 // See if this value already exists in the symbol table. If so, it is either
686 // a redefinition or a definition of a forward reference.
687 if (GlobalValue *Val = M->getNamedValue(Name)) {
688 // See if this was a redefinition. If so, there is no entry in
690 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
691 I = ForwardRefVals.find(Name);
692 if (I == ForwardRefVals.end())
693 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
695 // Otherwise, this was a definition of forward ref. Verify that types
697 if (Val->getType() != GA->getType())
698 return Error(NameLoc,
699 "forward reference and definition of alias have different types");
701 // If they agree, just RAUW the old value with the alias and remove the
703 Val->replaceAllUsesWith(GA.get());
704 Val->eraseFromParent();
705 ForwardRefVals.erase(I);
708 // Insert into the module, we know its name won't collide now.
709 M->getAliasList().push_back(GA.get());
710 assert(GA->getName() == Name && "Should not be a name conflict!");
712 // The module owns this now
719 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
720 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
721 /// OptionalExternallyInitialized GlobalType Type Const
722 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
723 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
724 /// OptionalExternallyInitialized GlobalType Type Const
726 /// Everything up to and including OptionalUnnamedAddr has been parsed
729 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
730 unsigned Linkage, bool HasLinkage,
731 unsigned Visibility, unsigned DLLStorageClass,
732 GlobalVariable::ThreadLocalMode TLM,
734 if (!isValidVisibilityForLinkage(Visibility, Linkage))
735 return Error(NameLoc,
736 "symbol with local linkage must have default visibility");
739 bool IsConstant, IsExternallyInitialized;
740 LocTy IsExternallyInitializedLoc;
744 if (ParseOptionalAddrSpace(AddrSpace) ||
745 ParseOptionalToken(lltok::kw_externally_initialized,
746 IsExternallyInitialized,
747 &IsExternallyInitializedLoc) ||
748 ParseGlobalType(IsConstant) ||
749 ParseType(Ty, TyLoc))
752 // If the linkage is specified and is external, then no initializer is
754 Constant *Init = nullptr;
755 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
756 Linkage != GlobalValue::ExternalLinkage)) {
757 if (ParseGlobalValue(Ty, Init))
761 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
762 return Error(TyLoc, "invalid type for global variable");
764 GlobalValue *GVal = nullptr;
766 // See if the global was forward referenced, if so, use the global.
768 GVal = M->getNamedValue(Name);
770 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
771 return Error(NameLoc, "redefinition of global '@" + Name + "'");
774 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
775 I = ForwardRefValIDs.find(NumberedVals.size());
776 if (I != ForwardRefValIDs.end()) {
777 GVal = I->second.first;
778 ForwardRefValIDs.erase(I);
784 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
785 Name, nullptr, GlobalVariable::NotThreadLocal,
788 if (GVal->getValueType() != Ty)
790 "forward reference and definition of global have different types");
792 GV = cast<GlobalVariable>(GVal);
794 // Move the forward-reference to the correct spot in the module.
795 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
799 NumberedVals.push_back(GV);
801 // Set the parsed properties on the global.
803 GV->setInitializer(Init);
804 GV->setConstant(IsConstant);
805 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
806 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
807 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
808 GV->setExternallyInitialized(IsExternallyInitialized);
809 GV->setThreadLocalMode(TLM);
810 GV->setUnnamedAddr(UnnamedAddr);
812 // Parse attributes on the global.
813 while (Lex.getKind() == lltok::comma) {
816 if (Lex.getKind() == lltok::kw_section) {
818 GV->setSection(Lex.getStrVal());
819 if (ParseToken(lltok::StringConstant, "expected global section string"))
821 } else if (Lex.getKind() == lltok::kw_align) {
823 if (ParseOptionalAlignment(Alignment)) return true;
824 GV->setAlignment(Alignment);
827 if (parseOptionalComdat(Name, C))
832 return TokError("unknown global variable property!");
839 /// ParseUnnamedAttrGrp
840 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
841 bool LLParser::ParseUnnamedAttrGrp() {
842 assert(Lex.getKind() == lltok::kw_attributes);
843 LocTy AttrGrpLoc = Lex.getLoc();
846 if (Lex.getKind() != lltok::AttrGrpID)
847 return TokError("expected attribute group id");
849 unsigned VarID = Lex.getUIntVal();
850 std::vector<unsigned> unused;
854 if (ParseToken(lltok::equal, "expected '=' here") ||
855 ParseToken(lltok::lbrace, "expected '{' here") ||
856 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
858 ParseToken(lltok::rbrace, "expected end of attribute group"))
861 if (!NumberedAttrBuilders[VarID].hasAttributes())
862 return Error(AttrGrpLoc, "attribute group has no attributes");
867 /// ParseFnAttributeValuePairs
868 /// ::= <attr> | <attr> '=' <value>
869 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
870 std::vector<unsigned> &FwdRefAttrGrps,
871 bool inAttrGrp, LocTy &BuiltinLoc) {
872 bool HaveError = false;
877 lltok::Kind Token = Lex.getKind();
878 if (Token == lltok::kw_builtin)
879 BuiltinLoc = Lex.getLoc();
882 if (!inAttrGrp) return HaveError;
883 return Error(Lex.getLoc(), "unterminated attribute group");
888 case lltok::AttrGrpID: {
889 // Allow a function to reference an attribute group:
891 // define void @foo() #1 { ... }
895 "cannot have an attribute group reference in an attribute group");
897 unsigned AttrGrpNum = Lex.getUIntVal();
898 if (inAttrGrp) break;
900 // Save the reference to the attribute group. We'll fill it in later.
901 FwdRefAttrGrps.push_back(AttrGrpNum);
904 // Target-dependent attributes:
905 case lltok::StringConstant: {
906 std::string Attr = Lex.getStrVal();
909 if (EatIfPresent(lltok::equal) &&
910 ParseStringConstant(Val))
913 B.addAttribute(Attr, Val);
917 // Target-independent attributes:
918 case lltok::kw_align: {
919 // As a hack, we allow function alignment to be initially parsed as an
920 // attribute on a function declaration/definition or added to an attribute
921 // group and later moved to the alignment field.
925 if (ParseToken(lltok::equal, "expected '=' here") ||
926 ParseUInt32(Alignment))
929 if (ParseOptionalAlignment(Alignment))
932 B.addAlignmentAttr(Alignment);
935 case lltok::kw_alignstack: {
939 if (ParseToken(lltok::equal, "expected '=' here") ||
940 ParseUInt32(Alignment))
943 if (ParseOptionalStackAlignment(Alignment))
946 B.addStackAlignmentAttr(Alignment);
949 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
950 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
951 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
952 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
953 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
954 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
955 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
956 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
957 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
958 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
959 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
960 case lltok::kw_noimplicitfloat:
961 B.addAttribute(Attribute::NoImplicitFloat); break;
962 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
963 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
964 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
965 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
966 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
967 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
968 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
969 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
970 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
971 case lltok::kw_returns_twice:
972 B.addAttribute(Attribute::ReturnsTwice); break;
973 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
974 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
975 case lltok::kw_sspstrong:
976 B.addAttribute(Attribute::StackProtectStrong); break;
977 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
978 case lltok::kw_sanitize_address:
979 B.addAttribute(Attribute::SanitizeAddress); break;
980 case lltok::kw_sanitize_thread:
981 B.addAttribute(Attribute::SanitizeThread); break;
982 case lltok::kw_sanitize_memory:
983 B.addAttribute(Attribute::SanitizeMemory); break;
984 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
987 case lltok::kw_inreg:
988 case lltok::kw_signext:
989 case lltok::kw_zeroext:
992 "invalid use of attribute on a function");
994 case lltok::kw_byval:
995 case lltok::kw_dereferenceable:
996 case lltok::kw_dereferenceable_or_null:
997 case lltok::kw_inalloca:
999 case lltok::kw_noalias:
1000 case lltok::kw_nocapture:
1001 case lltok::kw_nonnull:
1002 case lltok::kw_returned:
1003 case lltok::kw_sret:
1006 "invalid use of parameter-only attribute on a function");
1014 //===----------------------------------------------------------------------===//
1015 // GlobalValue Reference/Resolution Routines.
1016 //===----------------------------------------------------------------------===//
1018 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1019 /// forward reference record if needed. This can return null if the value
1020 /// exists but does not have the right type.
1021 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1023 PointerType *PTy = dyn_cast<PointerType>(Ty);
1025 Error(Loc, "global variable reference must have pointer type");
1029 // Look this name up in the normal function symbol table.
1031 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1033 // If this is a forward reference for the value, see if we already created a
1034 // forward ref record.
1036 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1037 I = ForwardRefVals.find(Name);
1038 if (I != ForwardRefVals.end())
1039 Val = I->second.first;
1042 // If we have the value in the symbol table or fwd-ref table, return it.
1044 if (Val->getType() == Ty) return Val;
1045 Error(Loc, "'@" + Name + "' defined with type '" +
1046 getTypeString(Val->getType()) + "'");
1050 // Otherwise, create a new forward reference for this value and remember it.
1051 GlobalValue *FwdVal;
1052 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1053 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1055 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1056 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1057 nullptr, GlobalVariable::NotThreadLocal,
1058 PTy->getAddressSpace());
1060 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1064 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1065 PointerType *PTy = dyn_cast<PointerType>(Ty);
1067 Error(Loc, "global variable reference must have pointer type");
1071 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1073 // If this is a forward reference for the value, see if we already created a
1074 // forward ref record.
1076 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1077 I = ForwardRefValIDs.find(ID);
1078 if (I != ForwardRefValIDs.end())
1079 Val = I->second.first;
1082 // If we have the value in the symbol table or fwd-ref table, return it.
1084 if (Val->getType() == Ty) return Val;
1085 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1086 getTypeString(Val->getType()) + "'");
1090 // Otherwise, create a new forward reference for this value and remember it.
1091 GlobalValue *FwdVal;
1092 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1093 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1095 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1096 GlobalValue::ExternalWeakLinkage, nullptr, "");
1098 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1103 //===----------------------------------------------------------------------===//
1104 // Comdat Reference/Resolution Routines.
1105 //===----------------------------------------------------------------------===//
1107 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1108 // Look this name up in the comdat symbol table.
1109 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1110 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1111 if (I != ComdatSymTab.end())
1114 // Otherwise, create a new forward reference for this value and remember it.
1115 Comdat *C = M->getOrInsertComdat(Name);
1116 ForwardRefComdats[Name] = Loc;
1121 //===----------------------------------------------------------------------===//
1123 //===----------------------------------------------------------------------===//
1125 /// ParseToken - If the current token has the specified kind, eat it and return
1126 /// success. Otherwise, emit the specified error and return failure.
1127 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1128 if (Lex.getKind() != T)
1129 return TokError(ErrMsg);
1134 /// ParseStringConstant
1135 /// ::= StringConstant
1136 bool LLParser::ParseStringConstant(std::string &Result) {
1137 if (Lex.getKind() != lltok::StringConstant)
1138 return TokError("expected string constant");
1139 Result = Lex.getStrVal();
1146 bool LLParser::ParseUInt32(unsigned &Val) {
1147 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1148 return TokError("expected integer");
1149 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1150 if (Val64 != unsigned(Val64))
1151 return TokError("expected 32-bit integer (too large)");
1159 bool LLParser::ParseUInt64(uint64_t &Val) {
1160 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1161 return TokError("expected integer");
1162 Val = Lex.getAPSIntVal().getLimitedValue();
1168 /// := 'localdynamic'
1169 /// := 'initialexec'
1171 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1172 switch (Lex.getKind()) {
1174 return TokError("expected localdynamic, initialexec or localexec");
1175 case lltok::kw_localdynamic:
1176 TLM = GlobalVariable::LocalDynamicTLSModel;
1178 case lltok::kw_initialexec:
1179 TLM = GlobalVariable::InitialExecTLSModel;
1181 case lltok::kw_localexec:
1182 TLM = GlobalVariable::LocalExecTLSModel;
1190 /// ParseOptionalThreadLocal
1192 /// := 'thread_local'
1193 /// := 'thread_local' '(' tlsmodel ')'
1194 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1195 TLM = GlobalVariable::NotThreadLocal;
1196 if (!EatIfPresent(lltok::kw_thread_local))
1199 TLM = GlobalVariable::GeneralDynamicTLSModel;
1200 if (Lex.getKind() == lltok::lparen) {
1202 return ParseTLSModel(TLM) ||
1203 ParseToken(lltok::rparen, "expected ')' after thread local model");
1208 /// ParseOptionalAddrSpace
1210 /// := 'addrspace' '(' uint32 ')'
1211 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1213 if (!EatIfPresent(lltok::kw_addrspace))
1215 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1216 ParseUInt32(AddrSpace) ||
1217 ParseToken(lltok::rparen, "expected ')' in address space");
1220 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1221 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1222 bool HaveError = false;
1227 lltok::Kind Token = Lex.getKind();
1229 default: // End of attributes.
1231 case lltok::kw_align: {
1233 if (ParseOptionalAlignment(Alignment))
1235 B.addAlignmentAttr(Alignment);
1238 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1239 case lltok::kw_dereferenceable: {
1241 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1243 B.addDereferenceableAttr(Bytes);
1246 case lltok::kw_dereferenceable_or_null: {
1248 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1250 B.addDereferenceableOrNullAttr(Bytes);
1253 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1254 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1255 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1256 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1257 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1258 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1259 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1260 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1261 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1262 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1263 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1264 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1266 case lltok::kw_alignstack:
1267 case lltok::kw_alwaysinline:
1268 case lltok::kw_argmemonly:
1269 case lltok::kw_builtin:
1270 case lltok::kw_inlinehint:
1271 case lltok::kw_jumptable:
1272 case lltok::kw_minsize:
1273 case lltok::kw_naked:
1274 case lltok::kw_nobuiltin:
1275 case lltok::kw_noduplicate:
1276 case lltok::kw_noimplicitfloat:
1277 case lltok::kw_noinline:
1278 case lltok::kw_nonlazybind:
1279 case lltok::kw_noredzone:
1280 case lltok::kw_noreturn:
1281 case lltok::kw_nounwind:
1282 case lltok::kw_optnone:
1283 case lltok::kw_optsize:
1284 case lltok::kw_returns_twice:
1285 case lltok::kw_sanitize_address:
1286 case lltok::kw_sanitize_memory:
1287 case lltok::kw_sanitize_thread:
1289 case lltok::kw_sspreq:
1290 case lltok::kw_sspstrong:
1291 case lltok::kw_safestack:
1292 case lltok::kw_uwtable:
1293 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1301 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1302 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1303 bool HaveError = false;
1308 lltok::Kind Token = Lex.getKind();
1310 default: // End of attributes.
1312 case lltok::kw_dereferenceable: {
1314 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1316 B.addDereferenceableAttr(Bytes);
1319 case lltok::kw_dereferenceable_or_null: {
1321 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1323 B.addDereferenceableOrNullAttr(Bytes);
1326 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1327 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1328 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1329 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1330 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1333 case lltok::kw_align:
1334 case lltok::kw_byval:
1335 case lltok::kw_inalloca:
1336 case lltok::kw_nest:
1337 case lltok::kw_nocapture:
1338 case lltok::kw_returned:
1339 case lltok::kw_sret:
1340 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1343 case lltok::kw_alignstack:
1344 case lltok::kw_alwaysinline:
1345 case lltok::kw_argmemonly:
1346 case lltok::kw_builtin:
1347 case lltok::kw_cold:
1348 case lltok::kw_inlinehint:
1349 case lltok::kw_jumptable:
1350 case lltok::kw_minsize:
1351 case lltok::kw_naked:
1352 case lltok::kw_nobuiltin:
1353 case lltok::kw_noduplicate:
1354 case lltok::kw_noimplicitfloat:
1355 case lltok::kw_noinline:
1356 case lltok::kw_nonlazybind:
1357 case lltok::kw_noredzone:
1358 case lltok::kw_noreturn:
1359 case lltok::kw_nounwind:
1360 case lltok::kw_optnone:
1361 case lltok::kw_optsize:
1362 case lltok::kw_returns_twice:
1363 case lltok::kw_sanitize_address:
1364 case lltok::kw_sanitize_memory:
1365 case lltok::kw_sanitize_thread:
1367 case lltok::kw_sspreq:
1368 case lltok::kw_sspstrong:
1369 case lltok::kw_safestack:
1370 case lltok::kw_uwtable:
1371 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1374 case lltok::kw_readnone:
1375 case lltok::kw_readonly:
1376 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1383 /// ParseOptionalLinkage
1390 /// ::= 'linkonce_odr'
1391 /// ::= 'available_externally'
1394 /// ::= 'extern_weak'
1396 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1398 switch (Lex.getKind()) {
1399 default: Res=GlobalValue::ExternalLinkage; return false;
1400 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1401 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1402 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1403 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1404 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1405 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1406 case lltok::kw_available_externally:
1407 Res = GlobalValue::AvailableExternallyLinkage;
1409 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1410 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1411 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1412 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1419 /// ParseOptionalVisibility
1425 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1426 switch (Lex.getKind()) {
1427 default: Res = GlobalValue::DefaultVisibility; return false;
1428 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1429 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1430 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1436 /// ParseOptionalDLLStorageClass
1441 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1442 switch (Lex.getKind()) {
1443 default: Res = GlobalValue::DefaultStorageClass; return false;
1444 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1445 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1451 /// ParseOptionalCallingConv
1455 /// ::= 'intel_ocl_bicc'
1457 /// ::= 'x86_stdcallcc'
1458 /// ::= 'x86_fastcallcc'
1459 /// ::= 'x86_thiscallcc'
1460 /// ::= 'x86_vectorcallcc'
1461 /// ::= 'arm_apcscc'
1462 /// ::= 'arm_aapcscc'
1463 /// ::= 'arm_aapcs_vfpcc'
1464 /// ::= 'msp430_intrcc'
1465 /// ::= 'ptx_kernel'
1466 /// ::= 'ptx_device'
1468 /// ::= 'spir_kernel'
1469 /// ::= 'x86_64_sysvcc'
1470 /// ::= 'x86_64_win64cc'
1471 /// ::= 'webkit_jscc'
1473 /// ::= 'preserve_mostcc'
1474 /// ::= 'preserve_allcc'
1478 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1479 switch (Lex.getKind()) {
1480 default: CC = CallingConv::C; return false;
1481 case lltok::kw_ccc: CC = CallingConv::C; break;
1482 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1483 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1484 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1485 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1486 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1487 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1488 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1489 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1490 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1491 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1492 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1493 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1494 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1495 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1496 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1497 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1498 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1499 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1500 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1501 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1502 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1503 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1504 case lltok::kw_cc: {
1506 return ParseUInt32(CC);
1514 /// ParseMetadataAttachment
1516 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1517 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1519 std::string Name = Lex.getStrVal();
1520 Kind = M->getMDKindID(Name);
1523 return ParseMDNode(MD);
1526 /// ParseInstructionMetadata
1527 /// ::= !dbg !42 (',' !dbg !57)*
1528 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1530 if (Lex.getKind() != lltok::MetadataVar)
1531 return TokError("expected metadata after comma");
1535 if (ParseMetadataAttachment(MDK, N))
1538 Inst.setMetadata(MDK, N);
1539 if (MDK == LLVMContext::MD_tbaa)
1540 InstsWithTBAATag.push_back(&Inst);
1542 // If this is the end of the list, we're done.
1543 } while (EatIfPresent(lltok::comma));
1547 /// ParseOptionalFunctionMetadata
1549 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1550 while (Lex.getKind() == lltok::MetadataVar) {
1553 if (ParseMetadataAttachment(MDK, N))
1556 F.setMetadata(MDK, N);
1561 /// ParseOptionalAlignment
1564 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1566 if (!EatIfPresent(lltok::kw_align))
1568 LocTy AlignLoc = Lex.getLoc();
1569 if (ParseUInt32(Alignment)) return true;
1570 if (!isPowerOf2_32(Alignment))
1571 return Error(AlignLoc, "alignment is not a power of two");
1572 if (Alignment > Value::MaximumAlignment)
1573 return Error(AlignLoc, "huge alignments are not supported yet");
1577 /// ParseOptionalDerefAttrBytes
1579 /// ::= AttrKind '(' 4 ')'
1581 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1582 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1584 assert((AttrKind == lltok::kw_dereferenceable ||
1585 AttrKind == lltok::kw_dereferenceable_or_null) &&
1589 if (!EatIfPresent(AttrKind))
1591 LocTy ParenLoc = Lex.getLoc();
1592 if (!EatIfPresent(lltok::lparen))
1593 return Error(ParenLoc, "expected '('");
1594 LocTy DerefLoc = Lex.getLoc();
1595 if (ParseUInt64(Bytes)) return true;
1596 ParenLoc = Lex.getLoc();
1597 if (!EatIfPresent(lltok::rparen))
1598 return Error(ParenLoc, "expected ')'");
1600 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1604 /// ParseOptionalCommaAlign
1608 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1610 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1611 bool &AteExtraComma) {
1612 AteExtraComma = false;
1613 while (EatIfPresent(lltok::comma)) {
1614 // Metadata at the end is an early exit.
1615 if (Lex.getKind() == lltok::MetadataVar) {
1616 AteExtraComma = true;
1620 if (Lex.getKind() != lltok::kw_align)
1621 return Error(Lex.getLoc(), "expected metadata or 'align'");
1623 if (ParseOptionalAlignment(Alignment)) return true;
1629 /// ParseScopeAndOrdering
1630 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1633 /// This sets Scope and Ordering to the parsed values.
1634 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1635 AtomicOrdering &Ordering) {
1639 Scope = CrossThread;
1640 if (EatIfPresent(lltok::kw_singlethread))
1641 Scope = SingleThread;
1643 return ParseOrdering(Ordering);
1647 /// ::= AtomicOrdering
1649 /// This sets Ordering to the parsed value.
1650 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1651 switch (Lex.getKind()) {
1652 default: return TokError("Expected ordering on atomic instruction");
1653 case lltok::kw_unordered: Ordering = Unordered; break;
1654 case lltok::kw_monotonic: Ordering = Monotonic; break;
1655 case lltok::kw_acquire: Ordering = Acquire; break;
1656 case lltok::kw_release: Ordering = Release; break;
1657 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1658 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1664 /// ParseOptionalStackAlignment
1666 /// ::= 'alignstack' '(' 4 ')'
1667 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1669 if (!EatIfPresent(lltok::kw_alignstack))
1671 LocTy ParenLoc = Lex.getLoc();
1672 if (!EatIfPresent(lltok::lparen))
1673 return Error(ParenLoc, "expected '('");
1674 LocTy AlignLoc = Lex.getLoc();
1675 if (ParseUInt32(Alignment)) return true;
1676 ParenLoc = Lex.getLoc();
1677 if (!EatIfPresent(lltok::rparen))
1678 return Error(ParenLoc, "expected ')'");
1679 if (!isPowerOf2_32(Alignment))
1680 return Error(AlignLoc, "stack alignment is not a power of two");
1684 /// ParseIndexList - This parses the index list for an insert/extractvalue
1685 /// instruction. This sets AteExtraComma in the case where we eat an extra
1686 /// comma at the end of the line and find that it is followed by metadata.
1687 /// Clients that don't allow metadata can call the version of this function that
1688 /// only takes one argument.
1691 /// ::= (',' uint32)+
1693 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1694 bool &AteExtraComma) {
1695 AteExtraComma = false;
1697 if (Lex.getKind() != lltok::comma)
1698 return TokError("expected ',' as start of index list");
1700 while (EatIfPresent(lltok::comma)) {
1701 if (Lex.getKind() == lltok::MetadataVar) {
1702 if (Indices.empty()) return TokError("expected index");
1703 AteExtraComma = true;
1707 if (ParseUInt32(Idx)) return true;
1708 Indices.push_back(Idx);
1714 //===----------------------------------------------------------------------===//
1716 //===----------------------------------------------------------------------===//
1718 /// ParseType - Parse a type.
1719 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1720 SMLoc TypeLoc = Lex.getLoc();
1721 switch (Lex.getKind()) {
1723 return TokError(Msg);
1725 // Type ::= 'float' | 'void' (etc)
1726 Result = Lex.getTyVal();
1730 // Type ::= StructType
1731 if (ParseAnonStructType(Result, false))
1734 case lltok::lsquare:
1735 // Type ::= '[' ... ']'
1736 Lex.Lex(); // eat the lsquare.
1737 if (ParseArrayVectorType(Result, false))
1740 case lltok::less: // Either vector or packed struct.
1741 // Type ::= '<' ... '>'
1743 if (Lex.getKind() == lltok::lbrace) {
1744 if (ParseAnonStructType(Result, true) ||
1745 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1747 } else if (ParseArrayVectorType(Result, true))
1750 case lltok::LocalVar: {
1752 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1754 // If the type hasn't been defined yet, create a forward definition and
1755 // remember where that forward def'n was seen (in case it never is defined).
1757 Entry.first = StructType::create(Context, Lex.getStrVal());
1758 Entry.second = Lex.getLoc();
1760 Result = Entry.first;
1765 case lltok::LocalVarID: {
1767 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1769 // If the type hasn't been defined yet, create a forward definition and
1770 // remember where that forward def'n was seen (in case it never is defined).
1772 Entry.first = StructType::create(Context);
1773 Entry.second = Lex.getLoc();
1775 Result = Entry.first;
1781 // Parse the type suffixes.
1783 switch (Lex.getKind()) {
1786 if (!AllowVoid && Result->isVoidTy())
1787 return Error(TypeLoc, "void type only allowed for function results");
1790 // Type ::= Type '*'
1792 if (Result->isLabelTy())
1793 return TokError("basic block pointers are invalid");
1794 if (Result->isVoidTy())
1795 return TokError("pointers to void are invalid - use i8* instead");
1796 if (!PointerType::isValidElementType(Result))
1797 return TokError("pointer to this type is invalid");
1798 Result = PointerType::getUnqual(Result);
1802 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1803 case lltok::kw_addrspace: {
1804 if (Result->isLabelTy())
1805 return TokError("basic block pointers are invalid");
1806 if (Result->isVoidTy())
1807 return TokError("pointers to void are invalid; use i8* instead");
1808 if (!PointerType::isValidElementType(Result))
1809 return TokError("pointer to this type is invalid");
1811 if (ParseOptionalAddrSpace(AddrSpace) ||
1812 ParseToken(lltok::star, "expected '*' in address space"))
1815 Result = PointerType::get(Result, AddrSpace);
1819 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1821 if (ParseFunctionType(Result))
1828 /// ParseParameterList
1830 /// ::= '(' Arg (',' Arg)* ')'
1832 /// ::= Type OptionalAttributes Value OptionalAttributes
1833 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1834 PerFunctionState &PFS, bool IsMustTailCall,
1835 bool InVarArgsFunc) {
1836 if (ParseToken(lltok::lparen, "expected '(' in call"))
1839 unsigned AttrIndex = 1;
1840 while (Lex.getKind() != lltok::rparen) {
1841 // If this isn't the first argument, we need a comma.
1842 if (!ArgList.empty() &&
1843 ParseToken(lltok::comma, "expected ',' in argument list"))
1846 // Parse an ellipsis if this is a musttail call in a variadic function.
1847 if (Lex.getKind() == lltok::dotdotdot) {
1848 const char *Msg = "unexpected ellipsis in argument list for ";
1849 if (!IsMustTailCall)
1850 return TokError(Twine(Msg) + "non-musttail call");
1852 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1853 Lex.Lex(); // Lex the '...', it is purely for readability.
1854 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1857 // Parse the argument.
1859 Type *ArgTy = nullptr;
1860 AttrBuilder ArgAttrs;
1862 if (ParseType(ArgTy, ArgLoc))
1865 if (ArgTy->isMetadataTy()) {
1866 if (ParseMetadataAsValue(V, PFS))
1869 // Otherwise, handle normal operands.
1870 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1873 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1878 if (IsMustTailCall && InVarArgsFunc)
1879 return TokError("expected '...' at end of argument list for musttail call "
1880 "in varargs function");
1882 Lex.Lex(); // Lex the ')'.
1888 /// ParseArgumentList - Parse the argument list for a function type or function
1890 /// ::= '(' ArgTypeListI ')'
1894 /// ::= ArgTypeList ',' '...'
1895 /// ::= ArgType (',' ArgType)*
1897 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1900 assert(Lex.getKind() == lltok::lparen);
1901 Lex.Lex(); // eat the (.
1903 if (Lex.getKind() == lltok::rparen) {
1905 } else if (Lex.getKind() == lltok::dotdotdot) {
1909 LocTy TypeLoc = Lex.getLoc();
1910 Type *ArgTy = nullptr;
1914 if (ParseType(ArgTy) ||
1915 ParseOptionalParamAttrs(Attrs)) return true;
1917 if (ArgTy->isVoidTy())
1918 return Error(TypeLoc, "argument can not have void type");
1920 if (Lex.getKind() == lltok::LocalVar) {
1921 Name = Lex.getStrVal();
1925 if (!FunctionType::isValidArgumentType(ArgTy))
1926 return Error(TypeLoc, "invalid type for function argument");
1928 unsigned AttrIndex = 1;
1929 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1930 AttrIndex++, Attrs),
1933 while (EatIfPresent(lltok::comma)) {
1934 // Handle ... at end of arg list.
1935 if (EatIfPresent(lltok::dotdotdot)) {
1940 // Otherwise must be an argument type.
1941 TypeLoc = Lex.getLoc();
1942 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1944 if (ArgTy->isVoidTy())
1945 return Error(TypeLoc, "argument can not have void type");
1947 if (Lex.getKind() == lltok::LocalVar) {
1948 Name = Lex.getStrVal();
1954 if (!ArgTy->isFirstClassType())
1955 return Error(TypeLoc, "invalid type for function argument");
1957 ArgList.emplace_back(
1959 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1964 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1967 /// ParseFunctionType
1968 /// ::= Type ArgumentList OptionalAttrs
1969 bool LLParser::ParseFunctionType(Type *&Result) {
1970 assert(Lex.getKind() == lltok::lparen);
1972 if (!FunctionType::isValidReturnType(Result))
1973 return TokError("invalid function return type");
1975 SmallVector<ArgInfo, 8> ArgList;
1977 if (ParseArgumentList(ArgList, isVarArg))
1980 // Reject names on the arguments lists.
1981 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1982 if (!ArgList[i].Name.empty())
1983 return Error(ArgList[i].Loc, "argument name invalid in function type");
1984 if (ArgList[i].Attrs.hasAttributes(i + 1))
1985 return Error(ArgList[i].Loc,
1986 "argument attributes invalid in function type");
1989 SmallVector<Type*, 16> ArgListTy;
1990 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1991 ArgListTy.push_back(ArgList[i].Ty);
1993 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1997 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1999 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2000 SmallVector<Type*, 8> Elts;
2001 if (ParseStructBody(Elts)) return true;
2003 Result = StructType::get(Context, Elts, Packed);
2007 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2008 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2009 std::pair<Type*, LocTy> &Entry,
2011 // If the type was already defined, diagnose the redefinition.
2012 if (Entry.first && !Entry.second.isValid())
2013 return Error(TypeLoc, "redefinition of type");
2015 // If we have opaque, just return without filling in the definition for the
2016 // struct. This counts as a definition as far as the .ll file goes.
2017 if (EatIfPresent(lltok::kw_opaque)) {
2018 // This type is being defined, so clear the location to indicate this.
2019 Entry.second = SMLoc();
2021 // If this type number has never been uttered, create it.
2023 Entry.first = StructType::create(Context, Name);
2024 ResultTy = Entry.first;
2028 // If the type starts with '<', then it is either a packed struct or a vector.
2029 bool isPacked = EatIfPresent(lltok::less);
2031 // If we don't have a struct, then we have a random type alias, which we
2032 // accept for compatibility with old files. These types are not allowed to be
2033 // forward referenced and not allowed to be recursive.
2034 if (Lex.getKind() != lltok::lbrace) {
2036 return Error(TypeLoc, "forward references to non-struct type");
2040 return ParseArrayVectorType(ResultTy, true);
2041 return ParseType(ResultTy);
2044 // This type is being defined, so clear the location to indicate this.
2045 Entry.second = SMLoc();
2047 // If this type number has never been uttered, create it.
2049 Entry.first = StructType::create(Context, Name);
2051 StructType *STy = cast<StructType>(Entry.first);
2053 SmallVector<Type*, 8> Body;
2054 if (ParseStructBody(Body) ||
2055 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2058 STy->setBody(Body, isPacked);
2064 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2067 /// ::= '{' Type (',' Type)* '}'
2068 /// ::= '<' '{' '}' '>'
2069 /// ::= '<' '{' Type (',' Type)* '}' '>'
2070 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2071 assert(Lex.getKind() == lltok::lbrace);
2072 Lex.Lex(); // Consume the '{'
2074 // Handle the empty struct.
2075 if (EatIfPresent(lltok::rbrace))
2078 LocTy EltTyLoc = Lex.getLoc();
2080 if (ParseType(Ty)) return true;
2083 if (!StructType::isValidElementType(Ty))
2084 return Error(EltTyLoc, "invalid element type for struct");
2086 while (EatIfPresent(lltok::comma)) {
2087 EltTyLoc = Lex.getLoc();
2088 if (ParseType(Ty)) return true;
2090 if (!StructType::isValidElementType(Ty))
2091 return Error(EltTyLoc, "invalid element type for struct");
2096 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2099 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2100 /// token has already been consumed.
2102 /// ::= '[' APSINTVAL 'x' Types ']'
2103 /// ::= '<' APSINTVAL 'x' Types '>'
2104 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2105 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2106 Lex.getAPSIntVal().getBitWidth() > 64)
2107 return TokError("expected number in address space");
2109 LocTy SizeLoc = Lex.getLoc();
2110 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2113 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2116 LocTy TypeLoc = Lex.getLoc();
2117 Type *EltTy = nullptr;
2118 if (ParseType(EltTy)) return true;
2120 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2121 "expected end of sequential type"))
2126 return Error(SizeLoc, "zero element vector is illegal");
2127 if ((unsigned)Size != Size)
2128 return Error(SizeLoc, "size too large for vector");
2129 if (!VectorType::isValidElementType(EltTy))
2130 return Error(TypeLoc, "invalid vector element type");
2131 Result = VectorType::get(EltTy, unsigned(Size));
2133 if (!ArrayType::isValidElementType(EltTy))
2134 return Error(TypeLoc, "invalid array element type");
2135 Result = ArrayType::get(EltTy, Size);
2140 //===----------------------------------------------------------------------===//
2141 // Function Semantic Analysis.
2142 //===----------------------------------------------------------------------===//
2144 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2146 : P(p), F(f), FunctionNumber(functionNumber) {
2148 // Insert unnamed arguments into the NumberedVals list.
2149 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2152 NumberedVals.push_back(AI);
2155 LLParser::PerFunctionState::~PerFunctionState() {
2156 // If there were any forward referenced non-basicblock values, delete them.
2157 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2158 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2159 if (!isa<BasicBlock>(I->second.first)) {
2160 I->second.first->replaceAllUsesWith(
2161 UndefValue::get(I->second.first->getType()));
2162 delete I->second.first;
2163 I->second.first = nullptr;
2166 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2167 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2168 if (!isa<BasicBlock>(I->second.first)) {
2169 I->second.first->replaceAllUsesWith(
2170 UndefValue::get(I->second.first->getType()));
2171 delete I->second.first;
2172 I->second.first = nullptr;
2176 bool LLParser::PerFunctionState::FinishFunction() {
2177 if (!ForwardRefVals.empty())
2178 return P.Error(ForwardRefVals.begin()->second.second,
2179 "use of undefined value '%" + ForwardRefVals.begin()->first +
2181 if (!ForwardRefValIDs.empty())
2182 return P.Error(ForwardRefValIDs.begin()->second.second,
2183 "use of undefined value '%" +
2184 Twine(ForwardRefValIDs.begin()->first) + "'");
2189 /// GetVal - Get a value with the specified name or ID, creating a
2190 /// forward reference record if needed. This can return null if the value
2191 /// exists but does not have the right type.
2192 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2193 Type *Ty, LocTy Loc) {
2194 // Look this name up in the normal function symbol table.
2195 Value *Val = F.getValueSymbolTable().lookup(Name);
2197 // If this is a forward reference for the value, see if we already created a
2198 // forward ref record.
2200 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2201 I = ForwardRefVals.find(Name);
2202 if (I != ForwardRefVals.end())
2203 Val = I->second.first;
2206 // If we have the value in the symbol table or fwd-ref table, return it.
2208 if (Val->getType() == Ty) return Val;
2209 if (Ty->isLabelTy())
2210 P.Error(Loc, "'%" + Name + "' is not a basic block");
2212 P.Error(Loc, "'%" + Name + "' defined with type '" +
2213 getTypeString(Val->getType()) + "'");
2217 // Don't make placeholders with invalid type.
2218 if (!Ty->isFirstClassType()) {
2219 P.Error(Loc, "invalid use of a non-first-class type");
2223 // Otherwise, create a new forward reference for this value and remember it.
2225 if (Ty->isLabelTy())
2226 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2228 FwdVal = new Argument(Ty, Name);
2230 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2234 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2236 // Look this name up in the normal function symbol table.
2237 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2239 // If this is a forward reference for the value, see if we already created a
2240 // forward ref record.
2242 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2243 I = ForwardRefValIDs.find(ID);
2244 if (I != ForwardRefValIDs.end())
2245 Val = I->second.first;
2248 // If we have the value in the symbol table or fwd-ref table, return it.
2250 if (Val->getType() == Ty) return Val;
2251 if (Ty->isLabelTy())
2252 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2254 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2255 getTypeString(Val->getType()) + "'");
2259 if (!Ty->isFirstClassType()) {
2260 P.Error(Loc, "invalid use of a non-first-class type");
2264 // Otherwise, create a new forward reference for this value and remember it.
2266 if (Ty->isLabelTy())
2267 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2269 FwdVal = new Argument(Ty);
2271 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2275 /// SetInstName - After an instruction is parsed and inserted into its
2276 /// basic block, this installs its name.
2277 bool LLParser::PerFunctionState::SetInstName(int NameID,
2278 const std::string &NameStr,
2279 LocTy NameLoc, Instruction *Inst) {
2280 // If this instruction has void type, it cannot have a name or ID specified.
2281 if (Inst->getType()->isVoidTy()) {
2282 if (NameID != -1 || !NameStr.empty())
2283 return P.Error(NameLoc, "instructions returning void cannot have a name");
2287 // If this was a numbered instruction, verify that the instruction is the
2288 // expected value and resolve any forward references.
2289 if (NameStr.empty()) {
2290 // If neither a name nor an ID was specified, just use the next ID.
2292 NameID = NumberedVals.size();
2294 if (unsigned(NameID) != NumberedVals.size())
2295 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2296 Twine(NumberedVals.size()) + "'");
2298 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2299 ForwardRefValIDs.find(NameID);
2300 if (FI != ForwardRefValIDs.end()) {
2301 if (FI->second.first->getType() != Inst->getType())
2302 return P.Error(NameLoc, "instruction forward referenced with type '" +
2303 getTypeString(FI->second.first->getType()) + "'");
2304 FI->second.first->replaceAllUsesWith(Inst);
2305 delete FI->second.first;
2306 ForwardRefValIDs.erase(FI);
2309 NumberedVals.push_back(Inst);
2313 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2314 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2315 FI = ForwardRefVals.find(NameStr);
2316 if (FI != ForwardRefVals.end()) {
2317 if (FI->second.first->getType() != Inst->getType())
2318 return P.Error(NameLoc, "instruction forward referenced with type '" +
2319 getTypeString(FI->second.first->getType()) + "'");
2320 FI->second.first->replaceAllUsesWith(Inst);
2321 delete FI->second.first;
2322 ForwardRefVals.erase(FI);
2325 // Set the name on the instruction.
2326 Inst->setName(NameStr);
2328 if (Inst->getName() != NameStr)
2329 return P.Error(NameLoc, "multiple definition of local value named '" +
2334 /// GetBB - Get a basic block with the specified name or ID, creating a
2335 /// forward reference record if needed.
2336 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2338 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2339 Type::getLabelTy(F.getContext()), Loc));
2342 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2343 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2344 Type::getLabelTy(F.getContext()), Loc));
2347 /// DefineBB - Define the specified basic block, which is either named or
2348 /// unnamed. If there is an error, this returns null otherwise it returns
2349 /// the block being defined.
2350 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2354 BB = GetBB(NumberedVals.size(), Loc);
2356 BB = GetBB(Name, Loc);
2357 if (!BB) return nullptr; // Already diagnosed error.
2359 // Move the block to the end of the function. Forward ref'd blocks are
2360 // inserted wherever they happen to be referenced.
2361 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2363 // Remove the block from forward ref sets.
2365 ForwardRefValIDs.erase(NumberedVals.size());
2366 NumberedVals.push_back(BB);
2368 // BB forward references are already in the function symbol table.
2369 ForwardRefVals.erase(Name);
2375 //===----------------------------------------------------------------------===//
2377 //===----------------------------------------------------------------------===//
2379 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2380 /// type implied. For example, if we parse "4" we don't know what integer type
2381 /// it has. The value will later be combined with its type and checked for
2382 /// sanity. PFS is used to convert function-local operands of metadata (since
2383 /// metadata operands are not just parsed here but also converted to values).
2384 /// PFS can be null when we are not parsing metadata values inside a function.
2385 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2386 ID.Loc = Lex.getLoc();
2387 switch (Lex.getKind()) {
2388 default: return TokError("expected value token");
2389 case lltok::GlobalID: // @42
2390 ID.UIntVal = Lex.getUIntVal();
2391 ID.Kind = ValID::t_GlobalID;
2393 case lltok::GlobalVar: // @foo
2394 ID.StrVal = Lex.getStrVal();
2395 ID.Kind = ValID::t_GlobalName;
2397 case lltok::LocalVarID: // %42
2398 ID.UIntVal = Lex.getUIntVal();
2399 ID.Kind = ValID::t_LocalID;
2401 case lltok::LocalVar: // %foo
2402 ID.StrVal = Lex.getStrVal();
2403 ID.Kind = ValID::t_LocalName;
2406 ID.APSIntVal = Lex.getAPSIntVal();
2407 ID.Kind = ValID::t_APSInt;
2409 case lltok::APFloat:
2410 ID.APFloatVal = Lex.getAPFloatVal();
2411 ID.Kind = ValID::t_APFloat;
2413 case lltok::kw_true:
2414 ID.ConstantVal = ConstantInt::getTrue(Context);
2415 ID.Kind = ValID::t_Constant;
2417 case lltok::kw_false:
2418 ID.ConstantVal = ConstantInt::getFalse(Context);
2419 ID.Kind = ValID::t_Constant;
2421 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2422 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2423 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2425 case lltok::lbrace: {
2426 // ValID ::= '{' ConstVector '}'
2428 SmallVector<Constant*, 16> Elts;
2429 if (ParseGlobalValueVector(Elts) ||
2430 ParseToken(lltok::rbrace, "expected end of struct constant"))
2433 ID.ConstantStructElts = new Constant*[Elts.size()];
2434 ID.UIntVal = Elts.size();
2435 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2436 ID.Kind = ValID::t_ConstantStruct;
2440 // ValID ::= '<' ConstVector '>' --> Vector.
2441 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2443 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2445 SmallVector<Constant*, 16> Elts;
2446 LocTy FirstEltLoc = Lex.getLoc();
2447 if (ParseGlobalValueVector(Elts) ||
2449 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2450 ParseToken(lltok::greater, "expected end of constant"))
2453 if (isPackedStruct) {
2454 ID.ConstantStructElts = new Constant*[Elts.size()];
2455 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2456 ID.UIntVal = Elts.size();
2457 ID.Kind = ValID::t_PackedConstantStruct;
2462 return Error(ID.Loc, "constant vector must not be empty");
2464 if (!Elts[0]->getType()->isIntegerTy() &&
2465 !Elts[0]->getType()->isFloatingPointTy() &&
2466 !Elts[0]->getType()->isPointerTy())
2467 return Error(FirstEltLoc,
2468 "vector elements must have integer, pointer or floating point type");
2470 // Verify that all the vector elements have the same type.
2471 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2472 if (Elts[i]->getType() != Elts[0]->getType())
2473 return Error(FirstEltLoc,
2474 "vector element #" + Twine(i) +
2475 " is not of type '" + getTypeString(Elts[0]->getType()));
2477 ID.ConstantVal = ConstantVector::get(Elts);
2478 ID.Kind = ValID::t_Constant;
2481 case lltok::lsquare: { // Array Constant
2483 SmallVector<Constant*, 16> Elts;
2484 LocTy FirstEltLoc = Lex.getLoc();
2485 if (ParseGlobalValueVector(Elts) ||
2486 ParseToken(lltok::rsquare, "expected end of array constant"))
2489 // Handle empty element.
2491 // Use undef instead of an array because it's inconvenient to determine
2492 // the element type at this point, there being no elements to examine.
2493 ID.Kind = ValID::t_EmptyArray;
2497 if (!Elts[0]->getType()->isFirstClassType())
2498 return Error(FirstEltLoc, "invalid array element type: " +
2499 getTypeString(Elts[0]->getType()));
2501 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2503 // Verify all elements are correct type!
2504 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2505 if (Elts[i]->getType() != Elts[0]->getType())
2506 return Error(FirstEltLoc,
2507 "array element #" + Twine(i) +
2508 " is not of type '" + getTypeString(Elts[0]->getType()));
2511 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2512 ID.Kind = ValID::t_Constant;
2515 case lltok::kw_c: // c "foo"
2517 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2519 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2520 ID.Kind = ValID::t_Constant;
2523 case lltok::kw_asm: {
2524 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2526 bool HasSideEffect, AlignStack, AsmDialect;
2528 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2529 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2530 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2531 ParseStringConstant(ID.StrVal) ||
2532 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2533 ParseToken(lltok::StringConstant, "expected constraint string"))
2535 ID.StrVal2 = Lex.getStrVal();
2536 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2537 (unsigned(AsmDialect)<<2);
2538 ID.Kind = ValID::t_InlineAsm;
2542 case lltok::kw_blockaddress: {
2543 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2548 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2550 ParseToken(lltok::comma, "expected comma in block address expression")||
2551 ParseValID(Label) ||
2552 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2555 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2556 return Error(Fn.Loc, "expected function name in blockaddress");
2557 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2558 return Error(Label.Loc, "expected basic block name in blockaddress");
2560 // Try to find the function (but skip it if it's forward-referenced).
2561 GlobalValue *GV = nullptr;
2562 if (Fn.Kind == ValID::t_GlobalID) {
2563 if (Fn.UIntVal < NumberedVals.size())
2564 GV = NumberedVals[Fn.UIntVal];
2565 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2566 GV = M->getNamedValue(Fn.StrVal);
2568 Function *F = nullptr;
2570 // Confirm that it's actually a function with a definition.
2571 if (!isa<Function>(GV))
2572 return Error(Fn.Loc, "expected function name in blockaddress");
2573 F = cast<Function>(GV);
2574 if (F->isDeclaration())
2575 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2579 // Make a global variable as a placeholder for this reference.
2580 GlobalValue *&FwdRef =
2581 ForwardRefBlockAddresses.insert(std::make_pair(
2583 std::map<ValID, GlobalValue *>()))
2584 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2587 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2588 GlobalValue::InternalLinkage, nullptr, "");
2589 ID.ConstantVal = FwdRef;
2590 ID.Kind = ValID::t_Constant;
2594 // We found the function; now find the basic block. Don't use PFS, since we
2595 // might be inside a constant expression.
2597 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2598 if (Label.Kind == ValID::t_LocalID)
2599 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2601 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2603 return Error(Label.Loc, "referenced value is not a basic block");
2605 if (Label.Kind == ValID::t_LocalID)
2606 return Error(Label.Loc, "cannot take address of numeric label after "
2607 "the function is defined");
2608 BB = dyn_cast_or_null<BasicBlock>(
2609 F->getValueSymbolTable().lookup(Label.StrVal));
2611 return Error(Label.Loc, "referenced value is not a basic block");
2614 ID.ConstantVal = BlockAddress::get(F, BB);
2615 ID.Kind = ValID::t_Constant;
2619 case lltok::kw_trunc:
2620 case lltok::kw_zext:
2621 case lltok::kw_sext:
2622 case lltok::kw_fptrunc:
2623 case lltok::kw_fpext:
2624 case lltok::kw_bitcast:
2625 case lltok::kw_addrspacecast:
2626 case lltok::kw_uitofp:
2627 case lltok::kw_sitofp:
2628 case lltok::kw_fptoui:
2629 case lltok::kw_fptosi:
2630 case lltok::kw_inttoptr:
2631 case lltok::kw_ptrtoint: {
2632 unsigned Opc = Lex.getUIntVal();
2633 Type *DestTy = nullptr;
2636 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2637 ParseGlobalTypeAndValue(SrcVal) ||
2638 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2639 ParseType(DestTy) ||
2640 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2642 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2643 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2644 getTypeString(SrcVal->getType()) + "' to '" +
2645 getTypeString(DestTy) + "'");
2646 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2648 ID.Kind = ValID::t_Constant;
2651 case lltok::kw_extractvalue: {
2654 SmallVector<unsigned, 4> Indices;
2655 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2656 ParseGlobalTypeAndValue(Val) ||
2657 ParseIndexList(Indices) ||
2658 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2661 if (!Val->getType()->isAggregateType())
2662 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2663 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2664 return Error(ID.Loc, "invalid indices for extractvalue");
2665 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2666 ID.Kind = ValID::t_Constant;
2669 case lltok::kw_insertvalue: {
2671 Constant *Val0, *Val1;
2672 SmallVector<unsigned, 4> Indices;
2673 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2674 ParseGlobalTypeAndValue(Val0) ||
2675 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2676 ParseGlobalTypeAndValue(Val1) ||
2677 ParseIndexList(Indices) ||
2678 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2680 if (!Val0->getType()->isAggregateType())
2681 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2683 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2685 return Error(ID.Loc, "invalid indices for insertvalue");
2686 if (IndexedType != Val1->getType())
2687 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2688 getTypeString(Val1->getType()) +
2689 "' instead of '" + getTypeString(IndexedType) +
2691 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2692 ID.Kind = ValID::t_Constant;
2695 case lltok::kw_icmp:
2696 case lltok::kw_fcmp: {
2697 unsigned PredVal, Opc = Lex.getUIntVal();
2698 Constant *Val0, *Val1;
2700 if (ParseCmpPredicate(PredVal, Opc) ||
2701 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2702 ParseGlobalTypeAndValue(Val0) ||
2703 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2704 ParseGlobalTypeAndValue(Val1) ||
2705 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2708 if (Val0->getType() != Val1->getType())
2709 return Error(ID.Loc, "compare operands must have the same type");
2711 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2713 if (Opc == Instruction::FCmp) {
2714 if (!Val0->getType()->isFPOrFPVectorTy())
2715 return Error(ID.Loc, "fcmp requires floating point operands");
2716 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2718 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2719 if (!Val0->getType()->isIntOrIntVectorTy() &&
2720 !Val0->getType()->getScalarType()->isPointerTy())
2721 return Error(ID.Loc, "icmp requires pointer or integer operands");
2722 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2724 ID.Kind = ValID::t_Constant;
2728 // Binary Operators.
2730 case lltok::kw_fadd:
2732 case lltok::kw_fsub:
2734 case lltok::kw_fmul:
2735 case lltok::kw_udiv:
2736 case lltok::kw_sdiv:
2737 case lltok::kw_fdiv:
2738 case lltok::kw_urem:
2739 case lltok::kw_srem:
2740 case lltok::kw_frem:
2742 case lltok::kw_lshr:
2743 case lltok::kw_ashr: {
2747 unsigned Opc = Lex.getUIntVal();
2748 Constant *Val0, *Val1;
2750 LocTy ModifierLoc = Lex.getLoc();
2751 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2752 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2753 if (EatIfPresent(lltok::kw_nuw))
2755 if (EatIfPresent(lltok::kw_nsw)) {
2757 if (EatIfPresent(lltok::kw_nuw))
2760 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2761 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2762 if (EatIfPresent(lltok::kw_exact))
2765 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2766 ParseGlobalTypeAndValue(Val0) ||
2767 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2768 ParseGlobalTypeAndValue(Val1) ||
2769 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2771 if (Val0->getType() != Val1->getType())
2772 return Error(ID.Loc, "operands of constexpr must have same type");
2773 if (!Val0->getType()->isIntOrIntVectorTy()) {
2775 return Error(ModifierLoc, "nuw only applies to integer operations");
2777 return Error(ModifierLoc, "nsw only applies to integer operations");
2779 // Check that the type is valid for the operator.
2781 case Instruction::Add:
2782 case Instruction::Sub:
2783 case Instruction::Mul:
2784 case Instruction::UDiv:
2785 case Instruction::SDiv:
2786 case Instruction::URem:
2787 case Instruction::SRem:
2788 case Instruction::Shl:
2789 case Instruction::AShr:
2790 case Instruction::LShr:
2791 if (!Val0->getType()->isIntOrIntVectorTy())
2792 return Error(ID.Loc, "constexpr requires integer operands");
2794 case Instruction::FAdd:
2795 case Instruction::FSub:
2796 case Instruction::FMul:
2797 case Instruction::FDiv:
2798 case Instruction::FRem:
2799 if (!Val0->getType()->isFPOrFPVectorTy())
2800 return Error(ID.Loc, "constexpr requires fp operands");
2802 default: llvm_unreachable("Unknown binary operator!");
2805 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2806 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2807 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2808 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2810 ID.Kind = ValID::t_Constant;
2814 // Logical Operations
2817 case lltok::kw_xor: {
2818 unsigned Opc = Lex.getUIntVal();
2819 Constant *Val0, *Val1;
2821 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2822 ParseGlobalTypeAndValue(Val0) ||
2823 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2824 ParseGlobalTypeAndValue(Val1) ||
2825 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2827 if (Val0->getType() != Val1->getType())
2828 return Error(ID.Loc, "operands of constexpr must have same type");
2829 if (!Val0->getType()->isIntOrIntVectorTy())
2830 return Error(ID.Loc,
2831 "constexpr requires integer or integer vector operands");
2832 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2833 ID.Kind = ValID::t_Constant;
2837 case lltok::kw_getelementptr:
2838 case lltok::kw_shufflevector:
2839 case lltok::kw_insertelement:
2840 case lltok::kw_extractelement:
2841 case lltok::kw_select: {
2842 unsigned Opc = Lex.getUIntVal();
2843 SmallVector<Constant*, 16> Elts;
2844 bool InBounds = false;
2848 if (Opc == Instruction::GetElementPtr)
2849 InBounds = EatIfPresent(lltok::kw_inbounds);
2851 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2854 LocTy ExplicitTypeLoc = Lex.getLoc();
2855 if (Opc == Instruction::GetElementPtr) {
2856 if (ParseType(Ty) ||
2857 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2861 if (ParseGlobalValueVector(Elts) ||
2862 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2865 if (Opc == Instruction::GetElementPtr) {
2866 if (Elts.size() == 0 ||
2867 !Elts[0]->getType()->getScalarType()->isPointerTy())
2868 return Error(ID.Loc, "base of getelementptr must be a pointer");
2870 Type *BaseType = Elts[0]->getType();
2871 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2872 if (Ty != BasePointerType->getElementType())
2875 "explicit pointee type doesn't match operand's pointee type");
2877 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2878 for (Constant *Val : Indices) {
2879 Type *ValTy = Val->getType();
2880 if (!ValTy->getScalarType()->isIntegerTy())
2881 return Error(ID.Loc, "getelementptr index must be an integer");
2882 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2883 return Error(ID.Loc, "getelementptr index type missmatch");
2884 if (ValTy->isVectorTy()) {
2885 unsigned ValNumEl = ValTy->getVectorNumElements();
2886 unsigned PtrNumEl = BaseType->getVectorNumElements();
2887 if (ValNumEl != PtrNumEl)
2890 "getelementptr vector index has a wrong number of elements");
2894 SmallPtrSet<const Type*, 4> Visited;
2895 if (!Indices.empty() && !Ty->isSized(&Visited))
2896 return Error(ID.Loc, "base element of getelementptr must be sized");
2898 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2899 return Error(ID.Loc, "invalid getelementptr indices");
2901 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2902 } else if (Opc == Instruction::Select) {
2903 if (Elts.size() != 3)
2904 return Error(ID.Loc, "expected three operands to select");
2905 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2907 return Error(ID.Loc, Reason);
2908 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2909 } else if (Opc == Instruction::ShuffleVector) {
2910 if (Elts.size() != 3)
2911 return Error(ID.Loc, "expected three operands to shufflevector");
2912 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2913 return Error(ID.Loc, "invalid operands to shufflevector");
2915 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2916 } else if (Opc == Instruction::ExtractElement) {
2917 if (Elts.size() != 2)
2918 return Error(ID.Loc, "expected two operands to extractelement");
2919 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2920 return Error(ID.Loc, "invalid extractelement operands");
2921 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2923 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2924 if (Elts.size() != 3)
2925 return Error(ID.Loc, "expected three operands to insertelement");
2926 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2927 return Error(ID.Loc, "invalid insertelement operands");
2929 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2932 ID.Kind = ValID::t_Constant;
2941 /// ParseGlobalValue - Parse a global value with the specified type.
2942 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2946 bool Parsed = ParseValID(ID) ||
2947 ConvertValIDToValue(Ty, ID, V, nullptr);
2948 if (V && !(C = dyn_cast<Constant>(V)))
2949 return Error(ID.Loc, "global values must be constants");
2953 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2955 return ParseType(Ty) ||
2956 ParseGlobalValue(Ty, V);
2959 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2962 LocTy KwLoc = Lex.getLoc();
2963 if (!EatIfPresent(lltok::kw_comdat))
2966 if (EatIfPresent(lltok::lparen)) {
2967 if (Lex.getKind() != lltok::ComdatVar)
2968 return TokError("expected comdat variable");
2969 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2971 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2974 if (GlobalName.empty())
2975 return TokError("comdat cannot be unnamed");
2976 C = getComdat(GlobalName, KwLoc);
2982 /// ParseGlobalValueVector
2984 /// ::= TypeAndValue (',' TypeAndValue)*
2985 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2987 if (Lex.getKind() == lltok::rbrace ||
2988 Lex.getKind() == lltok::rsquare ||
2989 Lex.getKind() == lltok::greater ||
2990 Lex.getKind() == lltok::rparen)
2994 if (ParseGlobalTypeAndValue(C)) return true;
2997 while (EatIfPresent(lltok::comma)) {
2998 if (ParseGlobalTypeAndValue(C)) return true;
3005 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3006 SmallVector<Metadata *, 16> Elts;
3007 if (ParseMDNodeVector(Elts))
3010 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3017 /// ::= !DILocation(...)
3018 bool LLParser::ParseMDNode(MDNode *&N) {
3019 if (Lex.getKind() == lltok::MetadataVar)
3020 return ParseSpecializedMDNode(N);
3022 return ParseToken(lltok::exclaim, "expected '!' here") ||
3026 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3028 if (Lex.getKind() == lltok::lbrace)
3029 return ParseMDTuple(N);
3032 return ParseMDNodeID(N);
3037 /// Structure to represent an optional metadata field.
3038 template <class FieldTy> struct MDFieldImpl {
3039 typedef MDFieldImpl ImplTy;
3043 void assign(FieldTy Val) {
3045 this->Val = std::move(Val);
3048 explicit MDFieldImpl(FieldTy Default)
3049 : Val(std::move(Default)), Seen(false) {}
3052 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3055 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3056 : ImplTy(Default), Max(Max) {}
3058 struct LineField : public MDUnsignedField {
3059 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3061 struct ColumnField : public MDUnsignedField {
3062 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3064 struct DwarfTagField : public MDUnsignedField {
3065 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3066 DwarfTagField(dwarf::Tag DefaultTag)
3067 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3069 struct DwarfAttEncodingField : public MDUnsignedField {
3070 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3072 struct DwarfVirtualityField : public MDUnsignedField {
3073 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3075 struct DwarfLangField : public MDUnsignedField {
3076 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3079 struct DIFlagField : public MDUnsignedField {
3080 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3083 struct MDSignedField : public MDFieldImpl<int64_t> {
3087 MDSignedField(int64_t Default = 0)
3088 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3089 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3090 : ImplTy(Default), Min(Min), Max(Max) {}
3093 struct MDBoolField : public MDFieldImpl<bool> {
3094 MDBoolField(bool Default = false) : ImplTy(Default) {}
3096 struct MDField : public MDFieldImpl<Metadata *> {
3099 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3101 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3102 MDConstant() : ImplTy(nullptr) {}
3104 struct MDStringField : public MDFieldImpl<MDString *> {
3106 MDStringField(bool AllowEmpty = true)
3107 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3109 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3110 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3118 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3119 MDUnsignedField &Result) {
3120 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3121 return TokError("expected unsigned integer");
3123 auto &U = Lex.getAPSIntVal();
3124 if (U.ugt(Result.Max))
3125 return TokError("value for '" + Name + "' too large, limit is " +
3127 Result.assign(U.getZExtValue());
3128 assert(Result.Val <= Result.Max && "Expected value in range");
3134 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3135 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3138 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3139 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3143 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3144 if (Lex.getKind() == lltok::APSInt)
3145 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3147 if (Lex.getKind() != lltok::DwarfTag)
3148 return TokError("expected DWARF tag");
3150 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3151 if (Tag == dwarf::DW_TAG_invalid)
3152 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3153 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3161 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3162 DwarfVirtualityField &Result) {
3163 if (Lex.getKind() == lltok::APSInt)
3164 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3166 if (Lex.getKind() != lltok::DwarfVirtuality)
3167 return TokError("expected DWARF virtuality code");
3169 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3171 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3172 Lex.getStrVal() + "'");
3173 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3174 Result.assign(Virtuality);
3180 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3181 if (Lex.getKind() == lltok::APSInt)
3182 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3184 if (Lex.getKind() != lltok::DwarfLang)
3185 return TokError("expected DWARF language");
3187 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3189 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3191 assert(Lang <= Result.Max && "Expected valid DWARF language");
3192 Result.assign(Lang);
3198 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3199 DwarfAttEncodingField &Result) {
3200 if (Lex.getKind() == lltok::APSInt)
3201 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3203 if (Lex.getKind() != lltok::DwarfAttEncoding)
3204 return TokError("expected DWARF type attribute encoding");
3206 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3208 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3209 Lex.getStrVal() + "'");
3210 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3211 Result.assign(Encoding);
3218 /// ::= DIFlagVector
3219 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3221 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3222 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3224 // Parser for a single flag.
3225 auto parseFlag = [&](unsigned &Val) {
3226 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3227 return ParseUInt32(Val);
3229 if (Lex.getKind() != lltok::DIFlag)
3230 return TokError("expected debug info flag");
3232 Val = DINode::getFlag(Lex.getStrVal());
3234 return TokError(Twine("invalid debug info flag flag '") +
3235 Lex.getStrVal() + "'");
3240 // Parse the flags and combine them together.
3241 unsigned Combined = 0;
3247 } while (EatIfPresent(lltok::bar));
3249 Result.assign(Combined);
3254 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3255 MDSignedField &Result) {
3256 if (Lex.getKind() != lltok::APSInt)
3257 return TokError("expected signed integer");
3259 auto &S = Lex.getAPSIntVal();
3261 return TokError("value for '" + Name + "' too small, limit is " +
3264 return TokError("value for '" + Name + "' too large, limit is " +
3266 Result.assign(S.getExtValue());
3267 assert(Result.Val >= Result.Min && "Expected value in range");
3268 assert(Result.Val <= Result.Max && "Expected value in range");
3274 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3275 switch (Lex.getKind()) {
3277 return TokError("expected 'true' or 'false'");
3278 case lltok::kw_true:
3279 Result.assign(true);
3281 case lltok::kw_false:
3282 Result.assign(false);
3290 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3291 if (Lex.getKind() == lltok::kw_null) {
3292 if (!Result.AllowNull)
3293 return TokError("'" + Name + "' cannot be null");
3295 Result.assign(nullptr);
3300 if (ParseMetadata(MD, nullptr))
3308 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3310 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3313 Result.assign(cast<ConstantAsMetadata>(MD));
3318 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3319 LocTy ValueLoc = Lex.getLoc();
3321 if (ParseStringConstant(S))
3324 if (!Result.AllowEmpty && S.empty())
3325 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3327 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3332 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3333 SmallVector<Metadata *, 4> MDs;
3334 if (ParseMDNodeVector(MDs))
3337 Result.assign(std::move(MDs));
3341 } // end namespace llvm
3343 template <class ParserTy>
3344 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3346 if (Lex.getKind() != lltok::LabelStr)
3347 return TokError("expected field label here");
3351 } while (EatIfPresent(lltok::comma));
3356 template <class ParserTy>
3357 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3358 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3361 if (ParseToken(lltok::lparen, "expected '(' here"))
3363 if (Lex.getKind() != lltok::rparen)
3364 if (ParseMDFieldsImplBody(parseField))
3367 ClosingLoc = Lex.getLoc();
3368 return ParseToken(lltok::rparen, "expected ')' here");
3371 template <class FieldTy>
3372 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3374 return TokError("field '" + Name + "' cannot be specified more than once");
3376 LocTy Loc = Lex.getLoc();
3378 return ParseMDField(Loc, Name, Result);
3381 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3382 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3384 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3385 if (Lex.getStrVal() == #CLASS) \
3386 return Parse##CLASS(N, IsDistinct);
3387 #include "llvm/IR/Metadata.def"
3389 return TokError("expected metadata type");
3392 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3393 #define NOP_FIELD(NAME, TYPE, INIT)
3394 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3396 return Error(ClosingLoc, "missing required field '" #NAME "'");
3397 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3398 if (Lex.getStrVal() == #NAME) \
3399 return ParseMDField(#NAME, NAME);
3400 #define PARSE_MD_FIELDS() \
3401 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3404 if (ParseMDFieldsImpl([&]() -> bool { \
3405 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3406 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3409 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3411 #define GET_OR_DISTINCT(CLASS, ARGS) \
3412 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3414 /// ParseDILocationFields:
3415 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3416 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3417 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3418 OPTIONAL(line, LineField, ); \
3419 OPTIONAL(column, ColumnField, ); \
3420 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3421 OPTIONAL(inlinedAt, MDField, );
3423 #undef VISIT_MD_FIELDS
3425 Result = GET_OR_DISTINCT(
3426 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3430 /// ParseGenericDINode:
3431 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3432 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3433 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3434 REQUIRED(tag, DwarfTagField, ); \
3435 OPTIONAL(header, MDStringField, ); \
3436 OPTIONAL(operands, MDFieldList, );
3438 #undef VISIT_MD_FIELDS
3440 Result = GET_OR_DISTINCT(GenericDINode,
3441 (Context, tag.Val, header.Val, operands.Val));
3445 /// ParseDISubrange:
3446 /// ::= !DISubrange(count: 30, lowerBound: 2)
3447 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3448 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3449 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3450 OPTIONAL(lowerBound, MDSignedField, );
3452 #undef VISIT_MD_FIELDS
3454 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3458 /// ParseDIEnumerator:
3459 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3460 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3461 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3462 REQUIRED(name, MDStringField, ); \
3463 REQUIRED(value, MDSignedField, );
3465 #undef VISIT_MD_FIELDS
3467 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3471 /// ParseDIBasicType:
3472 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3473 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3474 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3475 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3476 OPTIONAL(name, MDStringField, ); \
3477 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3478 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3479 OPTIONAL(encoding, DwarfAttEncodingField, );
3481 #undef VISIT_MD_FIELDS
3483 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3484 align.Val, encoding.Val));
3488 /// ParseDIDerivedType:
3489 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3490 /// line: 7, scope: !1, baseType: !2, size: 32,
3491 /// align: 32, offset: 0, flags: 0, extraData: !3)
3492 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3493 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3494 REQUIRED(tag, DwarfTagField, ); \
3495 OPTIONAL(name, MDStringField, ); \
3496 OPTIONAL(file, MDField, ); \
3497 OPTIONAL(line, LineField, ); \
3498 OPTIONAL(scope, MDField, ); \
3499 REQUIRED(baseType, MDField, ); \
3500 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3501 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3502 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3503 OPTIONAL(flags, DIFlagField, ); \
3504 OPTIONAL(extraData, MDField, );
3506 #undef VISIT_MD_FIELDS
3508 Result = GET_OR_DISTINCT(DIDerivedType,
3509 (Context, tag.Val, name.Val, file.Val, line.Val,
3510 scope.Val, baseType.Val, size.Val, align.Val,
3511 offset.Val, flags.Val, extraData.Val));
3515 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3516 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3517 REQUIRED(tag, DwarfTagField, ); \
3518 OPTIONAL(name, MDStringField, ); \
3519 OPTIONAL(file, MDField, ); \
3520 OPTIONAL(line, LineField, ); \
3521 OPTIONAL(scope, MDField, ); \
3522 OPTIONAL(baseType, MDField, ); \
3523 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3524 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3525 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3526 OPTIONAL(flags, DIFlagField, ); \
3527 OPTIONAL(elements, MDField, ); \
3528 OPTIONAL(runtimeLang, DwarfLangField, ); \
3529 OPTIONAL(vtableHolder, MDField, ); \
3530 OPTIONAL(templateParams, MDField, ); \
3531 OPTIONAL(identifier, MDStringField, );
3533 #undef VISIT_MD_FIELDS
3535 Result = GET_OR_DISTINCT(
3537 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3538 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3539 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3543 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3544 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3545 OPTIONAL(flags, DIFlagField, ); \
3546 REQUIRED(types, MDField, );
3548 #undef VISIT_MD_FIELDS
3550 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3554 /// ParseDIFileType:
3555 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3556 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3557 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3558 REQUIRED(filename, MDStringField, ); \
3559 REQUIRED(directory, MDStringField, );
3561 #undef VISIT_MD_FIELDS
3563 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3567 /// ParseDICompileUnit:
3568 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3569 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3570 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3571 /// enums: !1, retainedTypes: !2, subprograms: !3,
3572 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3573 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3574 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3575 REQUIRED(language, DwarfLangField, ); \
3576 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3577 OPTIONAL(producer, MDStringField, ); \
3578 OPTIONAL(isOptimized, MDBoolField, ); \
3579 OPTIONAL(flags, MDStringField, ); \
3580 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3581 OPTIONAL(splitDebugFilename, MDStringField, ); \
3582 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3583 OPTIONAL(enums, MDField, ); \
3584 OPTIONAL(retainedTypes, MDField, ); \
3585 OPTIONAL(subprograms, MDField, ); \
3586 OPTIONAL(globals, MDField, ); \
3587 OPTIONAL(imports, MDField, ); \
3588 OPTIONAL(dwoId, MDUnsignedField, );
3590 #undef VISIT_MD_FIELDS
3592 Result = GET_OR_DISTINCT(DICompileUnit,
3593 (Context, language.Val, file.Val, producer.Val,
3594 isOptimized.Val, flags.Val, runtimeVersion.Val,
3595 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3596 retainedTypes.Val, subprograms.Val, globals.Val,
3597 imports.Val, dwoId.Val));
3601 /// ParseDISubprogram:
3602 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3603 /// file: !1, line: 7, type: !2, isLocal: false,
3604 /// isDefinition: true, scopeLine: 8, containingType: !3,
3605 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3606 /// virtualIndex: 10, flags: 11,
3607 /// isOptimized: false, function: void ()* @_Z3foov,
3608 /// templateParams: !4, declaration: !5, variables: !6)
3609 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3610 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3611 OPTIONAL(scope, MDField, ); \
3612 OPTIONAL(name, MDStringField, ); \
3613 OPTIONAL(linkageName, MDStringField, ); \
3614 OPTIONAL(file, MDField, ); \
3615 OPTIONAL(line, LineField, ); \
3616 OPTIONAL(type, MDField, ); \
3617 OPTIONAL(isLocal, MDBoolField, ); \
3618 OPTIONAL(isDefinition, MDBoolField, (true)); \
3619 OPTIONAL(scopeLine, LineField, ); \
3620 OPTIONAL(containingType, MDField, ); \
3621 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3622 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3623 OPTIONAL(flags, DIFlagField, ); \
3624 OPTIONAL(isOptimized, MDBoolField, ); \
3625 OPTIONAL(function, MDConstant, ); \
3626 OPTIONAL(templateParams, MDField, ); \
3627 OPTIONAL(declaration, MDField, ); \
3628 OPTIONAL(variables, MDField, );
3630 #undef VISIT_MD_FIELDS
3632 Result = GET_OR_DISTINCT(
3633 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3634 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3635 scopeLine.Val, containingType.Val, virtuality.Val,
3636 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3637 templateParams.Val, declaration.Val, variables.Val));
3641 /// ParseDILexicalBlock:
3642 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3643 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3644 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3645 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3646 OPTIONAL(file, MDField, ); \
3647 OPTIONAL(line, LineField, ); \
3648 OPTIONAL(column, ColumnField, );
3650 #undef VISIT_MD_FIELDS
3652 Result = GET_OR_DISTINCT(
3653 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3657 /// ParseDILexicalBlockFile:
3658 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3659 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3660 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3661 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3662 OPTIONAL(file, MDField, ); \
3663 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3665 #undef VISIT_MD_FIELDS
3667 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3668 (Context, scope.Val, file.Val, discriminator.Val));
3672 /// ParseDINamespace:
3673 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3674 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3675 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3676 REQUIRED(scope, MDField, ); \
3677 OPTIONAL(file, MDField, ); \
3678 OPTIONAL(name, MDStringField, ); \
3679 OPTIONAL(line, LineField, );
3681 #undef VISIT_MD_FIELDS
3683 Result = GET_OR_DISTINCT(DINamespace,
3684 (Context, scope.Val, file.Val, name.Val, line.Val));
3689 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3690 /// includePath: "/usr/include", isysroot: "/")
3691 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3692 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3693 REQUIRED(scope, MDField, ); \
3694 REQUIRED(name, MDStringField, ); \
3695 OPTIONAL(configMacros, MDStringField, ); \
3696 OPTIONAL(includePath, MDStringField, ); \
3697 OPTIONAL(isysroot, MDStringField, );
3699 #undef VISIT_MD_FIELDS
3701 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3702 configMacros.Val, includePath.Val, isysroot.Val));
3706 /// ParseDITemplateTypeParameter:
3707 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3708 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3709 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3710 OPTIONAL(name, MDStringField, ); \
3711 REQUIRED(type, MDField, );
3713 #undef VISIT_MD_FIELDS
3716 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3720 /// ParseDITemplateValueParameter:
3721 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3722 /// name: "V", type: !1, value: i32 7)
3723 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3724 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3725 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3726 OPTIONAL(name, MDStringField, ); \
3727 OPTIONAL(type, MDField, ); \
3728 REQUIRED(value, MDField, );
3730 #undef VISIT_MD_FIELDS
3732 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3733 (Context, tag.Val, name.Val, type.Val, value.Val));
3737 /// ParseDIGlobalVariable:
3738 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3739 /// file: !1, line: 7, type: !2, isLocal: false,
3740 /// isDefinition: true, variable: i32* @foo,
3741 /// declaration: !3)
3742 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3743 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3744 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3745 OPTIONAL(scope, MDField, ); \
3746 OPTIONAL(linkageName, MDStringField, ); \
3747 OPTIONAL(file, MDField, ); \
3748 OPTIONAL(line, LineField, ); \
3749 OPTIONAL(type, MDField, ); \
3750 OPTIONAL(isLocal, MDBoolField, ); \
3751 OPTIONAL(isDefinition, MDBoolField, (true)); \
3752 OPTIONAL(variable, MDConstant, ); \
3753 OPTIONAL(declaration, MDField, );
3755 #undef VISIT_MD_FIELDS
3757 Result = GET_OR_DISTINCT(DIGlobalVariable,
3758 (Context, scope.Val, name.Val, linkageName.Val,
3759 file.Val, line.Val, type.Val, isLocal.Val,
3760 isDefinition.Val, variable.Val, declaration.Val));
3764 /// ParseDILocalVariable:
3765 /// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3766 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3767 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3768 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3769 REQUIRED(tag, DwarfTagField, ); \
3770 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3771 OPTIONAL(name, MDStringField, ); \
3772 OPTIONAL(file, MDField, ); \
3773 OPTIONAL(line, LineField, ); \
3774 OPTIONAL(type, MDField, ); \
3775 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3776 OPTIONAL(flags, DIFlagField, );
3778 #undef VISIT_MD_FIELDS
3780 Result = GET_OR_DISTINCT(DILocalVariable,
3781 (Context, tag.Val, scope.Val, name.Val, file.Val,
3782 line.Val, type.Val, arg.Val, flags.Val));
3786 /// ParseDIExpression:
3787 /// ::= !DIExpression(0, 7, -1)
3788 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3789 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3792 if (ParseToken(lltok::lparen, "expected '(' here"))
3795 SmallVector<uint64_t, 8> Elements;
3796 if (Lex.getKind() != lltok::rparen)
3798 if (Lex.getKind() == lltok::DwarfOp) {
3799 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3801 Elements.push_back(Op);
3804 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3807 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3808 return TokError("expected unsigned integer");
3810 auto &U = Lex.getAPSIntVal();
3811 if (U.ugt(UINT64_MAX))
3812 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3813 Elements.push_back(U.getZExtValue());
3815 } while (EatIfPresent(lltok::comma));
3817 if (ParseToken(lltok::rparen, "expected ')' here"))
3820 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3824 /// ParseDIObjCProperty:
3825 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3826 /// getter: "getFoo", attributes: 7, type: !2)
3827 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3828 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3829 OPTIONAL(name, MDStringField, ); \
3830 OPTIONAL(file, MDField, ); \
3831 OPTIONAL(line, LineField, ); \
3832 OPTIONAL(setter, MDStringField, ); \
3833 OPTIONAL(getter, MDStringField, ); \
3834 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3835 OPTIONAL(type, MDField, );
3837 #undef VISIT_MD_FIELDS
3839 Result = GET_OR_DISTINCT(DIObjCProperty,
3840 (Context, name.Val, file.Val, line.Val, setter.Val,
3841 getter.Val, attributes.Val, type.Val));
3845 /// ParseDIImportedEntity:
3846 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3847 /// line: 7, name: "foo")
3848 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3849 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3850 REQUIRED(tag, DwarfTagField, ); \
3851 REQUIRED(scope, MDField, ); \
3852 OPTIONAL(entity, MDField, ); \
3853 OPTIONAL(line, LineField, ); \
3854 OPTIONAL(name, MDStringField, );
3856 #undef VISIT_MD_FIELDS
3858 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3859 entity.Val, line.Val, name.Val));
3863 #undef PARSE_MD_FIELD
3865 #undef REQUIRE_FIELD
3866 #undef DECLARE_FIELD
3868 /// ParseMetadataAsValue
3869 /// ::= metadata i32 %local
3870 /// ::= metadata i32 @global
3871 /// ::= metadata i32 7
3873 /// ::= metadata !{...}
3874 /// ::= metadata !"string"
3875 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3876 // Note: the type 'metadata' has already been parsed.
3878 if (ParseMetadata(MD, &PFS))
3881 V = MetadataAsValue::get(Context, MD);
3885 /// ParseValueAsMetadata
3889 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3890 PerFunctionState *PFS) {
3893 if (ParseType(Ty, TypeMsg, Loc))
3895 if (Ty->isMetadataTy())
3896 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3899 if (ParseValue(Ty, V, PFS))
3902 MD = ValueAsMetadata::get(V);
3913 /// ::= !DILocation(...)
3914 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3915 if (Lex.getKind() == lltok::MetadataVar) {
3917 if (ParseSpecializedMDNode(N))
3925 if (Lex.getKind() != lltok::exclaim)
3926 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3929 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3933 // ::= '!' STRINGCONSTANT
3934 if (Lex.getKind() == lltok::StringConstant) {
3936 if (ParseMDString(S))
3946 if (ParseMDNodeTail(N))
3953 //===----------------------------------------------------------------------===//
3954 // Function Parsing.
3955 //===----------------------------------------------------------------------===//
3957 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3958 PerFunctionState *PFS) {
3959 if (Ty->isFunctionTy())
3960 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3963 case ValID::t_LocalID:
3964 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3965 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3966 return V == nullptr;
3967 case ValID::t_LocalName:
3968 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3969 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3970 return V == nullptr;
3971 case ValID::t_InlineAsm: {
3972 PointerType *PTy = dyn_cast<PointerType>(Ty);
3974 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3975 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3976 return Error(ID.Loc, "invalid type for inline asm constraint string");
3977 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3978 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3981 case ValID::t_GlobalName:
3982 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3983 return V == nullptr;
3984 case ValID::t_GlobalID:
3985 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3986 return V == nullptr;
3987 case ValID::t_APSInt:
3988 if (!Ty->isIntegerTy())
3989 return Error(ID.Loc, "integer constant must have integer type");
3990 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3991 V = ConstantInt::get(Context, ID.APSIntVal);
3993 case ValID::t_APFloat:
3994 if (!Ty->isFloatingPointTy() ||
3995 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3996 return Error(ID.Loc, "floating point constant invalid for type");
3998 // The lexer has no type info, so builds all half, float, and double FP
3999 // constants as double. Fix this here. Long double does not need this.
4000 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4003 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4005 else if (Ty->isFloatTy())
4006 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4009 V = ConstantFP::get(Context, ID.APFloatVal);
4011 if (V->getType() != Ty)
4012 return Error(ID.Loc, "floating point constant does not have type '" +
4013 getTypeString(Ty) + "'");
4017 if (!Ty->isPointerTy())
4018 return Error(ID.Loc, "null must be a pointer type");
4019 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4021 case ValID::t_Undef:
4022 // FIXME: LabelTy should not be a first-class type.
4023 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4024 return Error(ID.Loc, "invalid type for undef constant");
4025 V = UndefValue::get(Ty);
4027 case ValID::t_EmptyArray:
4028 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4029 return Error(ID.Loc, "invalid empty array initializer");
4030 V = UndefValue::get(Ty);
4033 // FIXME: LabelTy should not be a first-class type.
4034 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4035 return Error(ID.Loc, "invalid type for null constant");
4036 V = Constant::getNullValue(Ty);
4038 case ValID::t_Constant:
4039 if (ID.ConstantVal->getType() != Ty)
4040 return Error(ID.Loc, "constant expression type mismatch");
4044 case ValID::t_ConstantStruct:
4045 case ValID::t_PackedConstantStruct:
4046 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4047 if (ST->getNumElements() != ID.UIntVal)
4048 return Error(ID.Loc,
4049 "initializer with struct type has wrong # elements");
4050 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4051 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4053 // Verify that the elements are compatible with the structtype.
4054 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4055 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4056 return Error(ID.Loc, "element " + Twine(i) +
4057 " of struct initializer doesn't match struct element type");
4059 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4062 return Error(ID.Loc, "constant expression type mismatch");
4065 llvm_unreachable("Invalid ValID");
4068 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4071 return ParseValID(ID, PFS) ||
4072 ConvertValIDToValue(Ty, ID, V, PFS);
4075 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4077 return ParseType(Ty) ||
4078 ParseValue(Ty, V, PFS);
4081 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4082 PerFunctionState &PFS) {
4085 if (ParseTypeAndValue(V, PFS)) return true;
4086 if (!isa<BasicBlock>(V))
4087 return Error(Loc, "expected a basic block");
4088 BB = cast<BasicBlock>(V);
4094 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4095 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4096 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4097 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4098 // Parse the linkage.
4099 LocTy LinkageLoc = Lex.getLoc();
4102 unsigned Visibility;
4103 unsigned DLLStorageClass;
4104 AttrBuilder RetAttrs;
4106 Type *RetType = nullptr;
4107 LocTy RetTypeLoc = Lex.getLoc();
4108 if (ParseOptionalLinkage(Linkage) ||
4109 ParseOptionalVisibility(Visibility) ||
4110 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4111 ParseOptionalCallingConv(CC) ||
4112 ParseOptionalReturnAttrs(RetAttrs) ||
4113 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4116 // Verify that the linkage is ok.
4117 switch ((GlobalValue::LinkageTypes)Linkage) {
4118 case GlobalValue::ExternalLinkage:
4119 break; // always ok.
4120 case GlobalValue::ExternalWeakLinkage:
4122 return Error(LinkageLoc, "invalid linkage for function definition");
4124 case GlobalValue::PrivateLinkage:
4125 case GlobalValue::InternalLinkage:
4126 case GlobalValue::AvailableExternallyLinkage:
4127 case GlobalValue::LinkOnceAnyLinkage:
4128 case GlobalValue::LinkOnceODRLinkage:
4129 case GlobalValue::WeakAnyLinkage:
4130 case GlobalValue::WeakODRLinkage:
4132 return Error(LinkageLoc, "invalid linkage for function declaration");
4134 case GlobalValue::AppendingLinkage:
4135 case GlobalValue::CommonLinkage:
4136 return Error(LinkageLoc, "invalid function linkage type");
4139 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4140 return Error(LinkageLoc,
4141 "symbol with local linkage must have default visibility");
4143 if (!FunctionType::isValidReturnType(RetType))
4144 return Error(RetTypeLoc, "invalid function return type");
4146 LocTy NameLoc = Lex.getLoc();
4148 std::string FunctionName;
4149 if (Lex.getKind() == lltok::GlobalVar) {
4150 FunctionName = Lex.getStrVal();
4151 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4152 unsigned NameID = Lex.getUIntVal();
4154 if (NameID != NumberedVals.size())
4155 return TokError("function expected to be numbered '%" +
4156 Twine(NumberedVals.size()) + "'");
4158 return TokError("expected function name");
4163 if (Lex.getKind() != lltok::lparen)
4164 return TokError("expected '(' in function argument list");
4166 SmallVector<ArgInfo, 8> ArgList;
4168 AttrBuilder FuncAttrs;
4169 std::vector<unsigned> FwdRefAttrGrps;
4171 std::string Section;
4175 LocTy UnnamedAddrLoc;
4176 Constant *Prefix = nullptr;
4177 Constant *Prologue = nullptr;
4178 Constant *PersonalityFn = nullptr;
4181 if (ParseArgumentList(ArgList, isVarArg) ||
4182 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4184 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4186 (EatIfPresent(lltok::kw_section) &&
4187 ParseStringConstant(Section)) ||
4188 parseOptionalComdat(FunctionName, C) ||
4189 ParseOptionalAlignment(Alignment) ||
4190 (EatIfPresent(lltok::kw_gc) &&
4191 ParseStringConstant(GC)) ||
4192 (EatIfPresent(lltok::kw_prefix) &&
4193 ParseGlobalTypeAndValue(Prefix)) ||
4194 (EatIfPresent(lltok::kw_prologue) &&
4195 ParseGlobalTypeAndValue(Prologue)) ||
4196 (EatIfPresent(lltok::kw_personality) &&
4197 ParseGlobalTypeAndValue(PersonalityFn)))
4200 if (FuncAttrs.contains(Attribute::Builtin))
4201 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4203 // If the alignment was parsed as an attribute, move to the alignment field.
4204 if (FuncAttrs.hasAlignmentAttr()) {
4205 Alignment = FuncAttrs.getAlignment();
4206 FuncAttrs.removeAttribute(Attribute::Alignment);
4209 // Okay, if we got here, the function is syntactically valid. Convert types
4210 // and do semantic checks.
4211 std::vector<Type*> ParamTypeList;
4212 SmallVector<AttributeSet, 8> Attrs;
4214 if (RetAttrs.hasAttributes())
4215 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4216 AttributeSet::ReturnIndex,
4219 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4220 ParamTypeList.push_back(ArgList[i].Ty);
4221 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4222 AttrBuilder B(ArgList[i].Attrs, i + 1);
4223 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4227 if (FuncAttrs.hasAttributes())
4228 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4229 AttributeSet::FunctionIndex,
4232 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4234 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4235 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4238 FunctionType::get(RetType, ParamTypeList, isVarArg);
4239 PointerType *PFT = PointerType::getUnqual(FT);
4242 if (!FunctionName.empty()) {
4243 // If this was a definition of a forward reference, remove the definition
4244 // from the forward reference table and fill in the forward ref.
4245 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4246 ForwardRefVals.find(FunctionName);
4247 if (FRVI != ForwardRefVals.end()) {
4248 Fn = M->getFunction(FunctionName);
4250 return Error(FRVI->second.second, "invalid forward reference to "
4251 "function as global value!");
4252 if (Fn->getType() != PFT)
4253 return Error(FRVI->second.second, "invalid forward reference to "
4254 "function '" + FunctionName + "' with wrong type!");
4256 ForwardRefVals.erase(FRVI);
4257 } else if ((Fn = M->getFunction(FunctionName))) {
4258 // Reject redefinitions.
4259 return Error(NameLoc, "invalid redefinition of function '" +
4260 FunctionName + "'");
4261 } else if (M->getNamedValue(FunctionName)) {
4262 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4266 // If this is a definition of a forward referenced function, make sure the
4268 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4269 = ForwardRefValIDs.find(NumberedVals.size());
4270 if (I != ForwardRefValIDs.end()) {
4271 Fn = cast<Function>(I->second.first);
4272 if (Fn->getType() != PFT)
4273 return Error(NameLoc, "type of definition and forward reference of '@" +
4274 Twine(NumberedVals.size()) + "' disagree");
4275 ForwardRefValIDs.erase(I);
4280 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4281 else // Move the forward-reference to the correct spot in the module.
4282 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4284 if (FunctionName.empty())
4285 NumberedVals.push_back(Fn);
4287 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4288 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4289 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4290 Fn->setCallingConv(CC);
4291 Fn->setAttributes(PAL);
4292 Fn->setUnnamedAddr(UnnamedAddr);
4293 Fn->setAlignment(Alignment);
4294 Fn->setSection(Section);
4296 Fn->setPersonalityFn(PersonalityFn);
4297 if (!GC.empty()) Fn->setGC(GC.c_str());
4298 Fn->setPrefixData(Prefix);
4299 Fn->setPrologueData(Prologue);
4300 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4302 // Add all of the arguments we parsed to the function.
4303 Function::arg_iterator ArgIt = Fn->arg_begin();
4304 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4305 // If the argument has a name, insert it into the argument symbol table.
4306 if (ArgList[i].Name.empty()) continue;
4308 // Set the name, if it conflicted, it will be auto-renamed.
4309 ArgIt->setName(ArgList[i].Name);
4311 if (ArgIt->getName() != ArgList[i].Name)
4312 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4313 ArgList[i].Name + "'");
4319 // Check the declaration has no block address forward references.
4321 if (FunctionName.empty()) {
4322 ID.Kind = ValID::t_GlobalID;
4323 ID.UIntVal = NumberedVals.size() - 1;
4325 ID.Kind = ValID::t_GlobalName;
4326 ID.StrVal = FunctionName;
4328 auto Blocks = ForwardRefBlockAddresses.find(ID);
4329 if (Blocks != ForwardRefBlockAddresses.end())
4330 return Error(Blocks->first.Loc,
4331 "cannot take blockaddress inside a declaration");
4335 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4337 if (FunctionNumber == -1) {
4338 ID.Kind = ValID::t_GlobalName;
4339 ID.StrVal = F.getName();
4341 ID.Kind = ValID::t_GlobalID;
4342 ID.UIntVal = FunctionNumber;
4345 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4346 if (Blocks == P.ForwardRefBlockAddresses.end())
4349 for (const auto &I : Blocks->second) {
4350 const ValID &BBID = I.first;
4351 GlobalValue *GV = I.second;
4353 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4354 "Expected local id or name");
4356 if (BBID.Kind == ValID::t_LocalName)
4357 BB = GetBB(BBID.StrVal, BBID.Loc);
4359 BB = GetBB(BBID.UIntVal, BBID.Loc);
4361 return P.Error(BBID.Loc, "referenced value is not a basic block");
4363 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4364 GV->eraseFromParent();
4367 P.ForwardRefBlockAddresses.erase(Blocks);
4371 /// ParseFunctionBody
4372 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4373 bool LLParser::ParseFunctionBody(Function &Fn) {
4374 if (Lex.getKind() != lltok::lbrace)
4375 return TokError("expected '{' in function body");
4376 Lex.Lex(); // eat the {.
4378 int FunctionNumber = -1;
4379 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4381 PerFunctionState PFS(*this, Fn, FunctionNumber);
4383 // Resolve block addresses and allow basic blocks to be forward-declared
4384 // within this function.
4385 if (PFS.resolveForwardRefBlockAddresses())
4387 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4389 // We need at least one basic block.
4390 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4391 return TokError("function body requires at least one basic block");
4393 while (Lex.getKind() != lltok::rbrace &&
4394 Lex.getKind() != lltok::kw_uselistorder)
4395 if (ParseBasicBlock(PFS)) return true;
4397 while (Lex.getKind() != lltok::rbrace)
4398 if (ParseUseListOrder(&PFS))
4404 // Verify function is ok.
4405 return PFS.FinishFunction();
4409 /// ::= LabelStr? Instruction*
4410 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4411 // If this basic block starts out with a name, remember it.
4413 LocTy NameLoc = Lex.getLoc();
4414 if (Lex.getKind() == lltok::LabelStr) {
4415 Name = Lex.getStrVal();
4419 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4421 return Error(NameLoc,
4422 "unable to create block named '" + Name + "'");
4424 std::string NameStr;
4426 // Parse the instructions in this block until we get a terminator.
4429 // This instruction may have three possibilities for a name: a) none
4430 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4431 LocTy NameLoc = Lex.getLoc();
4435 if (Lex.getKind() == lltok::LocalVarID) {
4436 NameID = Lex.getUIntVal();
4438 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4440 } else if (Lex.getKind() == lltok::LocalVar) {
4441 NameStr = Lex.getStrVal();
4443 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4447 switch (ParseInstruction(Inst, BB, PFS)) {
4448 default: llvm_unreachable("Unknown ParseInstruction result!");
4449 case InstError: return true;
4451 BB->getInstList().push_back(Inst);
4453 // With a normal result, we check to see if the instruction is followed by
4454 // a comma and metadata.
4455 if (EatIfPresent(lltok::comma))
4456 if (ParseInstructionMetadata(*Inst))
4459 case InstExtraComma:
4460 BB->getInstList().push_back(Inst);
4462 // If the instruction parser ate an extra comma at the end of it, it
4463 // *must* be followed by metadata.
4464 if (ParseInstructionMetadata(*Inst))
4469 // Set the name on the instruction.
4470 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4471 } while (!isa<TerminatorInst>(Inst));
4476 //===----------------------------------------------------------------------===//
4477 // Instruction Parsing.
4478 //===----------------------------------------------------------------------===//
4480 /// ParseInstruction - Parse one of the many different instructions.
4482 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4483 PerFunctionState &PFS) {
4484 lltok::Kind Token = Lex.getKind();
4485 if (Token == lltok::Eof)
4486 return TokError("found end of file when expecting more instructions");
4487 LocTy Loc = Lex.getLoc();
4488 unsigned KeywordVal = Lex.getUIntVal();
4489 Lex.Lex(); // Eat the keyword.
4492 default: return Error(Loc, "expected instruction opcode");
4493 // Terminator Instructions.
4494 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4495 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4496 case lltok::kw_br: return ParseBr(Inst, PFS);
4497 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4498 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4499 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4500 case lltok::kw_resume: return ParseResume(Inst, PFS);
4501 // Binary Operators.
4505 case lltok::kw_shl: {
4506 bool NUW = EatIfPresent(lltok::kw_nuw);
4507 bool NSW = EatIfPresent(lltok::kw_nsw);
4508 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4510 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4512 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4513 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4516 case lltok::kw_fadd:
4517 case lltok::kw_fsub:
4518 case lltok::kw_fmul:
4519 case lltok::kw_fdiv:
4520 case lltok::kw_frem: {
4521 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4522 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4526 Inst->setFastMathFlags(FMF);
4530 case lltok::kw_sdiv:
4531 case lltok::kw_udiv:
4532 case lltok::kw_lshr:
4533 case lltok::kw_ashr: {
4534 bool Exact = EatIfPresent(lltok::kw_exact);
4536 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4537 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4541 case lltok::kw_urem:
4542 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4545 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4546 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4547 case lltok::kw_fcmp: {
4548 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4549 int Res = ParseCompare(Inst, PFS, KeywordVal);
4553 Inst->setFastMathFlags(FMF);
4558 case lltok::kw_trunc:
4559 case lltok::kw_zext:
4560 case lltok::kw_sext:
4561 case lltok::kw_fptrunc:
4562 case lltok::kw_fpext:
4563 case lltok::kw_bitcast:
4564 case lltok::kw_addrspacecast:
4565 case lltok::kw_uitofp:
4566 case lltok::kw_sitofp:
4567 case lltok::kw_fptoui:
4568 case lltok::kw_fptosi:
4569 case lltok::kw_inttoptr:
4570 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4572 case lltok::kw_select: return ParseSelect(Inst, PFS);
4573 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4574 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4575 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4576 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4577 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4578 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4580 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4581 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4582 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4584 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4585 case lltok::kw_load: return ParseLoad(Inst, PFS);
4586 case lltok::kw_store: return ParseStore(Inst, PFS);
4587 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4588 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4589 case lltok::kw_fence: return ParseFence(Inst, PFS);
4590 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4591 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4592 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4596 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4597 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4598 if (Opc == Instruction::FCmp) {
4599 switch (Lex.getKind()) {
4600 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4601 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4602 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4603 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4604 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4605 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4606 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4607 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4608 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4609 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4610 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4611 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4612 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4613 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4614 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4615 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4616 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4619 switch (Lex.getKind()) {
4620 default: return TokError("expected icmp predicate (e.g. 'eq')");
4621 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4622 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4623 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4624 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4625 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4626 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4627 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4628 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4629 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4630 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4637 //===----------------------------------------------------------------------===//
4638 // Terminator Instructions.
4639 //===----------------------------------------------------------------------===//
4641 /// ParseRet - Parse a return instruction.
4642 /// ::= 'ret' void (',' !dbg, !1)*
4643 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4644 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4645 PerFunctionState &PFS) {
4646 SMLoc TypeLoc = Lex.getLoc();
4648 if (ParseType(Ty, true /*void allowed*/)) return true;
4650 Type *ResType = PFS.getFunction().getReturnType();
4652 if (Ty->isVoidTy()) {
4653 if (!ResType->isVoidTy())
4654 return Error(TypeLoc, "value doesn't match function result type '" +
4655 getTypeString(ResType) + "'");
4657 Inst = ReturnInst::Create(Context);
4662 if (ParseValue(Ty, RV, PFS)) return true;
4664 if (ResType != RV->getType())
4665 return Error(TypeLoc, "value doesn't match function result type '" +
4666 getTypeString(ResType) + "'");
4668 Inst = ReturnInst::Create(Context, RV);
4674 /// ::= 'br' TypeAndValue
4675 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4676 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4679 BasicBlock *Op1, *Op2;
4680 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4682 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4683 Inst = BranchInst::Create(BB);
4687 if (Op0->getType() != Type::getInt1Ty(Context))
4688 return Error(Loc, "branch condition must have 'i1' type");
4690 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4691 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4692 ParseToken(lltok::comma, "expected ',' after true destination") ||
4693 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4696 Inst = BranchInst::Create(Op1, Op2, Op0);
4702 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4704 /// ::= (TypeAndValue ',' TypeAndValue)*
4705 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4706 LocTy CondLoc, BBLoc;
4708 BasicBlock *DefaultBB;
4709 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4710 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4711 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4712 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4715 if (!Cond->getType()->isIntegerTy())
4716 return Error(CondLoc, "switch condition must have integer type");
4718 // Parse the jump table pairs.
4719 SmallPtrSet<Value*, 32> SeenCases;
4720 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4721 while (Lex.getKind() != lltok::rsquare) {
4725 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4726 ParseToken(lltok::comma, "expected ',' after case value") ||
4727 ParseTypeAndBasicBlock(DestBB, PFS))
4730 if (!SeenCases.insert(Constant).second)
4731 return Error(CondLoc, "duplicate case value in switch");
4732 if (!isa<ConstantInt>(Constant))
4733 return Error(CondLoc, "case value is not a constant integer");
4735 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4738 Lex.Lex(); // Eat the ']'.
4740 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4741 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4742 SI->addCase(Table[i].first, Table[i].second);
4749 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4750 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4753 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4754 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4755 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4758 if (!Address->getType()->isPointerTy())
4759 return Error(AddrLoc, "indirectbr address must have pointer type");
4761 // Parse the destination list.
4762 SmallVector<BasicBlock*, 16> DestList;
4764 if (Lex.getKind() != lltok::rsquare) {
4766 if (ParseTypeAndBasicBlock(DestBB, PFS))
4768 DestList.push_back(DestBB);
4770 while (EatIfPresent(lltok::comma)) {
4771 if (ParseTypeAndBasicBlock(DestBB, PFS))
4773 DestList.push_back(DestBB);
4777 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4780 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4781 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4782 IBI->addDestination(DestList[i]);
4789 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4790 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4791 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4792 LocTy CallLoc = Lex.getLoc();
4793 AttrBuilder RetAttrs, FnAttrs;
4794 std::vector<unsigned> FwdRefAttrGrps;
4797 Type *RetType = nullptr;
4800 SmallVector<ParamInfo, 16> ArgList;
4802 BasicBlock *NormalBB, *UnwindBB;
4803 if (ParseOptionalCallingConv(CC) ||
4804 ParseOptionalReturnAttrs(RetAttrs) ||
4805 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4806 ParseValID(CalleeID) ||
4807 ParseParameterList(ArgList, PFS) ||
4808 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4810 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4811 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4812 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4813 ParseTypeAndBasicBlock(UnwindBB, PFS))
4816 // If RetType is a non-function pointer type, then this is the short syntax
4817 // for the call, which means that RetType is just the return type. Infer the
4818 // rest of the function argument types from the arguments that are present.
4819 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4821 // Pull out the types of all of the arguments...
4822 std::vector<Type*> ParamTypes;
4823 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4824 ParamTypes.push_back(ArgList[i].V->getType());
4826 if (!FunctionType::isValidReturnType(RetType))
4827 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4829 Ty = FunctionType::get(RetType, ParamTypes, false);
4832 // Look up the callee.
4834 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4837 // Set up the Attribute for the function.
4838 SmallVector<AttributeSet, 8> Attrs;
4839 if (RetAttrs.hasAttributes())
4840 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4841 AttributeSet::ReturnIndex,
4844 SmallVector<Value*, 8> Args;
4846 // Loop through FunctionType's arguments and ensure they are specified
4847 // correctly. Also, gather any parameter attributes.
4848 FunctionType::param_iterator I = Ty->param_begin();
4849 FunctionType::param_iterator E = Ty->param_end();
4850 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4851 Type *ExpectedTy = nullptr;
4854 } else if (!Ty->isVarArg()) {
4855 return Error(ArgList[i].Loc, "too many arguments specified");
4858 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4859 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4860 getTypeString(ExpectedTy) + "'");
4861 Args.push_back(ArgList[i].V);
4862 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4863 AttrBuilder B(ArgList[i].Attrs, i + 1);
4864 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4869 return Error(CallLoc, "not enough parameters specified for call");
4871 if (FnAttrs.hasAttributes()) {
4872 if (FnAttrs.hasAlignmentAttr())
4873 return Error(CallLoc, "invoke instructions may not have an alignment");
4875 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4876 AttributeSet::FunctionIndex,
4880 // Finish off the Attribute and check them
4881 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4883 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4884 II->setCallingConv(CC);
4885 II->setAttributes(PAL);
4886 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4892 /// ::= 'resume' TypeAndValue
4893 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4894 Value *Exn; LocTy ExnLoc;
4895 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4898 ResumeInst *RI = ResumeInst::Create(Exn);
4903 //===----------------------------------------------------------------------===//
4904 // Binary Operators.
4905 //===----------------------------------------------------------------------===//
4908 /// ::= ArithmeticOps TypeAndValue ',' Value
4910 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4911 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4912 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4913 unsigned Opc, unsigned OperandType) {
4914 LocTy Loc; Value *LHS, *RHS;
4915 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4916 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4917 ParseValue(LHS->getType(), RHS, PFS))
4921 switch (OperandType) {
4922 default: llvm_unreachable("Unknown operand type!");
4923 case 0: // int or FP.
4924 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4925 LHS->getType()->isFPOrFPVectorTy();
4927 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4928 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4932 return Error(Loc, "invalid operand type for instruction");
4934 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4939 /// ::= ArithmeticOps TypeAndValue ',' Value {
4940 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4942 LocTy Loc; Value *LHS, *RHS;
4943 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4944 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4945 ParseValue(LHS->getType(), RHS, PFS))
4948 if (!LHS->getType()->isIntOrIntVectorTy())
4949 return Error(Loc,"instruction requires integer or integer vector operands");
4951 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4957 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4958 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4959 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4961 // Parse the integer/fp comparison predicate.
4965 if (ParseCmpPredicate(Pred, Opc) ||
4966 ParseTypeAndValue(LHS, Loc, PFS) ||
4967 ParseToken(lltok::comma, "expected ',' after compare value") ||
4968 ParseValue(LHS->getType(), RHS, PFS))
4971 if (Opc == Instruction::FCmp) {
4972 if (!LHS->getType()->isFPOrFPVectorTy())
4973 return Error(Loc, "fcmp requires floating point operands");
4974 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4976 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4977 if (!LHS->getType()->isIntOrIntVectorTy() &&
4978 !LHS->getType()->getScalarType()->isPointerTy())
4979 return Error(Loc, "icmp requires integer operands");
4980 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4985 //===----------------------------------------------------------------------===//
4986 // Other Instructions.
4987 //===----------------------------------------------------------------------===//
4991 /// ::= CastOpc TypeAndValue 'to' Type
4992 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4996 Type *DestTy = nullptr;
4997 if (ParseTypeAndValue(Op, Loc, PFS) ||
4998 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5002 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5003 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5004 return Error(Loc, "invalid cast opcode for cast from '" +
5005 getTypeString(Op->getType()) + "' to '" +
5006 getTypeString(DestTy) + "'");
5008 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5013 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5014 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5016 Value *Op0, *Op1, *Op2;
5017 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5018 ParseToken(lltok::comma, "expected ',' after select condition") ||
5019 ParseTypeAndValue(Op1, PFS) ||
5020 ParseToken(lltok::comma, "expected ',' after select value") ||
5021 ParseTypeAndValue(Op2, PFS))
5024 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5025 return Error(Loc, Reason);
5027 Inst = SelectInst::Create(Op0, Op1, Op2);
5032 /// ::= 'va_arg' TypeAndValue ',' Type
5033 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5035 Type *EltTy = nullptr;
5037 if (ParseTypeAndValue(Op, PFS) ||
5038 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5039 ParseType(EltTy, TypeLoc))
5042 if (!EltTy->isFirstClassType())
5043 return Error(TypeLoc, "va_arg requires operand with first class type");
5045 Inst = new VAArgInst(Op, EltTy);
5049 /// ParseExtractElement
5050 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5051 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5054 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5055 ParseToken(lltok::comma, "expected ',' after extract value") ||
5056 ParseTypeAndValue(Op1, PFS))
5059 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5060 return Error(Loc, "invalid extractelement operands");
5062 Inst = ExtractElementInst::Create(Op0, Op1);
5066 /// ParseInsertElement
5067 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5068 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5070 Value *Op0, *Op1, *Op2;
5071 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5072 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5073 ParseTypeAndValue(Op1, PFS) ||
5074 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5075 ParseTypeAndValue(Op2, PFS))
5078 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5079 return Error(Loc, "invalid insertelement operands");
5081 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5085 /// ParseShuffleVector
5086 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5087 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5089 Value *Op0, *Op1, *Op2;
5090 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5091 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5092 ParseTypeAndValue(Op1, PFS) ||
5093 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5094 ParseTypeAndValue(Op2, PFS))
5097 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5098 return Error(Loc, "invalid shufflevector operands");
5100 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5105 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5106 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5107 Type *Ty = nullptr; LocTy TypeLoc;
5110 if (ParseType(Ty, TypeLoc) ||
5111 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5112 ParseValue(Ty, Op0, PFS) ||
5113 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5114 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5115 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5118 bool AteExtraComma = false;
5119 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5121 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5123 if (!EatIfPresent(lltok::comma))
5126 if (Lex.getKind() == lltok::MetadataVar) {
5127 AteExtraComma = true;
5131 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5132 ParseValue(Ty, Op0, PFS) ||
5133 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5134 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5135 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5139 if (!Ty->isFirstClassType())
5140 return Error(TypeLoc, "phi node must have first class type");
5142 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5143 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5144 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5146 return AteExtraComma ? InstExtraComma : InstNormal;
5150 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5152 /// ::= 'catch' TypeAndValue
5154 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5155 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5156 Type *Ty = nullptr; LocTy TyLoc;
5158 if (ParseType(Ty, TyLoc))
5161 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5162 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5164 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5165 LandingPadInst::ClauseType CT;
5166 if (EatIfPresent(lltok::kw_catch))
5167 CT = LandingPadInst::Catch;
5168 else if (EatIfPresent(lltok::kw_filter))
5169 CT = LandingPadInst::Filter;
5171 return TokError("expected 'catch' or 'filter' clause type");
5175 if (ParseTypeAndValue(V, VLoc, PFS))
5178 // A 'catch' type expects a non-array constant. A filter clause expects an
5180 if (CT == LandingPadInst::Catch) {
5181 if (isa<ArrayType>(V->getType()))
5182 Error(VLoc, "'catch' clause has an invalid type");
5184 if (!isa<ArrayType>(V->getType()))
5185 Error(VLoc, "'filter' clause has an invalid type");
5188 Constant *CV = dyn_cast<Constant>(V);
5190 return Error(VLoc, "clause argument must be a constant");
5194 Inst = LP.release();
5199 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5200 /// ParameterList OptionalAttrs
5201 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5202 /// ParameterList OptionalAttrs
5203 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5204 /// ParameterList OptionalAttrs
5205 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5206 CallInst::TailCallKind TCK) {
5207 AttrBuilder RetAttrs, FnAttrs;
5208 std::vector<unsigned> FwdRefAttrGrps;
5211 Type *RetType = nullptr;
5214 SmallVector<ParamInfo, 16> ArgList;
5215 LocTy CallLoc = Lex.getLoc();
5217 if ((TCK != CallInst::TCK_None &&
5218 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5219 ParseOptionalCallingConv(CC) ||
5220 ParseOptionalReturnAttrs(RetAttrs) ||
5221 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5222 ParseValID(CalleeID) ||
5223 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5224 PFS.getFunction().isVarArg()) ||
5225 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5229 // If RetType is a non-function pointer type, then this is the short syntax
5230 // for the call, which means that RetType is just the return type. Infer the
5231 // rest of the function argument types from the arguments that are present.
5232 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5234 // Pull out the types of all of the arguments...
5235 std::vector<Type*> ParamTypes;
5236 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5237 ParamTypes.push_back(ArgList[i].V->getType());
5239 if (!FunctionType::isValidReturnType(RetType))
5240 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5242 Ty = FunctionType::get(RetType, ParamTypes, false);
5245 // Look up the callee.
5247 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5250 // Set up the Attribute for the function.
5251 SmallVector<AttributeSet, 8> Attrs;
5252 if (RetAttrs.hasAttributes())
5253 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5254 AttributeSet::ReturnIndex,
5257 SmallVector<Value*, 8> Args;
5259 // Loop through FunctionType's arguments and ensure they are specified
5260 // correctly. Also, gather any parameter attributes.
5261 FunctionType::param_iterator I = Ty->param_begin();
5262 FunctionType::param_iterator E = Ty->param_end();
5263 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5264 Type *ExpectedTy = nullptr;
5267 } else if (!Ty->isVarArg()) {
5268 return Error(ArgList[i].Loc, "too many arguments specified");
5271 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5272 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5273 getTypeString(ExpectedTy) + "'");
5274 Args.push_back(ArgList[i].V);
5275 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5276 AttrBuilder B(ArgList[i].Attrs, i + 1);
5277 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5282 return Error(CallLoc, "not enough parameters specified for call");
5284 if (FnAttrs.hasAttributes()) {
5285 if (FnAttrs.hasAlignmentAttr())
5286 return Error(CallLoc, "call instructions may not have an alignment");
5288 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5289 AttributeSet::FunctionIndex,
5293 // Finish off the Attribute and check them
5294 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5296 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5297 CI->setTailCallKind(TCK);
5298 CI->setCallingConv(CC);
5299 CI->setAttributes(PAL);
5300 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5305 //===----------------------------------------------------------------------===//
5306 // Memory Instructions.
5307 //===----------------------------------------------------------------------===//
5310 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5311 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5312 Value *Size = nullptr;
5313 LocTy SizeLoc, TyLoc;
5314 unsigned Alignment = 0;
5317 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5319 if (ParseType(Ty, TyLoc)) return true;
5321 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5322 return Error(TyLoc, "invalid type for alloca");
5324 bool AteExtraComma = false;
5325 if (EatIfPresent(lltok::comma)) {
5326 if (Lex.getKind() == lltok::kw_align) {
5327 if (ParseOptionalAlignment(Alignment)) return true;
5328 } else if (Lex.getKind() == lltok::MetadataVar) {
5329 AteExtraComma = true;
5331 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5332 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5337 if (Size && !Size->getType()->isIntegerTy())
5338 return Error(SizeLoc, "element count must have integer type");
5340 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5341 AI->setUsedWithInAlloca(IsInAlloca);
5343 return AteExtraComma ? InstExtraComma : InstNormal;
5347 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5348 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5349 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5350 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5351 Value *Val; LocTy Loc;
5352 unsigned Alignment = 0;
5353 bool AteExtraComma = false;
5354 bool isAtomic = false;
5355 AtomicOrdering Ordering = NotAtomic;
5356 SynchronizationScope Scope = CrossThread;
5358 if (Lex.getKind() == lltok::kw_atomic) {
5363 bool isVolatile = false;
5364 if (Lex.getKind() == lltok::kw_volatile) {
5370 LocTy ExplicitTypeLoc = Lex.getLoc();
5371 if (ParseType(Ty) ||
5372 ParseToken(lltok::comma, "expected comma after load's type") ||
5373 ParseTypeAndValue(Val, Loc, PFS) ||
5374 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5375 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5378 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5379 return Error(Loc, "load operand must be a pointer to a first class type");
5380 if (isAtomic && !Alignment)
5381 return Error(Loc, "atomic load must have explicit non-zero alignment");
5382 if (Ordering == Release || Ordering == AcquireRelease)
5383 return Error(Loc, "atomic load cannot use Release ordering");
5385 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5386 return Error(ExplicitTypeLoc,
5387 "explicit pointee type doesn't match operand's pointee type");
5389 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5390 return AteExtraComma ? InstExtraComma : InstNormal;
5395 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5396 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5397 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5398 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5399 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5400 unsigned Alignment = 0;
5401 bool AteExtraComma = false;
5402 bool isAtomic = false;
5403 AtomicOrdering Ordering = NotAtomic;
5404 SynchronizationScope Scope = CrossThread;
5406 if (Lex.getKind() == lltok::kw_atomic) {
5411 bool isVolatile = false;
5412 if (Lex.getKind() == lltok::kw_volatile) {
5417 if (ParseTypeAndValue(Val, Loc, PFS) ||
5418 ParseToken(lltok::comma, "expected ',' after store operand") ||
5419 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5420 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5421 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5424 if (!Ptr->getType()->isPointerTy())
5425 return Error(PtrLoc, "store operand must be a pointer");
5426 if (!Val->getType()->isFirstClassType())
5427 return Error(Loc, "store operand must be a first class value");
5428 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5429 return Error(Loc, "stored value and pointer type do not match");
5430 if (isAtomic && !Alignment)
5431 return Error(Loc, "atomic store must have explicit non-zero alignment");
5432 if (Ordering == Acquire || Ordering == AcquireRelease)
5433 return Error(Loc, "atomic store cannot use Acquire ordering");
5435 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5436 return AteExtraComma ? InstExtraComma : InstNormal;
5440 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5441 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5442 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5443 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5444 bool AteExtraComma = false;
5445 AtomicOrdering SuccessOrdering = NotAtomic;
5446 AtomicOrdering FailureOrdering = NotAtomic;
5447 SynchronizationScope Scope = CrossThread;
5448 bool isVolatile = false;
5449 bool isWeak = false;
5451 if (EatIfPresent(lltok::kw_weak))
5454 if (EatIfPresent(lltok::kw_volatile))
5457 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5458 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5459 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5460 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5461 ParseTypeAndValue(New, NewLoc, PFS) ||
5462 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5463 ParseOrdering(FailureOrdering))
5466 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5467 return TokError("cmpxchg cannot be unordered");
5468 if (SuccessOrdering < FailureOrdering)
5469 return TokError("cmpxchg must be at least as ordered on success as failure");
5470 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5471 return TokError("cmpxchg failure ordering cannot include release semantics");
5472 if (!Ptr->getType()->isPointerTy())
5473 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5474 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5475 return Error(CmpLoc, "compare value and pointer type do not match");
5476 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5477 return Error(NewLoc, "new value and pointer type do not match");
5478 if (!New->getType()->isIntegerTy())
5479 return Error(NewLoc, "cmpxchg operand must be an integer");
5480 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5481 if (Size < 8 || (Size & (Size - 1)))
5482 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5485 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5486 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5487 CXI->setVolatile(isVolatile);
5488 CXI->setWeak(isWeak);
5490 return AteExtraComma ? InstExtraComma : InstNormal;
5494 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5495 /// 'singlethread'? AtomicOrdering
5496 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5497 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5498 bool AteExtraComma = false;
5499 AtomicOrdering Ordering = NotAtomic;
5500 SynchronizationScope Scope = CrossThread;
5501 bool isVolatile = false;
5502 AtomicRMWInst::BinOp Operation;
5504 if (EatIfPresent(lltok::kw_volatile))
5507 switch (Lex.getKind()) {
5508 default: return TokError("expected binary operation in atomicrmw");
5509 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5510 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5511 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5512 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5513 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5514 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5515 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5516 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5517 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5518 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5519 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5521 Lex.Lex(); // Eat the operation.
5523 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5524 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5525 ParseTypeAndValue(Val, ValLoc, PFS) ||
5526 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5529 if (Ordering == Unordered)
5530 return TokError("atomicrmw cannot be unordered");
5531 if (!Ptr->getType()->isPointerTy())
5532 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5533 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5534 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5535 if (!Val->getType()->isIntegerTy())
5536 return Error(ValLoc, "atomicrmw operand must be an integer");
5537 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5538 if (Size < 8 || (Size & (Size - 1)))
5539 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5542 AtomicRMWInst *RMWI =
5543 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5544 RMWI->setVolatile(isVolatile);
5546 return AteExtraComma ? InstExtraComma : InstNormal;
5550 /// ::= 'fence' 'singlethread'? AtomicOrdering
5551 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5552 AtomicOrdering Ordering = NotAtomic;
5553 SynchronizationScope Scope = CrossThread;
5554 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5557 if (Ordering == Unordered)
5558 return TokError("fence cannot be unordered");
5559 if (Ordering == Monotonic)
5560 return TokError("fence cannot be monotonic");
5562 Inst = new FenceInst(Context, Ordering, Scope);
5566 /// ParseGetElementPtr
5567 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5568 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5569 Value *Ptr = nullptr;
5570 Value *Val = nullptr;
5573 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5576 LocTy ExplicitTypeLoc = Lex.getLoc();
5577 if (ParseType(Ty) ||
5578 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5579 ParseTypeAndValue(Ptr, Loc, PFS))
5582 Type *BaseType = Ptr->getType();
5583 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5584 if (!BasePointerType)
5585 return Error(Loc, "base of getelementptr must be a pointer");
5587 if (Ty != BasePointerType->getElementType())
5588 return Error(ExplicitTypeLoc,
5589 "explicit pointee type doesn't match operand's pointee type");
5591 SmallVector<Value*, 16> Indices;
5592 bool AteExtraComma = false;
5593 // GEP returns a vector of pointers if at least one of parameters is a vector.
5594 // All vector parameters should have the same vector width.
5595 unsigned GEPWidth = BaseType->isVectorTy() ?
5596 BaseType->getVectorNumElements() : 0;
5598 while (EatIfPresent(lltok::comma)) {
5599 if (Lex.getKind() == lltok::MetadataVar) {
5600 AteExtraComma = true;
5603 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5604 if (!Val->getType()->getScalarType()->isIntegerTy())
5605 return Error(EltLoc, "getelementptr index must be an integer");
5607 if (Val->getType()->isVectorTy()) {
5608 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5609 if (GEPWidth && GEPWidth != ValNumEl)
5610 return Error(EltLoc,
5611 "getelementptr vector index has a wrong number of elements");
5612 GEPWidth = ValNumEl;
5614 Indices.push_back(Val);
5617 SmallPtrSet<const Type*, 4> Visited;
5618 if (!Indices.empty() && !Ty->isSized(&Visited))
5619 return Error(Loc, "base element of getelementptr must be sized");
5621 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5622 return Error(Loc, "invalid getelementptr indices");
5623 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5625 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5626 return AteExtraComma ? InstExtraComma : InstNormal;
5629 /// ParseExtractValue
5630 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5631 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5632 Value *Val; LocTy Loc;
5633 SmallVector<unsigned, 4> Indices;
5635 if (ParseTypeAndValue(Val, Loc, PFS) ||
5636 ParseIndexList(Indices, AteExtraComma))
5639 if (!Val->getType()->isAggregateType())
5640 return Error(Loc, "extractvalue operand must be aggregate type");
5642 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5643 return Error(Loc, "invalid indices for extractvalue");
5644 Inst = ExtractValueInst::Create(Val, Indices);
5645 return AteExtraComma ? InstExtraComma : InstNormal;
5648 /// ParseInsertValue
5649 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5650 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5651 Value *Val0, *Val1; LocTy Loc0, Loc1;
5652 SmallVector<unsigned, 4> Indices;
5654 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5655 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5656 ParseTypeAndValue(Val1, Loc1, PFS) ||
5657 ParseIndexList(Indices, AteExtraComma))
5660 if (!Val0->getType()->isAggregateType())
5661 return Error(Loc0, "insertvalue operand must be aggregate type");
5663 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5665 return Error(Loc0, "invalid indices for insertvalue");
5666 if (IndexedType != Val1->getType())
5667 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5668 getTypeString(Val1->getType()) + "' instead of '" +
5669 getTypeString(IndexedType) + "'");
5670 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5671 return AteExtraComma ? InstExtraComma : InstNormal;
5674 //===----------------------------------------------------------------------===//
5675 // Embedded metadata.
5676 //===----------------------------------------------------------------------===//
5678 /// ParseMDNodeVector
5679 /// ::= { Element (',' Element)* }
5681 /// ::= 'null' | TypeAndValue
5682 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5683 if (ParseToken(lltok::lbrace, "expected '{' here"))
5686 // Check for an empty list.
5687 if (EatIfPresent(lltok::rbrace))
5691 // Null is a special case since it is typeless.
5692 if (EatIfPresent(lltok::kw_null)) {
5693 Elts.push_back(nullptr);
5698 if (ParseMetadata(MD, nullptr))
5701 } while (EatIfPresent(lltok::comma));
5703 return ParseToken(lltok::rbrace, "expected end of metadata node");
5706 //===----------------------------------------------------------------------===//
5707 // Use-list order directives.
5708 //===----------------------------------------------------------------------===//
5709 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5712 return Error(Loc, "value has no uses");
5714 unsigned NumUses = 0;
5715 SmallDenseMap<const Use *, unsigned, 16> Order;
5716 for (const Use &U : V->uses()) {
5717 if (++NumUses > Indexes.size())
5719 Order[&U] = Indexes[NumUses - 1];
5722 return Error(Loc, "value only has one use");
5723 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5724 return Error(Loc, "wrong number of indexes, expected " +
5725 Twine(std::distance(V->use_begin(), V->use_end())));
5727 V->sortUseList([&](const Use &L, const Use &R) {
5728 return Order.lookup(&L) < Order.lookup(&R);
5733 /// ParseUseListOrderIndexes
5734 /// ::= '{' uint32 (',' uint32)+ '}'
5735 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5736 SMLoc Loc = Lex.getLoc();
5737 if (ParseToken(lltok::lbrace, "expected '{' here"))
5739 if (Lex.getKind() == lltok::rbrace)
5740 return Lex.Error("expected non-empty list of uselistorder indexes");
5742 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5743 // indexes should be distinct numbers in the range [0, size-1], and should
5745 unsigned Offset = 0;
5747 bool IsOrdered = true;
5748 assert(Indexes.empty() && "Expected empty order vector");
5751 if (ParseUInt32(Index))
5754 // Update consistency checks.
5755 Offset += Index - Indexes.size();
5756 Max = std::max(Max, Index);
5757 IsOrdered &= Index == Indexes.size();
5759 Indexes.push_back(Index);
5760 } while (EatIfPresent(lltok::comma));
5762 if (ParseToken(lltok::rbrace, "expected '}' here"))
5765 if (Indexes.size() < 2)
5766 return Error(Loc, "expected >= 2 uselistorder indexes");
5767 if (Offset != 0 || Max >= Indexes.size())
5768 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5770 return Error(Loc, "expected uselistorder indexes to change the order");
5775 /// ParseUseListOrder
5776 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5777 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5778 SMLoc Loc = Lex.getLoc();
5779 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5783 SmallVector<unsigned, 16> Indexes;
5784 if (ParseTypeAndValue(V, PFS) ||
5785 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5786 ParseUseListOrderIndexes(Indexes))
5789 return sortUseListOrder(V, Indexes, Loc);
5792 /// ParseUseListOrderBB
5793 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5794 bool LLParser::ParseUseListOrderBB() {
5795 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5796 SMLoc Loc = Lex.getLoc();
5800 SmallVector<unsigned, 16> Indexes;
5801 if (ParseValID(Fn) ||
5802 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5803 ParseValID(Label) ||
5804 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5805 ParseUseListOrderIndexes(Indexes))
5808 // Check the function.
5810 if (Fn.Kind == ValID::t_GlobalName)
5811 GV = M->getNamedValue(Fn.StrVal);
5812 else if (Fn.Kind == ValID::t_GlobalID)
5813 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5815 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5817 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5818 auto *F = dyn_cast<Function>(GV);
5820 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5821 if (F->isDeclaration())
5822 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5824 // Check the basic block.
5825 if (Label.Kind == ValID::t_LocalID)
5826 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5827 if (Label.Kind != ValID::t_LocalName)
5828 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5829 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5831 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5832 if (!isa<BasicBlock>(V))
5833 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5835 return sortUseListOrder(V, Indexes, Loc);