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_builtin: B.addAttribute(Attribute::Builtin); break;
951 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
952 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
953 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
954 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
955 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
956 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
957 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
958 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
959 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
960 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
961 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
962 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
963 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
964 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
965 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
966 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
967 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
968 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
969 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
970 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
971 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
972 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
973 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
974 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
975 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
976 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
977 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
980 case lltok::kw_inreg:
981 case lltok::kw_signext:
982 case lltok::kw_zeroext:
985 "invalid use of attribute on a function");
987 case lltok::kw_byval:
988 case lltok::kw_dereferenceable:
989 case lltok::kw_dereferenceable_or_null:
990 case lltok::kw_inalloca:
992 case lltok::kw_noalias:
993 case lltok::kw_nocapture:
994 case lltok::kw_nonnull:
995 case lltok::kw_returned:
999 "invalid use of parameter-only attribute on a function");
1007 //===----------------------------------------------------------------------===//
1008 // GlobalValue Reference/Resolution Routines.
1009 //===----------------------------------------------------------------------===//
1011 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1012 /// forward reference record if needed. This can return null if the value
1013 /// exists but does not have the right type.
1014 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1016 PointerType *PTy = dyn_cast<PointerType>(Ty);
1018 Error(Loc, "global variable reference must have pointer type");
1022 // Look this name up in the normal function symbol table.
1024 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1026 // If this is a forward reference for the value, see if we already created a
1027 // forward ref record.
1029 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1030 I = ForwardRefVals.find(Name);
1031 if (I != ForwardRefVals.end())
1032 Val = I->second.first;
1035 // If we have the value in the symbol table or fwd-ref table, return it.
1037 if (Val->getType() == Ty) return Val;
1038 Error(Loc, "'@" + Name + "' defined with type '" +
1039 getTypeString(Val->getType()) + "'");
1043 // Otherwise, create a new forward reference for this value and remember it.
1044 GlobalValue *FwdVal;
1045 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1046 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1048 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1049 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1050 nullptr, GlobalVariable::NotThreadLocal,
1051 PTy->getAddressSpace());
1053 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1057 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1058 PointerType *PTy = dyn_cast<PointerType>(Ty);
1060 Error(Loc, "global variable reference must have pointer type");
1064 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1066 // If this is a forward reference for the value, see if we already created a
1067 // forward ref record.
1069 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1070 I = ForwardRefValIDs.find(ID);
1071 if (I != ForwardRefValIDs.end())
1072 Val = I->second.first;
1075 // If we have the value in the symbol table or fwd-ref table, return it.
1077 if (Val->getType() == Ty) return Val;
1078 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1079 getTypeString(Val->getType()) + "'");
1083 // Otherwise, create a new forward reference for this value and remember it.
1084 GlobalValue *FwdVal;
1085 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1086 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1088 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1089 GlobalValue::ExternalWeakLinkage, nullptr, "");
1091 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1096 //===----------------------------------------------------------------------===//
1097 // Comdat Reference/Resolution Routines.
1098 //===----------------------------------------------------------------------===//
1100 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1101 // Look this name up in the comdat symbol table.
1102 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1103 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1104 if (I != ComdatSymTab.end())
1107 // Otherwise, create a new forward reference for this value and remember it.
1108 Comdat *C = M->getOrInsertComdat(Name);
1109 ForwardRefComdats[Name] = Loc;
1114 //===----------------------------------------------------------------------===//
1116 //===----------------------------------------------------------------------===//
1118 /// ParseToken - If the current token has the specified kind, eat it and return
1119 /// success. Otherwise, emit the specified error and return failure.
1120 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1121 if (Lex.getKind() != T)
1122 return TokError(ErrMsg);
1127 /// ParseStringConstant
1128 /// ::= StringConstant
1129 bool LLParser::ParseStringConstant(std::string &Result) {
1130 if (Lex.getKind() != lltok::StringConstant)
1131 return TokError("expected string constant");
1132 Result = Lex.getStrVal();
1139 bool LLParser::ParseUInt32(unsigned &Val) {
1140 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1141 return TokError("expected integer");
1142 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1143 if (Val64 != unsigned(Val64))
1144 return TokError("expected 32-bit integer (too large)");
1152 bool LLParser::ParseUInt64(uint64_t &Val) {
1153 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1154 return TokError("expected integer");
1155 Val = Lex.getAPSIntVal().getLimitedValue();
1161 /// := 'localdynamic'
1162 /// := 'initialexec'
1164 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1165 switch (Lex.getKind()) {
1167 return TokError("expected localdynamic, initialexec or localexec");
1168 case lltok::kw_localdynamic:
1169 TLM = GlobalVariable::LocalDynamicTLSModel;
1171 case lltok::kw_initialexec:
1172 TLM = GlobalVariable::InitialExecTLSModel;
1174 case lltok::kw_localexec:
1175 TLM = GlobalVariable::LocalExecTLSModel;
1183 /// ParseOptionalThreadLocal
1185 /// := 'thread_local'
1186 /// := 'thread_local' '(' tlsmodel ')'
1187 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1188 TLM = GlobalVariable::NotThreadLocal;
1189 if (!EatIfPresent(lltok::kw_thread_local))
1192 TLM = GlobalVariable::GeneralDynamicTLSModel;
1193 if (Lex.getKind() == lltok::lparen) {
1195 return ParseTLSModel(TLM) ||
1196 ParseToken(lltok::rparen, "expected ')' after thread local model");
1201 /// ParseOptionalAddrSpace
1203 /// := 'addrspace' '(' uint32 ')'
1204 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1206 if (!EatIfPresent(lltok::kw_addrspace))
1208 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1209 ParseUInt32(AddrSpace) ||
1210 ParseToken(lltok::rparen, "expected ')' in address space");
1213 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1214 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1215 bool HaveError = false;
1220 lltok::Kind Token = Lex.getKind();
1222 default: // End of attributes.
1224 case lltok::kw_align: {
1226 if (ParseOptionalAlignment(Alignment))
1228 B.addAlignmentAttr(Alignment);
1231 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1232 case lltok::kw_dereferenceable: {
1234 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1236 B.addDereferenceableAttr(Bytes);
1239 case lltok::kw_dereferenceable_or_null: {
1241 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1243 B.addDereferenceableOrNullAttr(Bytes);
1246 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1247 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1248 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1249 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1250 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1251 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1252 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1253 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1254 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1255 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1256 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1257 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1259 case lltok::kw_alignstack:
1260 case lltok::kw_alwaysinline:
1261 case lltok::kw_builtin:
1262 case lltok::kw_inlinehint:
1263 case lltok::kw_jumptable:
1264 case lltok::kw_minsize:
1265 case lltok::kw_naked:
1266 case lltok::kw_nobuiltin:
1267 case lltok::kw_noduplicate:
1268 case lltok::kw_noimplicitfloat:
1269 case lltok::kw_noinline:
1270 case lltok::kw_nonlazybind:
1271 case lltok::kw_noredzone:
1272 case lltok::kw_noreturn:
1273 case lltok::kw_nounwind:
1274 case lltok::kw_optnone:
1275 case lltok::kw_optsize:
1276 case lltok::kw_returns_twice:
1277 case lltok::kw_sanitize_address:
1278 case lltok::kw_sanitize_memory:
1279 case lltok::kw_sanitize_thread:
1281 case lltok::kw_sspreq:
1282 case lltok::kw_sspstrong:
1283 case lltok::kw_safestack:
1284 case lltok::kw_uwtable:
1285 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1293 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1294 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1295 bool HaveError = false;
1300 lltok::Kind Token = Lex.getKind();
1302 default: // End of attributes.
1304 case lltok::kw_dereferenceable: {
1306 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1308 B.addDereferenceableAttr(Bytes);
1311 case lltok::kw_dereferenceable_or_null: {
1313 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1315 B.addDereferenceableOrNullAttr(Bytes);
1318 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1319 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1320 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1321 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1322 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1325 case lltok::kw_align:
1326 case lltok::kw_byval:
1327 case lltok::kw_inalloca:
1328 case lltok::kw_nest:
1329 case lltok::kw_nocapture:
1330 case lltok::kw_returned:
1331 case lltok::kw_sret:
1332 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1335 case lltok::kw_alignstack:
1336 case lltok::kw_alwaysinline:
1337 case lltok::kw_builtin:
1338 case lltok::kw_cold:
1339 case lltok::kw_inlinehint:
1340 case lltok::kw_jumptable:
1341 case lltok::kw_minsize:
1342 case lltok::kw_naked:
1343 case lltok::kw_nobuiltin:
1344 case lltok::kw_noduplicate:
1345 case lltok::kw_noimplicitfloat:
1346 case lltok::kw_noinline:
1347 case lltok::kw_nonlazybind:
1348 case lltok::kw_noredzone:
1349 case lltok::kw_noreturn:
1350 case lltok::kw_nounwind:
1351 case lltok::kw_optnone:
1352 case lltok::kw_optsize:
1353 case lltok::kw_returns_twice:
1354 case lltok::kw_sanitize_address:
1355 case lltok::kw_sanitize_memory:
1356 case lltok::kw_sanitize_thread:
1358 case lltok::kw_sspreq:
1359 case lltok::kw_sspstrong:
1360 case lltok::kw_safestack:
1361 case lltok::kw_uwtable:
1362 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1365 case lltok::kw_readnone:
1366 case lltok::kw_readonly:
1367 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1374 /// ParseOptionalLinkage
1381 /// ::= 'linkonce_odr'
1382 /// ::= 'available_externally'
1385 /// ::= 'extern_weak'
1387 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1389 switch (Lex.getKind()) {
1390 default: Res=GlobalValue::ExternalLinkage; return false;
1391 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1392 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1393 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1394 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1395 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1396 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1397 case lltok::kw_available_externally:
1398 Res = GlobalValue::AvailableExternallyLinkage;
1400 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1401 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1402 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1403 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1410 /// ParseOptionalVisibility
1416 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1417 switch (Lex.getKind()) {
1418 default: Res = GlobalValue::DefaultVisibility; return false;
1419 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1420 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1421 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1427 /// ParseOptionalDLLStorageClass
1432 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1433 switch (Lex.getKind()) {
1434 default: Res = GlobalValue::DefaultStorageClass; return false;
1435 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1436 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1442 /// ParseOptionalCallingConv
1446 /// ::= 'intel_ocl_bicc'
1448 /// ::= 'x86_stdcallcc'
1449 /// ::= 'x86_fastcallcc'
1450 /// ::= 'x86_thiscallcc'
1451 /// ::= 'x86_vectorcallcc'
1452 /// ::= 'arm_apcscc'
1453 /// ::= 'arm_aapcscc'
1454 /// ::= 'arm_aapcs_vfpcc'
1455 /// ::= 'msp430_intrcc'
1456 /// ::= 'ptx_kernel'
1457 /// ::= 'ptx_device'
1459 /// ::= 'spir_kernel'
1460 /// ::= 'x86_64_sysvcc'
1461 /// ::= 'x86_64_win64cc'
1462 /// ::= 'webkit_jscc'
1464 /// ::= 'preserve_mostcc'
1465 /// ::= 'preserve_allcc'
1469 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1470 switch (Lex.getKind()) {
1471 default: CC = CallingConv::C; return false;
1472 case lltok::kw_ccc: CC = CallingConv::C; break;
1473 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1474 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1475 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1476 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1477 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1478 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1479 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1480 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1481 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1482 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1483 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1484 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1485 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1486 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1487 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1488 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1489 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1490 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1491 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1492 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1493 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1494 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1495 case lltok::kw_cc: {
1497 return ParseUInt32(CC);
1505 /// ParseMetadataAttachment
1507 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1508 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1510 std::string Name = Lex.getStrVal();
1511 Kind = M->getMDKindID(Name);
1514 return ParseMDNode(MD);
1517 /// ParseInstructionMetadata
1518 /// ::= !dbg !42 (',' !dbg !57)*
1519 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1521 if (Lex.getKind() != lltok::MetadataVar)
1522 return TokError("expected metadata after comma");
1526 if (ParseMetadataAttachment(MDK, N))
1529 Inst.setMetadata(MDK, N);
1530 if (MDK == LLVMContext::MD_tbaa)
1531 InstsWithTBAATag.push_back(&Inst);
1533 // If this is the end of the list, we're done.
1534 } while (EatIfPresent(lltok::comma));
1538 /// ParseOptionalFunctionMetadata
1540 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1541 while (Lex.getKind() == lltok::MetadataVar) {
1544 if (ParseMetadataAttachment(MDK, N))
1547 F.setMetadata(MDK, N);
1552 /// ParseOptionalAlignment
1555 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1557 if (!EatIfPresent(lltok::kw_align))
1559 LocTy AlignLoc = Lex.getLoc();
1560 if (ParseUInt32(Alignment)) return true;
1561 if (!isPowerOf2_32(Alignment))
1562 return Error(AlignLoc, "alignment is not a power of two");
1563 if (Alignment > Value::MaximumAlignment)
1564 return Error(AlignLoc, "huge alignments are not supported yet");
1568 /// ParseOptionalDerefAttrBytes
1570 /// ::= AttrKind '(' 4 ')'
1572 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1573 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1575 assert((AttrKind == lltok::kw_dereferenceable ||
1576 AttrKind == lltok::kw_dereferenceable_or_null) &&
1580 if (!EatIfPresent(AttrKind))
1582 LocTy ParenLoc = Lex.getLoc();
1583 if (!EatIfPresent(lltok::lparen))
1584 return Error(ParenLoc, "expected '('");
1585 LocTy DerefLoc = Lex.getLoc();
1586 if (ParseUInt64(Bytes)) return true;
1587 ParenLoc = Lex.getLoc();
1588 if (!EatIfPresent(lltok::rparen))
1589 return Error(ParenLoc, "expected ')'");
1591 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1595 /// ParseOptionalCommaAlign
1599 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1601 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1602 bool &AteExtraComma) {
1603 AteExtraComma = false;
1604 while (EatIfPresent(lltok::comma)) {
1605 // Metadata at the end is an early exit.
1606 if (Lex.getKind() == lltok::MetadataVar) {
1607 AteExtraComma = true;
1611 if (Lex.getKind() != lltok::kw_align)
1612 return Error(Lex.getLoc(), "expected metadata or 'align'");
1614 if (ParseOptionalAlignment(Alignment)) return true;
1620 /// ParseScopeAndOrdering
1621 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1624 /// This sets Scope and Ordering to the parsed values.
1625 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1626 AtomicOrdering &Ordering) {
1630 Scope = CrossThread;
1631 if (EatIfPresent(lltok::kw_singlethread))
1632 Scope = SingleThread;
1634 return ParseOrdering(Ordering);
1638 /// ::= AtomicOrdering
1640 /// This sets Ordering to the parsed value.
1641 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1642 switch (Lex.getKind()) {
1643 default: return TokError("Expected ordering on atomic instruction");
1644 case lltok::kw_unordered: Ordering = Unordered; break;
1645 case lltok::kw_monotonic: Ordering = Monotonic; break;
1646 case lltok::kw_acquire: Ordering = Acquire; break;
1647 case lltok::kw_release: Ordering = Release; break;
1648 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1649 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1655 /// ParseOptionalStackAlignment
1657 /// ::= 'alignstack' '(' 4 ')'
1658 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1660 if (!EatIfPresent(lltok::kw_alignstack))
1662 LocTy ParenLoc = Lex.getLoc();
1663 if (!EatIfPresent(lltok::lparen))
1664 return Error(ParenLoc, "expected '('");
1665 LocTy AlignLoc = Lex.getLoc();
1666 if (ParseUInt32(Alignment)) return true;
1667 ParenLoc = Lex.getLoc();
1668 if (!EatIfPresent(lltok::rparen))
1669 return Error(ParenLoc, "expected ')'");
1670 if (!isPowerOf2_32(Alignment))
1671 return Error(AlignLoc, "stack alignment is not a power of two");
1675 /// ParseIndexList - This parses the index list for an insert/extractvalue
1676 /// instruction. This sets AteExtraComma in the case where we eat an extra
1677 /// comma at the end of the line and find that it is followed by metadata.
1678 /// Clients that don't allow metadata can call the version of this function that
1679 /// only takes one argument.
1682 /// ::= (',' uint32)+
1684 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1685 bool &AteExtraComma) {
1686 AteExtraComma = false;
1688 if (Lex.getKind() != lltok::comma)
1689 return TokError("expected ',' as start of index list");
1691 while (EatIfPresent(lltok::comma)) {
1692 if (Lex.getKind() == lltok::MetadataVar) {
1693 if (Indices.empty()) return TokError("expected index");
1694 AteExtraComma = true;
1698 if (ParseUInt32(Idx)) return true;
1699 Indices.push_back(Idx);
1705 //===----------------------------------------------------------------------===//
1707 //===----------------------------------------------------------------------===//
1709 /// ParseType - Parse a type.
1710 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1711 SMLoc TypeLoc = Lex.getLoc();
1712 switch (Lex.getKind()) {
1714 return TokError(Msg);
1716 // Type ::= 'float' | 'void' (etc)
1717 Result = Lex.getTyVal();
1721 // Type ::= StructType
1722 if (ParseAnonStructType(Result, false))
1725 case lltok::lsquare:
1726 // Type ::= '[' ... ']'
1727 Lex.Lex(); // eat the lsquare.
1728 if (ParseArrayVectorType(Result, false))
1731 case lltok::less: // Either vector or packed struct.
1732 // Type ::= '<' ... '>'
1734 if (Lex.getKind() == lltok::lbrace) {
1735 if (ParseAnonStructType(Result, true) ||
1736 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1738 } else if (ParseArrayVectorType(Result, true))
1741 case lltok::LocalVar: {
1743 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1745 // If the type hasn't been defined yet, create a forward definition and
1746 // remember where that forward def'n was seen (in case it never is defined).
1748 Entry.first = StructType::create(Context, Lex.getStrVal());
1749 Entry.second = Lex.getLoc();
1751 Result = Entry.first;
1756 case lltok::LocalVarID: {
1758 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1760 // If the type hasn't been defined yet, create a forward definition and
1761 // remember where that forward def'n was seen (in case it never is defined).
1763 Entry.first = StructType::create(Context);
1764 Entry.second = Lex.getLoc();
1766 Result = Entry.first;
1772 // Parse the type suffixes.
1774 switch (Lex.getKind()) {
1777 if (!AllowVoid && Result->isVoidTy())
1778 return Error(TypeLoc, "void type only allowed for function results");
1781 // Type ::= Type '*'
1783 if (Result->isLabelTy())
1784 return TokError("basic block pointers are invalid");
1785 if (Result->isVoidTy())
1786 return TokError("pointers to void are invalid - use i8* instead");
1787 if (!PointerType::isValidElementType(Result))
1788 return TokError("pointer to this type is invalid");
1789 Result = PointerType::getUnqual(Result);
1793 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1794 case lltok::kw_addrspace: {
1795 if (Result->isLabelTy())
1796 return TokError("basic block pointers are invalid");
1797 if (Result->isVoidTy())
1798 return TokError("pointers to void are invalid; use i8* instead");
1799 if (!PointerType::isValidElementType(Result))
1800 return TokError("pointer to this type is invalid");
1802 if (ParseOptionalAddrSpace(AddrSpace) ||
1803 ParseToken(lltok::star, "expected '*' in address space"))
1806 Result = PointerType::get(Result, AddrSpace);
1810 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1812 if (ParseFunctionType(Result))
1819 /// ParseParameterList
1821 /// ::= '(' Arg (',' Arg)* ')'
1823 /// ::= Type OptionalAttributes Value OptionalAttributes
1824 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1825 PerFunctionState &PFS, bool IsMustTailCall,
1826 bool InVarArgsFunc) {
1827 if (ParseToken(lltok::lparen, "expected '(' in call"))
1830 unsigned AttrIndex = 1;
1831 while (Lex.getKind() != lltok::rparen) {
1832 // If this isn't the first argument, we need a comma.
1833 if (!ArgList.empty() &&
1834 ParseToken(lltok::comma, "expected ',' in argument list"))
1837 // Parse an ellipsis if this is a musttail call in a variadic function.
1838 if (Lex.getKind() == lltok::dotdotdot) {
1839 const char *Msg = "unexpected ellipsis in argument list for ";
1840 if (!IsMustTailCall)
1841 return TokError(Twine(Msg) + "non-musttail call");
1843 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1844 Lex.Lex(); // Lex the '...', it is purely for readability.
1845 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1848 // Parse the argument.
1850 Type *ArgTy = nullptr;
1851 AttrBuilder ArgAttrs;
1853 if (ParseType(ArgTy, ArgLoc))
1856 if (ArgTy->isMetadataTy()) {
1857 if (ParseMetadataAsValue(V, PFS))
1860 // Otherwise, handle normal operands.
1861 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1864 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1869 if (IsMustTailCall && InVarArgsFunc)
1870 return TokError("expected '...' at end of argument list for musttail call "
1871 "in varargs function");
1873 Lex.Lex(); // Lex the ')'.
1879 /// ParseArgumentList - Parse the argument list for a function type or function
1881 /// ::= '(' ArgTypeListI ')'
1885 /// ::= ArgTypeList ',' '...'
1886 /// ::= ArgType (',' ArgType)*
1888 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1891 assert(Lex.getKind() == lltok::lparen);
1892 Lex.Lex(); // eat the (.
1894 if (Lex.getKind() == lltok::rparen) {
1896 } else if (Lex.getKind() == lltok::dotdotdot) {
1900 LocTy TypeLoc = Lex.getLoc();
1901 Type *ArgTy = nullptr;
1905 if (ParseType(ArgTy) ||
1906 ParseOptionalParamAttrs(Attrs)) return true;
1908 if (ArgTy->isVoidTy())
1909 return Error(TypeLoc, "argument can not have void type");
1911 if (Lex.getKind() == lltok::LocalVar) {
1912 Name = Lex.getStrVal();
1916 if (!FunctionType::isValidArgumentType(ArgTy))
1917 return Error(TypeLoc, "invalid type for function argument");
1919 unsigned AttrIndex = 1;
1920 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1921 AttrIndex++, Attrs),
1924 while (EatIfPresent(lltok::comma)) {
1925 // Handle ... at end of arg list.
1926 if (EatIfPresent(lltok::dotdotdot)) {
1931 // Otherwise must be an argument type.
1932 TypeLoc = Lex.getLoc();
1933 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1935 if (ArgTy->isVoidTy())
1936 return Error(TypeLoc, "argument can not have void type");
1938 if (Lex.getKind() == lltok::LocalVar) {
1939 Name = Lex.getStrVal();
1945 if (!ArgTy->isFirstClassType())
1946 return Error(TypeLoc, "invalid type for function argument");
1948 ArgList.emplace_back(
1950 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1955 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1958 /// ParseFunctionType
1959 /// ::= Type ArgumentList OptionalAttrs
1960 bool LLParser::ParseFunctionType(Type *&Result) {
1961 assert(Lex.getKind() == lltok::lparen);
1963 if (!FunctionType::isValidReturnType(Result))
1964 return TokError("invalid function return type");
1966 SmallVector<ArgInfo, 8> ArgList;
1968 if (ParseArgumentList(ArgList, isVarArg))
1971 // Reject names on the arguments lists.
1972 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1973 if (!ArgList[i].Name.empty())
1974 return Error(ArgList[i].Loc, "argument name invalid in function type");
1975 if (ArgList[i].Attrs.hasAttributes(i + 1))
1976 return Error(ArgList[i].Loc,
1977 "argument attributes invalid in function type");
1980 SmallVector<Type*, 16> ArgListTy;
1981 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1982 ArgListTy.push_back(ArgList[i].Ty);
1984 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1988 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1990 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1991 SmallVector<Type*, 8> Elts;
1992 if (ParseStructBody(Elts)) return true;
1994 Result = StructType::get(Context, Elts, Packed);
1998 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1999 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2000 std::pair<Type*, LocTy> &Entry,
2002 // If the type was already defined, diagnose the redefinition.
2003 if (Entry.first && !Entry.second.isValid())
2004 return Error(TypeLoc, "redefinition of type");
2006 // If we have opaque, just return without filling in the definition for the
2007 // struct. This counts as a definition as far as the .ll file goes.
2008 if (EatIfPresent(lltok::kw_opaque)) {
2009 // This type is being defined, so clear the location to indicate this.
2010 Entry.second = SMLoc();
2012 // If this type number has never been uttered, create it.
2014 Entry.first = StructType::create(Context, Name);
2015 ResultTy = Entry.first;
2019 // If the type starts with '<', then it is either a packed struct or a vector.
2020 bool isPacked = EatIfPresent(lltok::less);
2022 // If we don't have a struct, then we have a random type alias, which we
2023 // accept for compatibility with old files. These types are not allowed to be
2024 // forward referenced and not allowed to be recursive.
2025 if (Lex.getKind() != lltok::lbrace) {
2027 return Error(TypeLoc, "forward references to non-struct type");
2031 return ParseArrayVectorType(ResultTy, true);
2032 return ParseType(ResultTy);
2035 // This type is being defined, so clear the location to indicate this.
2036 Entry.second = SMLoc();
2038 // If this type number has never been uttered, create it.
2040 Entry.first = StructType::create(Context, Name);
2042 StructType *STy = cast<StructType>(Entry.first);
2044 SmallVector<Type*, 8> Body;
2045 if (ParseStructBody(Body) ||
2046 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2049 STy->setBody(Body, isPacked);
2055 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2058 /// ::= '{' Type (',' Type)* '}'
2059 /// ::= '<' '{' '}' '>'
2060 /// ::= '<' '{' Type (',' Type)* '}' '>'
2061 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2062 assert(Lex.getKind() == lltok::lbrace);
2063 Lex.Lex(); // Consume the '{'
2065 // Handle the empty struct.
2066 if (EatIfPresent(lltok::rbrace))
2069 LocTy EltTyLoc = Lex.getLoc();
2071 if (ParseType(Ty)) return true;
2074 if (!StructType::isValidElementType(Ty))
2075 return Error(EltTyLoc, "invalid element type for struct");
2077 while (EatIfPresent(lltok::comma)) {
2078 EltTyLoc = Lex.getLoc();
2079 if (ParseType(Ty)) return true;
2081 if (!StructType::isValidElementType(Ty))
2082 return Error(EltTyLoc, "invalid element type for struct");
2087 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2090 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2091 /// token has already been consumed.
2093 /// ::= '[' APSINTVAL 'x' Types ']'
2094 /// ::= '<' APSINTVAL 'x' Types '>'
2095 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2096 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2097 Lex.getAPSIntVal().getBitWidth() > 64)
2098 return TokError("expected number in address space");
2100 LocTy SizeLoc = Lex.getLoc();
2101 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2104 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2107 LocTy TypeLoc = Lex.getLoc();
2108 Type *EltTy = nullptr;
2109 if (ParseType(EltTy)) return true;
2111 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2112 "expected end of sequential type"))
2117 return Error(SizeLoc, "zero element vector is illegal");
2118 if ((unsigned)Size != Size)
2119 return Error(SizeLoc, "size too large for vector");
2120 if (!VectorType::isValidElementType(EltTy))
2121 return Error(TypeLoc, "invalid vector element type");
2122 Result = VectorType::get(EltTy, unsigned(Size));
2124 if (!ArrayType::isValidElementType(EltTy))
2125 return Error(TypeLoc, "invalid array element type");
2126 Result = ArrayType::get(EltTy, Size);
2131 //===----------------------------------------------------------------------===//
2132 // Function Semantic Analysis.
2133 //===----------------------------------------------------------------------===//
2135 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2137 : P(p), F(f), FunctionNumber(functionNumber) {
2139 // Insert unnamed arguments into the NumberedVals list.
2140 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2143 NumberedVals.push_back(AI);
2146 LLParser::PerFunctionState::~PerFunctionState() {
2147 // If there were any forward referenced non-basicblock values, delete them.
2148 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2149 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2150 if (!isa<BasicBlock>(I->second.first)) {
2151 I->second.first->replaceAllUsesWith(
2152 UndefValue::get(I->second.first->getType()));
2153 delete I->second.first;
2154 I->second.first = nullptr;
2157 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2158 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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;
2167 bool LLParser::PerFunctionState::FinishFunction() {
2168 if (!ForwardRefVals.empty())
2169 return P.Error(ForwardRefVals.begin()->second.second,
2170 "use of undefined value '%" + ForwardRefVals.begin()->first +
2172 if (!ForwardRefValIDs.empty())
2173 return P.Error(ForwardRefValIDs.begin()->second.second,
2174 "use of undefined value '%" +
2175 Twine(ForwardRefValIDs.begin()->first) + "'");
2180 /// GetVal - Get a value with the specified name or ID, creating a
2181 /// forward reference record if needed. This can return null if the value
2182 /// exists but does not have the right type.
2183 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2184 Type *Ty, LocTy Loc) {
2185 // Look this name up in the normal function symbol table.
2186 Value *Val = F.getValueSymbolTable().lookup(Name);
2188 // If this is a forward reference for the value, see if we already created a
2189 // forward ref record.
2191 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2192 I = ForwardRefVals.find(Name);
2193 if (I != ForwardRefVals.end())
2194 Val = I->second.first;
2197 // If we have the value in the symbol table or fwd-ref table, return it.
2199 if (Val->getType() == Ty) return Val;
2200 if (Ty->isLabelTy())
2201 P.Error(Loc, "'%" + Name + "' is not a basic block");
2203 P.Error(Loc, "'%" + Name + "' defined with type '" +
2204 getTypeString(Val->getType()) + "'");
2208 // Don't make placeholders with invalid type.
2209 if (!Ty->isFirstClassType()) {
2210 P.Error(Loc, "invalid use of a non-first-class type");
2214 // Otherwise, create a new forward reference for this value and remember it.
2216 if (Ty->isLabelTy())
2217 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2219 FwdVal = new Argument(Ty, Name);
2221 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2225 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2227 // Look this name up in the normal function symbol table.
2228 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2230 // If this is a forward reference for the value, see if we already created a
2231 // forward ref record.
2233 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2234 I = ForwardRefValIDs.find(ID);
2235 if (I != ForwardRefValIDs.end())
2236 Val = I->second.first;
2239 // If we have the value in the symbol table or fwd-ref table, return it.
2241 if (Val->getType() == Ty) return Val;
2242 if (Ty->isLabelTy())
2243 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2245 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2246 getTypeString(Val->getType()) + "'");
2250 if (!Ty->isFirstClassType()) {
2251 P.Error(Loc, "invalid use of a non-first-class type");
2255 // Otherwise, create a new forward reference for this value and remember it.
2257 if (Ty->isLabelTy())
2258 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2260 FwdVal = new Argument(Ty);
2262 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2266 /// SetInstName - After an instruction is parsed and inserted into its
2267 /// basic block, this installs its name.
2268 bool LLParser::PerFunctionState::SetInstName(int NameID,
2269 const std::string &NameStr,
2270 LocTy NameLoc, Instruction *Inst) {
2271 // If this instruction has void type, it cannot have a name or ID specified.
2272 if (Inst->getType()->isVoidTy()) {
2273 if (NameID != -1 || !NameStr.empty())
2274 return P.Error(NameLoc, "instructions returning void cannot have a name");
2278 // If this was a numbered instruction, verify that the instruction is the
2279 // expected value and resolve any forward references.
2280 if (NameStr.empty()) {
2281 // If neither a name nor an ID was specified, just use the next ID.
2283 NameID = NumberedVals.size();
2285 if (unsigned(NameID) != NumberedVals.size())
2286 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2287 Twine(NumberedVals.size()) + "'");
2289 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2290 ForwardRefValIDs.find(NameID);
2291 if (FI != ForwardRefValIDs.end()) {
2292 if (FI->second.first->getType() != Inst->getType())
2293 return P.Error(NameLoc, "instruction forward referenced with type '" +
2294 getTypeString(FI->second.first->getType()) + "'");
2295 FI->second.first->replaceAllUsesWith(Inst);
2296 delete FI->second.first;
2297 ForwardRefValIDs.erase(FI);
2300 NumberedVals.push_back(Inst);
2304 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2305 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2306 FI = ForwardRefVals.find(NameStr);
2307 if (FI != ForwardRefVals.end()) {
2308 if (FI->second.first->getType() != Inst->getType())
2309 return P.Error(NameLoc, "instruction forward referenced with type '" +
2310 getTypeString(FI->second.first->getType()) + "'");
2311 FI->second.first->replaceAllUsesWith(Inst);
2312 delete FI->second.first;
2313 ForwardRefVals.erase(FI);
2316 // Set the name on the instruction.
2317 Inst->setName(NameStr);
2319 if (Inst->getName() != NameStr)
2320 return P.Error(NameLoc, "multiple definition of local value named '" +
2325 /// GetBB - Get a basic block with the specified name or ID, creating a
2326 /// forward reference record if needed.
2327 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2329 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2330 Type::getLabelTy(F.getContext()), Loc));
2333 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2334 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2335 Type::getLabelTy(F.getContext()), Loc));
2338 /// DefineBB - Define the specified basic block, which is either named or
2339 /// unnamed. If there is an error, this returns null otherwise it returns
2340 /// the block being defined.
2341 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2345 BB = GetBB(NumberedVals.size(), Loc);
2347 BB = GetBB(Name, Loc);
2348 if (!BB) return nullptr; // Already diagnosed error.
2350 // Move the block to the end of the function. Forward ref'd blocks are
2351 // inserted wherever they happen to be referenced.
2352 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2354 // Remove the block from forward ref sets.
2356 ForwardRefValIDs.erase(NumberedVals.size());
2357 NumberedVals.push_back(BB);
2359 // BB forward references are already in the function symbol table.
2360 ForwardRefVals.erase(Name);
2366 //===----------------------------------------------------------------------===//
2368 //===----------------------------------------------------------------------===//
2370 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2371 /// type implied. For example, if we parse "4" we don't know what integer type
2372 /// it has. The value will later be combined with its type and checked for
2373 /// sanity. PFS is used to convert function-local operands of metadata (since
2374 /// metadata operands are not just parsed here but also converted to values).
2375 /// PFS can be null when we are not parsing metadata values inside a function.
2376 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2377 ID.Loc = Lex.getLoc();
2378 switch (Lex.getKind()) {
2379 default: return TokError("expected value token");
2380 case lltok::GlobalID: // @42
2381 ID.UIntVal = Lex.getUIntVal();
2382 ID.Kind = ValID::t_GlobalID;
2384 case lltok::GlobalVar: // @foo
2385 ID.StrVal = Lex.getStrVal();
2386 ID.Kind = ValID::t_GlobalName;
2388 case lltok::LocalVarID: // %42
2389 ID.UIntVal = Lex.getUIntVal();
2390 ID.Kind = ValID::t_LocalID;
2392 case lltok::LocalVar: // %foo
2393 ID.StrVal = Lex.getStrVal();
2394 ID.Kind = ValID::t_LocalName;
2397 ID.APSIntVal = Lex.getAPSIntVal();
2398 ID.Kind = ValID::t_APSInt;
2400 case lltok::APFloat:
2401 ID.APFloatVal = Lex.getAPFloatVal();
2402 ID.Kind = ValID::t_APFloat;
2404 case lltok::kw_true:
2405 ID.ConstantVal = ConstantInt::getTrue(Context);
2406 ID.Kind = ValID::t_Constant;
2408 case lltok::kw_false:
2409 ID.ConstantVal = ConstantInt::getFalse(Context);
2410 ID.Kind = ValID::t_Constant;
2412 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2413 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2414 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2416 case lltok::lbrace: {
2417 // ValID ::= '{' ConstVector '}'
2419 SmallVector<Constant*, 16> Elts;
2420 if (ParseGlobalValueVector(Elts) ||
2421 ParseToken(lltok::rbrace, "expected end of struct constant"))
2424 ID.ConstantStructElts = new Constant*[Elts.size()];
2425 ID.UIntVal = Elts.size();
2426 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2427 ID.Kind = ValID::t_ConstantStruct;
2431 // ValID ::= '<' ConstVector '>' --> Vector.
2432 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2434 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2436 SmallVector<Constant*, 16> Elts;
2437 LocTy FirstEltLoc = Lex.getLoc();
2438 if (ParseGlobalValueVector(Elts) ||
2440 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2441 ParseToken(lltok::greater, "expected end of constant"))
2444 if (isPackedStruct) {
2445 ID.ConstantStructElts = new Constant*[Elts.size()];
2446 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2447 ID.UIntVal = Elts.size();
2448 ID.Kind = ValID::t_PackedConstantStruct;
2453 return Error(ID.Loc, "constant vector must not be empty");
2455 if (!Elts[0]->getType()->isIntegerTy() &&
2456 !Elts[0]->getType()->isFloatingPointTy() &&
2457 !Elts[0]->getType()->isPointerTy())
2458 return Error(FirstEltLoc,
2459 "vector elements must have integer, pointer or floating point type");
2461 // Verify that all the vector elements have the same type.
2462 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2463 if (Elts[i]->getType() != Elts[0]->getType())
2464 return Error(FirstEltLoc,
2465 "vector element #" + Twine(i) +
2466 " is not of type '" + getTypeString(Elts[0]->getType()));
2468 ID.ConstantVal = ConstantVector::get(Elts);
2469 ID.Kind = ValID::t_Constant;
2472 case lltok::lsquare: { // Array Constant
2474 SmallVector<Constant*, 16> Elts;
2475 LocTy FirstEltLoc = Lex.getLoc();
2476 if (ParseGlobalValueVector(Elts) ||
2477 ParseToken(lltok::rsquare, "expected end of array constant"))
2480 // Handle empty element.
2482 // Use undef instead of an array because it's inconvenient to determine
2483 // the element type at this point, there being no elements to examine.
2484 ID.Kind = ValID::t_EmptyArray;
2488 if (!Elts[0]->getType()->isFirstClassType())
2489 return Error(FirstEltLoc, "invalid array element type: " +
2490 getTypeString(Elts[0]->getType()));
2492 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2494 // Verify all elements are correct type!
2495 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2496 if (Elts[i]->getType() != Elts[0]->getType())
2497 return Error(FirstEltLoc,
2498 "array element #" + Twine(i) +
2499 " is not of type '" + getTypeString(Elts[0]->getType()));
2502 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2503 ID.Kind = ValID::t_Constant;
2506 case lltok::kw_c: // c "foo"
2508 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2510 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2511 ID.Kind = ValID::t_Constant;
2514 case lltok::kw_asm: {
2515 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2517 bool HasSideEffect, AlignStack, AsmDialect;
2519 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2520 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2521 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2522 ParseStringConstant(ID.StrVal) ||
2523 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2524 ParseToken(lltok::StringConstant, "expected constraint string"))
2526 ID.StrVal2 = Lex.getStrVal();
2527 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2528 (unsigned(AsmDialect)<<2);
2529 ID.Kind = ValID::t_InlineAsm;
2533 case lltok::kw_blockaddress: {
2534 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2539 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2541 ParseToken(lltok::comma, "expected comma in block address expression")||
2542 ParseValID(Label) ||
2543 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2546 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2547 return Error(Fn.Loc, "expected function name in blockaddress");
2548 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2549 return Error(Label.Loc, "expected basic block name in blockaddress");
2551 // Try to find the function (but skip it if it's forward-referenced).
2552 GlobalValue *GV = nullptr;
2553 if (Fn.Kind == ValID::t_GlobalID) {
2554 if (Fn.UIntVal < NumberedVals.size())
2555 GV = NumberedVals[Fn.UIntVal];
2556 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2557 GV = M->getNamedValue(Fn.StrVal);
2559 Function *F = nullptr;
2561 // Confirm that it's actually a function with a definition.
2562 if (!isa<Function>(GV))
2563 return Error(Fn.Loc, "expected function name in blockaddress");
2564 F = cast<Function>(GV);
2565 if (F->isDeclaration())
2566 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2570 // Make a global variable as a placeholder for this reference.
2571 GlobalValue *&FwdRef =
2572 ForwardRefBlockAddresses.insert(std::make_pair(
2574 std::map<ValID, GlobalValue *>()))
2575 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2578 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2579 GlobalValue::InternalLinkage, nullptr, "");
2580 ID.ConstantVal = FwdRef;
2581 ID.Kind = ValID::t_Constant;
2585 // We found the function; now find the basic block. Don't use PFS, since we
2586 // might be inside a constant expression.
2588 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2589 if (Label.Kind == ValID::t_LocalID)
2590 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2592 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2594 return Error(Label.Loc, "referenced value is not a basic block");
2596 if (Label.Kind == ValID::t_LocalID)
2597 return Error(Label.Loc, "cannot take address of numeric label after "
2598 "the function is defined");
2599 BB = dyn_cast_or_null<BasicBlock>(
2600 F->getValueSymbolTable().lookup(Label.StrVal));
2602 return Error(Label.Loc, "referenced value is not a basic block");
2605 ID.ConstantVal = BlockAddress::get(F, BB);
2606 ID.Kind = ValID::t_Constant;
2610 case lltok::kw_trunc:
2611 case lltok::kw_zext:
2612 case lltok::kw_sext:
2613 case lltok::kw_fptrunc:
2614 case lltok::kw_fpext:
2615 case lltok::kw_bitcast:
2616 case lltok::kw_addrspacecast:
2617 case lltok::kw_uitofp:
2618 case lltok::kw_sitofp:
2619 case lltok::kw_fptoui:
2620 case lltok::kw_fptosi:
2621 case lltok::kw_inttoptr:
2622 case lltok::kw_ptrtoint: {
2623 unsigned Opc = Lex.getUIntVal();
2624 Type *DestTy = nullptr;
2627 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2628 ParseGlobalTypeAndValue(SrcVal) ||
2629 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2630 ParseType(DestTy) ||
2631 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2633 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2634 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2635 getTypeString(SrcVal->getType()) + "' to '" +
2636 getTypeString(DestTy) + "'");
2637 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2639 ID.Kind = ValID::t_Constant;
2642 case lltok::kw_extractvalue: {
2645 SmallVector<unsigned, 4> Indices;
2646 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2647 ParseGlobalTypeAndValue(Val) ||
2648 ParseIndexList(Indices) ||
2649 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2652 if (!Val->getType()->isAggregateType())
2653 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2654 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2655 return Error(ID.Loc, "invalid indices for extractvalue");
2656 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2657 ID.Kind = ValID::t_Constant;
2660 case lltok::kw_insertvalue: {
2662 Constant *Val0, *Val1;
2663 SmallVector<unsigned, 4> Indices;
2664 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2665 ParseGlobalTypeAndValue(Val0) ||
2666 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2667 ParseGlobalTypeAndValue(Val1) ||
2668 ParseIndexList(Indices) ||
2669 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2671 if (!Val0->getType()->isAggregateType())
2672 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2674 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2676 return Error(ID.Loc, "invalid indices for insertvalue");
2677 if (IndexedType != Val1->getType())
2678 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2679 getTypeString(Val1->getType()) +
2680 "' instead of '" + getTypeString(IndexedType) +
2682 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2683 ID.Kind = ValID::t_Constant;
2686 case lltok::kw_icmp:
2687 case lltok::kw_fcmp: {
2688 unsigned PredVal, Opc = Lex.getUIntVal();
2689 Constant *Val0, *Val1;
2691 if (ParseCmpPredicate(PredVal, Opc) ||
2692 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2693 ParseGlobalTypeAndValue(Val0) ||
2694 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2695 ParseGlobalTypeAndValue(Val1) ||
2696 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2699 if (Val0->getType() != Val1->getType())
2700 return Error(ID.Loc, "compare operands must have the same type");
2702 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2704 if (Opc == Instruction::FCmp) {
2705 if (!Val0->getType()->isFPOrFPVectorTy())
2706 return Error(ID.Loc, "fcmp requires floating point operands");
2707 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2709 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2710 if (!Val0->getType()->isIntOrIntVectorTy() &&
2711 !Val0->getType()->getScalarType()->isPointerTy())
2712 return Error(ID.Loc, "icmp requires pointer or integer operands");
2713 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2715 ID.Kind = ValID::t_Constant;
2719 // Binary Operators.
2721 case lltok::kw_fadd:
2723 case lltok::kw_fsub:
2725 case lltok::kw_fmul:
2726 case lltok::kw_udiv:
2727 case lltok::kw_sdiv:
2728 case lltok::kw_fdiv:
2729 case lltok::kw_urem:
2730 case lltok::kw_srem:
2731 case lltok::kw_frem:
2733 case lltok::kw_lshr:
2734 case lltok::kw_ashr: {
2738 unsigned Opc = Lex.getUIntVal();
2739 Constant *Val0, *Val1;
2741 LocTy ModifierLoc = Lex.getLoc();
2742 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2743 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2744 if (EatIfPresent(lltok::kw_nuw))
2746 if (EatIfPresent(lltok::kw_nsw)) {
2748 if (EatIfPresent(lltok::kw_nuw))
2751 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2752 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2753 if (EatIfPresent(lltok::kw_exact))
2756 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2757 ParseGlobalTypeAndValue(Val0) ||
2758 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2759 ParseGlobalTypeAndValue(Val1) ||
2760 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2762 if (Val0->getType() != Val1->getType())
2763 return Error(ID.Loc, "operands of constexpr must have same type");
2764 if (!Val0->getType()->isIntOrIntVectorTy()) {
2766 return Error(ModifierLoc, "nuw only applies to integer operations");
2768 return Error(ModifierLoc, "nsw only applies to integer operations");
2770 // Check that the type is valid for the operator.
2772 case Instruction::Add:
2773 case Instruction::Sub:
2774 case Instruction::Mul:
2775 case Instruction::UDiv:
2776 case Instruction::SDiv:
2777 case Instruction::URem:
2778 case Instruction::SRem:
2779 case Instruction::Shl:
2780 case Instruction::AShr:
2781 case Instruction::LShr:
2782 if (!Val0->getType()->isIntOrIntVectorTy())
2783 return Error(ID.Loc, "constexpr requires integer operands");
2785 case Instruction::FAdd:
2786 case Instruction::FSub:
2787 case Instruction::FMul:
2788 case Instruction::FDiv:
2789 case Instruction::FRem:
2790 if (!Val0->getType()->isFPOrFPVectorTy())
2791 return Error(ID.Loc, "constexpr requires fp operands");
2793 default: llvm_unreachable("Unknown binary operator!");
2796 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2797 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2798 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2799 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2801 ID.Kind = ValID::t_Constant;
2805 // Logical Operations
2808 case lltok::kw_xor: {
2809 unsigned Opc = Lex.getUIntVal();
2810 Constant *Val0, *Val1;
2812 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2813 ParseGlobalTypeAndValue(Val0) ||
2814 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2815 ParseGlobalTypeAndValue(Val1) ||
2816 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2818 if (Val0->getType() != Val1->getType())
2819 return Error(ID.Loc, "operands of constexpr must have same type");
2820 if (!Val0->getType()->isIntOrIntVectorTy())
2821 return Error(ID.Loc,
2822 "constexpr requires integer or integer vector operands");
2823 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2824 ID.Kind = ValID::t_Constant;
2828 case lltok::kw_getelementptr:
2829 case lltok::kw_shufflevector:
2830 case lltok::kw_insertelement:
2831 case lltok::kw_extractelement:
2832 case lltok::kw_select: {
2833 unsigned Opc = Lex.getUIntVal();
2834 SmallVector<Constant*, 16> Elts;
2835 bool InBounds = false;
2839 if (Opc == Instruction::GetElementPtr)
2840 InBounds = EatIfPresent(lltok::kw_inbounds);
2842 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2845 LocTy ExplicitTypeLoc = Lex.getLoc();
2846 if (Opc == Instruction::GetElementPtr) {
2847 if (ParseType(Ty) ||
2848 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2852 if (ParseGlobalValueVector(Elts) ||
2853 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2856 if (Opc == Instruction::GetElementPtr) {
2857 if (Elts.size() == 0 ||
2858 !Elts[0]->getType()->getScalarType()->isPointerTy())
2859 return Error(ID.Loc, "base of getelementptr must be a pointer");
2861 Type *BaseType = Elts[0]->getType();
2862 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2863 if (Ty != BasePointerType->getElementType())
2866 "explicit pointee type doesn't match operand's pointee type");
2868 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2869 for (Constant *Val : Indices) {
2870 Type *ValTy = Val->getType();
2871 if (!ValTy->getScalarType()->isIntegerTy())
2872 return Error(ID.Loc, "getelementptr index must be an integer");
2873 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2874 return Error(ID.Loc, "getelementptr index type missmatch");
2875 if (ValTy->isVectorTy()) {
2876 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2877 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2878 if (ValNumEl != PtrNumEl)
2881 "getelementptr vector index has a wrong number of elements");
2885 SmallPtrSet<const Type*, 4> Visited;
2886 if (!Indices.empty() && !Ty->isSized(&Visited))
2887 return Error(ID.Loc, "base element of getelementptr must be sized");
2889 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2890 return Error(ID.Loc, "invalid getelementptr indices");
2892 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2893 } else if (Opc == Instruction::Select) {
2894 if (Elts.size() != 3)
2895 return Error(ID.Loc, "expected three operands to select");
2896 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2898 return Error(ID.Loc, Reason);
2899 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2900 } else if (Opc == Instruction::ShuffleVector) {
2901 if (Elts.size() != 3)
2902 return Error(ID.Loc, "expected three operands to shufflevector");
2903 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2904 return Error(ID.Loc, "invalid operands to shufflevector");
2906 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2907 } else if (Opc == Instruction::ExtractElement) {
2908 if (Elts.size() != 2)
2909 return Error(ID.Loc, "expected two operands to extractelement");
2910 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2911 return Error(ID.Loc, "invalid extractelement operands");
2912 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2914 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2915 if (Elts.size() != 3)
2916 return Error(ID.Loc, "expected three operands to insertelement");
2917 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2918 return Error(ID.Loc, "invalid insertelement operands");
2920 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2923 ID.Kind = ValID::t_Constant;
2932 /// ParseGlobalValue - Parse a global value with the specified type.
2933 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2937 bool Parsed = ParseValID(ID) ||
2938 ConvertValIDToValue(Ty, ID, V, nullptr);
2939 if (V && !(C = dyn_cast<Constant>(V)))
2940 return Error(ID.Loc, "global values must be constants");
2944 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2946 return ParseType(Ty) ||
2947 ParseGlobalValue(Ty, V);
2950 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2953 LocTy KwLoc = Lex.getLoc();
2954 if (!EatIfPresent(lltok::kw_comdat))
2957 if (EatIfPresent(lltok::lparen)) {
2958 if (Lex.getKind() != lltok::ComdatVar)
2959 return TokError("expected comdat variable");
2960 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2962 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2965 if (GlobalName.empty())
2966 return TokError("comdat cannot be unnamed");
2967 C = getComdat(GlobalName, KwLoc);
2973 /// ParseGlobalValueVector
2975 /// ::= TypeAndValue (',' TypeAndValue)*
2976 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2978 if (Lex.getKind() == lltok::rbrace ||
2979 Lex.getKind() == lltok::rsquare ||
2980 Lex.getKind() == lltok::greater ||
2981 Lex.getKind() == lltok::rparen)
2985 if (ParseGlobalTypeAndValue(C)) return true;
2988 while (EatIfPresent(lltok::comma)) {
2989 if (ParseGlobalTypeAndValue(C)) return true;
2996 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2997 SmallVector<Metadata *, 16> Elts;
2998 if (ParseMDNodeVector(Elts))
3001 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3008 /// ::= !DILocation(...)
3009 bool LLParser::ParseMDNode(MDNode *&N) {
3010 if (Lex.getKind() == lltok::MetadataVar)
3011 return ParseSpecializedMDNode(N);
3013 return ParseToken(lltok::exclaim, "expected '!' here") ||
3017 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3019 if (Lex.getKind() == lltok::lbrace)
3020 return ParseMDTuple(N);
3023 return ParseMDNodeID(N);
3028 /// Structure to represent an optional metadata field.
3029 template <class FieldTy> struct MDFieldImpl {
3030 typedef MDFieldImpl ImplTy;
3034 void assign(FieldTy Val) {
3036 this->Val = std::move(Val);
3039 explicit MDFieldImpl(FieldTy Default)
3040 : Val(std::move(Default)), Seen(false) {}
3043 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3046 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3047 : ImplTy(Default), Max(Max) {}
3049 struct LineField : public MDUnsignedField {
3050 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3052 struct ColumnField : public MDUnsignedField {
3053 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3055 struct DwarfTagField : public MDUnsignedField {
3056 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3057 DwarfTagField(dwarf::Tag DefaultTag)
3058 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3060 struct DwarfAttEncodingField : public MDUnsignedField {
3061 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3063 struct DwarfVirtualityField : public MDUnsignedField {
3064 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3066 struct DwarfLangField : public MDUnsignedField {
3067 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3070 struct DIFlagField : public MDUnsignedField {
3071 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3074 struct MDSignedField : public MDFieldImpl<int64_t> {
3078 MDSignedField(int64_t Default = 0)
3079 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3080 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3081 : ImplTy(Default), Min(Min), Max(Max) {}
3084 struct MDBoolField : public MDFieldImpl<bool> {
3085 MDBoolField(bool Default = false) : ImplTy(Default) {}
3087 struct MDField : public MDFieldImpl<Metadata *> {
3090 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3092 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3093 MDConstant() : ImplTy(nullptr) {}
3095 struct MDStringField : public MDFieldImpl<MDString *> {
3097 MDStringField(bool AllowEmpty = true)
3098 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3100 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3101 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3109 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3110 MDUnsignedField &Result) {
3111 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3112 return TokError("expected unsigned integer");
3114 auto &U = Lex.getAPSIntVal();
3115 if (U.ugt(Result.Max))
3116 return TokError("value for '" + Name + "' too large, limit is " +
3118 Result.assign(U.getZExtValue());
3119 assert(Result.Val <= Result.Max && "Expected value in range");
3125 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3126 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3129 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3130 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3134 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3135 if (Lex.getKind() == lltok::APSInt)
3136 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3138 if (Lex.getKind() != lltok::DwarfTag)
3139 return TokError("expected DWARF tag");
3141 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3142 if (Tag == dwarf::DW_TAG_invalid)
3143 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3144 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3152 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3153 DwarfVirtualityField &Result) {
3154 if (Lex.getKind() == lltok::APSInt)
3155 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3157 if (Lex.getKind() != lltok::DwarfVirtuality)
3158 return TokError("expected DWARF virtuality code");
3160 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3162 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3163 Lex.getStrVal() + "'");
3164 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3165 Result.assign(Virtuality);
3171 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3172 if (Lex.getKind() == lltok::APSInt)
3173 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3175 if (Lex.getKind() != lltok::DwarfLang)
3176 return TokError("expected DWARF language");
3178 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3180 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3182 assert(Lang <= Result.Max && "Expected valid DWARF language");
3183 Result.assign(Lang);
3189 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3190 DwarfAttEncodingField &Result) {
3191 if (Lex.getKind() == lltok::APSInt)
3192 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3194 if (Lex.getKind() != lltok::DwarfAttEncoding)
3195 return TokError("expected DWARF type attribute encoding");
3197 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3199 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3200 Lex.getStrVal() + "'");
3201 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3202 Result.assign(Encoding);
3209 /// ::= DIFlagVector
3210 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3212 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3213 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3215 // Parser for a single flag.
3216 auto parseFlag = [&](unsigned &Val) {
3217 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3218 return ParseUInt32(Val);
3220 if (Lex.getKind() != lltok::DIFlag)
3221 return TokError("expected debug info flag");
3223 Val = DINode::getFlag(Lex.getStrVal());
3225 return TokError(Twine("invalid debug info flag flag '") +
3226 Lex.getStrVal() + "'");
3231 // Parse the flags and combine them together.
3232 unsigned Combined = 0;
3238 } while (EatIfPresent(lltok::bar));
3240 Result.assign(Combined);
3245 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3246 MDSignedField &Result) {
3247 if (Lex.getKind() != lltok::APSInt)
3248 return TokError("expected signed integer");
3250 auto &S = Lex.getAPSIntVal();
3252 return TokError("value for '" + Name + "' too small, limit is " +
3255 return TokError("value for '" + Name + "' too large, limit is " +
3257 Result.assign(S.getExtValue());
3258 assert(Result.Val >= Result.Min && "Expected value in range");
3259 assert(Result.Val <= Result.Max && "Expected value in range");
3265 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3266 switch (Lex.getKind()) {
3268 return TokError("expected 'true' or 'false'");
3269 case lltok::kw_true:
3270 Result.assign(true);
3272 case lltok::kw_false:
3273 Result.assign(false);
3281 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3282 if (Lex.getKind() == lltok::kw_null) {
3283 if (!Result.AllowNull)
3284 return TokError("'" + Name + "' cannot be null");
3286 Result.assign(nullptr);
3291 if (ParseMetadata(MD, nullptr))
3299 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3301 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3304 Result.assign(cast<ConstantAsMetadata>(MD));
3309 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3310 LocTy ValueLoc = Lex.getLoc();
3312 if (ParseStringConstant(S))
3315 if (!Result.AllowEmpty && S.empty())
3316 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3318 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3323 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3324 SmallVector<Metadata *, 4> MDs;
3325 if (ParseMDNodeVector(MDs))
3328 Result.assign(std::move(MDs));
3332 } // end namespace llvm
3334 template <class ParserTy>
3335 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3337 if (Lex.getKind() != lltok::LabelStr)
3338 return TokError("expected field label here");
3342 } while (EatIfPresent(lltok::comma));
3347 template <class ParserTy>
3348 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3349 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3352 if (ParseToken(lltok::lparen, "expected '(' here"))
3354 if (Lex.getKind() != lltok::rparen)
3355 if (ParseMDFieldsImplBody(parseField))
3358 ClosingLoc = Lex.getLoc();
3359 return ParseToken(lltok::rparen, "expected ')' here");
3362 template <class FieldTy>
3363 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3365 return TokError("field '" + Name + "' cannot be specified more than once");
3367 LocTy Loc = Lex.getLoc();
3369 return ParseMDField(Loc, Name, Result);
3372 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3373 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3375 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3376 if (Lex.getStrVal() == #CLASS) \
3377 return Parse##CLASS(N, IsDistinct);
3378 #include "llvm/IR/Metadata.def"
3380 return TokError("expected metadata type");
3383 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3384 #define NOP_FIELD(NAME, TYPE, INIT)
3385 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3387 return Error(ClosingLoc, "missing required field '" #NAME "'");
3388 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3389 if (Lex.getStrVal() == #NAME) \
3390 return ParseMDField(#NAME, NAME);
3391 #define PARSE_MD_FIELDS() \
3392 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3395 if (ParseMDFieldsImpl([&]() -> bool { \
3396 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3397 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3400 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3402 #define GET_OR_DISTINCT(CLASS, ARGS) \
3403 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3405 /// ParseDILocationFields:
3406 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3407 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3408 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3409 OPTIONAL(line, LineField, ); \
3410 OPTIONAL(column, ColumnField, ); \
3411 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3412 OPTIONAL(inlinedAt, MDField, );
3414 #undef VISIT_MD_FIELDS
3416 Result = GET_OR_DISTINCT(
3417 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3421 /// ParseGenericDINode:
3422 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3423 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3424 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3425 REQUIRED(tag, DwarfTagField, ); \
3426 OPTIONAL(header, MDStringField, ); \
3427 OPTIONAL(operands, MDFieldList, );
3429 #undef VISIT_MD_FIELDS
3431 Result = GET_OR_DISTINCT(GenericDINode,
3432 (Context, tag.Val, header.Val, operands.Val));
3436 /// ParseDISubrange:
3437 /// ::= !DISubrange(count: 30, lowerBound: 2)
3438 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3439 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3440 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3441 OPTIONAL(lowerBound, MDSignedField, );
3443 #undef VISIT_MD_FIELDS
3445 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3449 /// ParseDIEnumerator:
3450 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3451 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3452 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3453 REQUIRED(name, MDStringField, ); \
3454 REQUIRED(value, MDSignedField, );
3456 #undef VISIT_MD_FIELDS
3458 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3462 /// ParseDIBasicType:
3463 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3464 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3465 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3466 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3467 OPTIONAL(name, MDStringField, ); \
3468 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3469 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3470 OPTIONAL(encoding, DwarfAttEncodingField, );
3472 #undef VISIT_MD_FIELDS
3474 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3475 align.Val, encoding.Val));
3479 /// ParseDIDerivedType:
3480 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3481 /// line: 7, scope: !1, baseType: !2, size: 32,
3482 /// align: 32, offset: 0, flags: 0, extraData: !3)
3483 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3484 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3485 REQUIRED(tag, DwarfTagField, ); \
3486 OPTIONAL(name, MDStringField, ); \
3487 OPTIONAL(file, MDField, ); \
3488 OPTIONAL(line, LineField, ); \
3489 OPTIONAL(scope, MDField, ); \
3490 REQUIRED(baseType, MDField, ); \
3491 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3492 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3493 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3494 OPTIONAL(flags, DIFlagField, ); \
3495 OPTIONAL(extraData, MDField, );
3497 #undef VISIT_MD_FIELDS
3499 Result = GET_OR_DISTINCT(DIDerivedType,
3500 (Context, tag.Val, name.Val, file.Val, line.Val,
3501 scope.Val, baseType.Val, size.Val, align.Val,
3502 offset.Val, flags.Val, extraData.Val));
3506 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3507 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3508 REQUIRED(tag, DwarfTagField, ); \
3509 OPTIONAL(name, MDStringField, ); \
3510 OPTIONAL(file, MDField, ); \
3511 OPTIONAL(line, LineField, ); \
3512 OPTIONAL(scope, MDField, ); \
3513 OPTIONAL(baseType, MDField, ); \
3514 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3515 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3516 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3517 OPTIONAL(flags, DIFlagField, ); \
3518 OPTIONAL(elements, MDField, ); \
3519 OPTIONAL(runtimeLang, DwarfLangField, ); \
3520 OPTIONAL(vtableHolder, MDField, ); \
3521 OPTIONAL(templateParams, MDField, ); \
3522 OPTIONAL(identifier, MDStringField, );
3524 #undef VISIT_MD_FIELDS
3526 Result = GET_OR_DISTINCT(
3528 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3529 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3530 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3534 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3535 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3536 OPTIONAL(flags, DIFlagField, ); \
3537 REQUIRED(types, MDField, );
3539 #undef VISIT_MD_FIELDS
3541 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3545 /// ParseDIFileType:
3546 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3547 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3548 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3549 REQUIRED(filename, MDStringField, ); \
3550 REQUIRED(directory, MDStringField, );
3552 #undef VISIT_MD_FIELDS
3554 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3558 /// ParseDICompileUnit:
3559 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3560 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3561 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3562 /// enums: !1, retainedTypes: !2, subprograms: !3,
3563 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3564 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3565 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3566 REQUIRED(language, DwarfLangField, ); \
3567 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3568 OPTIONAL(producer, MDStringField, ); \
3569 OPTIONAL(isOptimized, MDBoolField, ); \
3570 OPTIONAL(flags, MDStringField, ); \
3571 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3572 OPTIONAL(splitDebugFilename, MDStringField, ); \
3573 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3574 OPTIONAL(enums, MDField, ); \
3575 OPTIONAL(retainedTypes, MDField, ); \
3576 OPTIONAL(subprograms, MDField, ); \
3577 OPTIONAL(globals, MDField, ); \
3578 OPTIONAL(imports, MDField, ); \
3579 OPTIONAL(dwoId, MDUnsignedField, );
3581 #undef VISIT_MD_FIELDS
3583 Result = GET_OR_DISTINCT(DICompileUnit,
3584 (Context, language.Val, file.Val, producer.Val,
3585 isOptimized.Val, flags.Val, runtimeVersion.Val,
3586 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3587 retainedTypes.Val, subprograms.Val, globals.Val,
3588 imports.Val, dwoId.Val));
3592 /// ParseDISubprogram:
3593 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3594 /// file: !1, line: 7, type: !2, isLocal: false,
3595 /// isDefinition: true, scopeLine: 8, containingType: !3,
3596 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3597 /// virtualIndex: 10, flags: 11,
3598 /// isOptimized: false, function: void ()* @_Z3foov,
3599 /// templateParams: !4, declaration: !5, variables: !6)
3600 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3601 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3602 OPTIONAL(scope, MDField, ); \
3603 OPTIONAL(name, MDStringField, ); \
3604 OPTIONAL(linkageName, MDStringField, ); \
3605 OPTIONAL(file, MDField, ); \
3606 OPTIONAL(line, LineField, ); \
3607 OPTIONAL(type, MDField, ); \
3608 OPTIONAL(isLocal, MDBoolField, ); \
3609 OPTIONAL(isDefinition, MDBoolField, (true)); \
3610 OPTIONAL(scopeLine, LineField, ); \
3611 OPTIONAL(containingType, MDField, ); \
3612 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3613 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3614 OPTIONAL(flags, DIFlagField, ); \
3615 OPTIONAL(isOptimized, MDBoolField, ); \
3616 OPTIONAL(function, MDConstant, ); \
3617 OPTIONAL(templateParams, MDField, ); \
3618 OPTIONAL(declaration, MDField, ); \
3619 OPTIONAL(variables, MDField, );
3621 #undef VISIT_MD_FIELDS
3623 Result = GET_OR_DISTINCT(
3624 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3625 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3626 scopeLine.Val, containingType.Val, virtuality.Val,
3627 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3628 templateParams.Val, declaration.Val, variables.Val));
3632 /// ParseDILexicalBlock:
3633 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3634 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3635 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3636 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3637 OPTIONAL(file, MDField, ); \
3638 OPTIONAL(line, LineField, ); \
3639 OPTIONAL(column, ColumnField, );
3641 #undef VISIT_MD_FIELDS
3643 Result = GET_OR_DISTINCT(
3644 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3648 /// ParseDILexicalBlockFile:
3649 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3650 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3651 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3652 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3653 OPTIONAL(file, MDField, ); \
3654 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3656 #undef VISIT_MD_FIELDS
3658 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3659 (Context, scope.Val, file.Val, discriminator.Val));
3663 /// ParseDINamespace:
3664 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3665 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3666 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3667 REQUIRED(scope, MDField, ); \
3668 OPTIONAL(file, MDField, ); \
3669 OPTIONAL(name, MDStringField, ); \
3670 OPTIONAL(line, LineField, );
3672 #undef VISIT_MD_FIELDS
3674 Result = GET_OR_DISTINCT(DINamespace,
3675 (Context, scope.Val, file.Val, name.Val, line.Val));
3680 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3681 /// includePath: "/usr/include", isysroot: "/")
3682 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3683 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3684 REQUIRED(scope, MDField, ); \
3685 REQUIRED(name, MDStringField, ); \
3686 OPTIONAL(configMacros, MDStringField, ); \
3687 OPTIONAL(includePath, MDStringField, ); \
3688 OPTIONAL(isysroot, MDStringField, );
3690 #undef VISIT_MD_FIELDS
3692 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3693 configMacros.Val, includePath.Val, isysroot.Val));
3697 /// ParseDITemplateTypeParameter:
3698 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3699 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3700 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3701 OPTIONAL(name, MDStringField, ); \
3702 REQUIRED(type, MDField, );
3704 #undef VISIT_MD_FIELDS
3707 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3711 /// ParseDITemplateValueParameter:
3712 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3713 /// name: "V", type: !1, value: i32 7)
3714 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3715 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3716 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3717 OPTIONAL(name, MDStringField, ); \
3718 OPTIONAL(type, MDField, ); \
3719 REQUIRED(value, MDField, );
3721 #undef VISIT_MD_FIELDS
3723 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3724 (Context, tag.Val, name.Val, type.Val, value.Val));
3728 /// ParseDIGlobalVariable:
3729 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3730 /// file: !1, line: 7, type: !2, isLocal: false,
3731 /// isDefinition: true, variable: i32* @foo,
3732 /// declaration: !3)
3733 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3734 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3735 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3736 OPTIONAL(scope, MDField, ); \
3737 OPTIONAL(linkageName, MDStringField, ); \
3738 OPTIONAL(file, MDField, ); \
3739 OPTIONAL(line, LineField, ); \
3740 OPTIONAL(type, MDField, ); \
3741 OPTIONAL(isLocal, MDBoolField, ); \
3742 OPTIONAL(isDefinition, MDBoolField, (true)); \
3743 OPTIONAL(variable, MDConstant, ); \
3744 OPTIONAL(declaration, MDField, );
3746 #undef VISIT_MD_FIELDS
3748 Result = GET_OR_DISTINCT(DIGlobalVariable,
3749 (Context, scope.Val, name.Val, linkageName.Val,
3750 file.Val, line.Val, type.Val, isLocal.Val,
3751 isDefinition.Val, variable.Val, declaration.Val));
3755 /// ParseDILocalVariable:
3756 /// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3757 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3758 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3759 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3760 REQUIRED(tag, DwarfTagField, ); \
3761 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3762 OPTIONAL(name, MDStringField, ); \
3763 OPTIONAL(file, MDField, ); \
3764 OPTIONAL(line, LineField, ); \
3765 OPTIONAL(type, MDField, ); \
3766 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3767 OPTIONAL(flags, DIFlagField, );
3769 #undef VISIT_MD_FIELDS
3771 Result = GET_OR_DISTINCT(DILocalVariable,
3772 (Context, tag.Val, scope.Val, name.Val, file.Val,
3773 line.Val, type.Val, arg.Val, flags.Val));
3777 /// ParseDIExpression:
3778 /// ::= !DIExpression(0, 7, -1)
3779 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3780 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3783 if (ParseToken(lltok::lparen, "expected '(' here"))
3786 SmallVector<uint64_t, 8> Elements;
3787 if (Lex.getKind() != lltok::rparen)
3789 if (Lex.getKind() == lltok::DwarfOp) {
3790 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3792 Elements.push_back(Op);
3795 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3798 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3799 return TokError("expected unsigned integer");
3801 auto &U = Lex.getAPSIntVal();
3802 if (U.ugt(UINT64_MAX))
3803 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3804 Elements.push_back(U.getZExtValue());
3806 } while (EatIfPresent(lltok::comma));
3808 if (ParseToken(lltok::rparen, "expected ')' here"))
3811 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3815 /// ParseDIObjCProperty:
3816 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3817 /// getter: "getFoo", attributes: 7, type: !2)
3818 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3819 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3820 OPTIONAL(name, MDStringField, ); \
3821 OPTIONAL(file, MDField, ); \
3822 OPTIONAL(line, LineField, ); \
3823 OPTIONAL(setter, MDStringField, ); \
3824 OPTIONAL(getter, MDStringField, ); \
3825 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3826 OPTIONAL(type, MDField, );
3828 #undef VISIT_MD_FIELDS
3830 Result = GET_OR_DISTINCT(DIObjCProperty,
3831 (Context, name.Val, file.Val, line.Val, setter.Val,
3832 getter.Val, attributes.Val, type.Val));
3836 /// ParseDIImportedEntity:
3837 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3838 /// line: 7, name: "foo")
3839 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3840 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3841 REQUIRED(tag, DwarfTagField, ); \
3842 REQUIRED(scope, MDField, ); \
3843 OPTIONAL(entity, MDField, ); \
3844 OPTIONAL(line, LineField, ); \
3845 OPTIONAL(name, MDStringField, );
3847 #undef VISIT_MD_FIELDS
3849 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3850 entity.Val, line.Val, name.Val));
3854 #undef PARSE_MD_FIELD
3856 #undef REQUIRE_FIELD
3857 #undef DECLARE_FIELD
3859 /// ParseMetadataAsValue
3860 /// ::= metadata i32 %local
3861 /// ::= metadata i32 @global
3862 /// ::= metadata i32 7
3864 /// ::= metadata !{...}
3865 /// ::= metadata !"string"
3866 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3867 // Note: the type 'metadata' has already been parsed.
3869 if (ParseMetadata(MD, &PFS))
3872 V = MetadataAsValue::get(Context, MD);
3876 /// ParseValueAsMetadata
3880 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3881 PerFunctionState *PFS) {
3884 if (ParseType(Ty, TypeMsg, Loc))
3886 if (Ty->isMetadataTy())
3887 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3890 if (ParseValue(Ty, V, PFS))
3893 MD = ValueAsMetadata::get(V);
3904 /// ::= !DILocation(...)
3905 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3906 if (Lex.getKind() == lltok::MetadataVar) {
3908 if (ParseSpecializedMDNode(N))
3916 if (Lex.getKind() != lltok::exclaim)
3917 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3920 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3924 // ::= '!' STRINGCONSTANT
3925 if (Lex.getKind() == lltok::StringConstant) {
3927 if (ParseMDString(S))
3937 if (ParseMDNodeTail(N))
3944 //===----------------------------------------------------------------------===//
3945 // Function Parsing.
3946 //===----------------------------------------------------------------------===//
3948 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3949 PerFunctionState *PFS) {
3950 if (Ty->isFunctionTy())
3951 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3954 case ValID::t_LocalID:
3955 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3956 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3957 return V == nullptr;
3958 case ValID::t_LocalName:
3959 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3960 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3961 return V == nullptr;
3962 case ValID::t_InlineAsm: {
3963 PointerType *PTy = dyn_cast<PointerType>(Ty);
3965 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3966 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3967 return Error(ID.Loc, "invalid type for inline asm constraint string");
3968 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3969 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3972 case ValID::t_GlobalName:
3973 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3974 return V == nullptr;
3975 case ValID::t_GlobalID:
3976 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3977 return V == nullptr;
3978 case ValID::t_APSInt:
3979 if (!Ty->isIntegerTy())
3980 return Error(ID.Loc, "integer constant must have integer type");
3981 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3982 V = ConstantInt::get(Context, ID.APSIntVal);
3984 case ValID::t_APFloat:
3985 if (!Ty->isFloatingPointTy() ||
3986 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3987 return Error(ID.Loc, "floating point constant invalid for type");
3989 // The lexer has no type info, so builds all half, float, and double FP
3990 // constants as double. Fix this here. Long double does not need this.
3991 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3994 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3996 else if (Ty->isFloatTy())
3997 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4000 V = ConstantFP::get(Context, ID.APFloatVal);
4002 if (V->getType() != Ty)
4003 return Error(ID.Loc, "floating point constant does not have type '" +
4004 getTypeString(Ty) + "'");
4008 if (!Ty->isPointerTy())
4009 return Error(ID.Loc, "null must be a pointer type");
4010 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4012 case ValID::t_Undef:
4013 // FIXME: LabelTy should not be a first-class type.
4014 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4015 return Error(ID.Loc, "invalid type for undef constant");
4016 V = UndefValue::get(Ty);
4018 case ValID::t_EmptyArray:
4019 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4020 return Error(ID.Loc, "invalid empty array initializer");
4021 V = UndefValue::get(Ty);
4024 // FIXME: LabelTy should not be a first-class type.
4025 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4026 return Error(ID.Loc, "invalid type for null constant");
4027 V = Constant::getNullValue(Ty);
4029 case ValID::t_Constant:
4030 if (ID.ConstantVal->getType() != Ty)
4031 return Error(ID.Loc, "constant expression type mismatch");
4035 case ValID::t_ConstantStruct:
4036 case ValID::t_PackedConstantStruct:
4037 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4038 if (ST->getNumElements() != ID.UIntVal)
4039 return Error(ID.Loc,
4040 "initializer with struct type has wrong # elements");
4041 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4042 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4044 // Verify that the elements are compatible with the structtype.
4045 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4046 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4047 return Error(ID.Loc, "element " + Twine(i) +
4048 " of struct initializer doesn't match struct element type");
4050 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4053 return Error(ID.Loc, "constant expression type mismatch");
4056 llvm_unreachable("Invalid ValID");
4059 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4062 return ParseValID(ID, PFS) ||
4063 ConvertValIDToValue(Ty, ID, V, PFS);
4066 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4068 return ParseType(Ty) ||
4069 ParseValue(Ty, V, PFS);
4072 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4073 PerFunctionState &PFS) {
4076 if (ParseTypeAndValue(V, PFS)) return true;
4077 if (!isa<BasicBlock>(V))
4078 return Error(Loc, "expected a basic block");
4079 BB = cast<BasicBlock>(V);
4085 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4086 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4087 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4088 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4089 // Parse the linkage.
4090 LocTy LinkageLoc = Lex.getLoc();
4093 unsigned Visibility;
4094 unsigned DLLStorageClass;
4095 AttrBuilder RetAttrs;
4097 Type *RetType = nullptr;
4098 LocTy RetTypeLoc = Lex.getLoc();
4099 if (ParseOptionalLinkage(Linkage) ||
4100 ParseOptionalVisibility(Visibility) ||
4101 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4102 ParseOptionalCallingConv(CC) ||
4103 ParseOptionalReturnAttrs(RetAttrs) ||
4104 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4107 // Verify that the linkage is ok.
4108 switch ((GlobalValue::LinkageTypes)Linkage) {
4109 case GlobalValue::ExternalLinkage:
4110 break; // always ok.
4111 case GlobalValue::ExternalWeakLinkage:
4113 return Error(LinkageLoc, "invalid linkage for function definition");
4115 case GlobalValue::PrivateLinkage:
4116 case GlobalValue::InternalLinkage:
4117 case GlobalValue::AvailableExternallyLinkage:
4118 case GlobalValue::LinkOnceAnyLinkage:
4119 case GlobalValue::LinkOnceODRLinkage:
4120 case GlobalValue::WeakAnyLinkage:
4121 case GlobalValue::WeakODRLinkage:
4123 return Error(LinkageLoc, "invalid linkage for function declaration");
4125 case GlobalValue::AppendingLinkage:
4126 case GlobalValue::CommonLinkage:
4127 return Error(LinkageLoc, "invalid function linkage type");
4130 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4131 return Error(LinkageLoc,
4132 "symbol with local linkage must have default visibility");
4134 if (!FunctionType::isValidReturnType(RetType))
4135 return Error(RetTypeLoc, "invalid function return type");
4137 LocTy NameLoc = Lex.getLoc();
4139 std::string FunctionName;
4140 if (Lex.getKind() == lltok::GlobalVar) {
4141 FunctionName = Lex.getStrVal();
4142 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4143 unsigned NameID = Lex.getUIntVal();
4145 if (NameID != NumberedVals.size())
4146 return TokError("function expected to be numbered '%" +
4147 Twine(NumberedVals.size()) + "'");
4149 return TokError("expected function name");
4154 if (Lex.getKind() != lltok::lparen)
4155 return TokError("expected '(' in function argument list");
4157 SmallVector<ArgInfo, 8> ArgList;
4159 AttrBuilder FuncAttrs;
4160 std::vector<unsigned> FwdRefAttrGrps;
4162 std::string Section;
4166 LocTy UnnamedAddrLoc;
4167 Constant *Prefix = nullptr;
4168 Constant *Prologue = nullptr;
4169 Constant *PersonalityFn = nullptr;
4172 if (ParseArgumentList(ArgList, isVarArg) ||
4173 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4175 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4177 (EatIfPresent(lltok::kw_section) &&
4178 ParseStringConstant(Section)) ||
4179 parseOptionalComdat(FunctionName, C) ||
4180 ParseOptionalAlignment(Alignment) ||
4181 (EatIfPresent(lltok::kw_gc) &&
4182 ParseStringConstant(GC)) ||
4183 (EatIfPresent(lltok::kw_prefix) &&
4184 ParseGlobalTypeAndValue(Prefix)) ||
4185 (EatIfPresent(lltok::kw_prologue) &&
4186 ParseGlobalTypeAndValue(Prologue)) ||
4187 (EatIfPresent(lltok::kw_personality) &&
4188 ParseGlobalTypeAndValue(PersonalityFn)))
4191 if (FuncAttrs.contains(Attribute::Builtin))
4192 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4194 // If the alignment was parsed as an attribute, move to the alignment field.
4195 if (FuncAttrs.hasAlignmentAttr()) {
4196 Alignment = FuncAttrs.getAlignment();
4197 FuncAttrs.removeAttribute(Attribute::Alignment);
4200 // Okay, if we got here, the function is syntactically valid. Convert types
4201 // and do semantic checks.
4202 std::vector<Type*> ParamTypeList;
4203 SmallVector<AttributeSet, 8> Attrs;
4205 if (RetAttrs.hasAttributes())
4206 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4207 AttributeSet::ReturnIndex,
4210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4211 ParamTypeList.push_back(ArgList[i].Ty);
4212 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4213 AttrBuilder B(ArgList[i].Attrs, i + 1);
4214 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4218 if (FuncAttrs.hasAttributes())
4219 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4220 AttributeSet::FunctionIndex,
4223 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4225 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4226 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4229 FunctionType::get(RetType, ParamTypeList, isVarArg);
4230 PointerType *PFT = PointerType::getUnqual(FT);
4233 if (!FunctionName.empty()) {
4234 // If this was a definition of a forward reference, remove the definition
4235 // from the forward reference table and fill in the forward ref.
4236 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4237 ForwardRefVals.find(FunctionName);
4238 if (FRVI != ForwardRefVals.end()) {
4239 Fn = M->getFunction(FunctionName);
4241 return Error(FRVI->second.second, "invalid forward reference to "
4242 "function as global value!");
4243 if (Fn->getType() != PFT)
4244 return Error(FRVI->second.second, "invalid forward reference to "
4245 "function '" + FunctionName + "' with wrong type!");
4247 ForwardRefVals.erase(FRVI);
4248 } else if ((Fn = M->getFunction(FunctionName))) {
4249 // Reject redefinitions.
4250 return Error(NameLoc, "invalid redefinition of function '" +
4251 FunctionName + "'");
4252 } else if (M->getNamedValue(FunctionName)) {
4253 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4257 // If this is a definition of a forward referenced function, make sure the
4259 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4260 = ForwardRefValIDs.find(NumberedVals.size());
4261 if (I != ForwardRefValIDs.end()) {
4262 Fn = cast<Function>(I->second.first);
4263 if (Fn->getType() != PFT)
4264 return Error(NameLoc, "type of definition and forward reference of '@" +
4265 Twine(NumberedVals.size()) + "' disagree");
4266 ForwardRefValIDs.erase(I);
4271 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4272 else // Move the forward-reference to the correct spot in the module.
4273 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4275 if (FunctionName.empty())
4276 NumberedVals.push_back(Fn);
4278 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4279 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4280 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4281 Fn->setCallingConv(CC);
4282 Fn->setAttributes(PAL);
4283 Fn->setUnnamedAddr(UnnamedAddr);
4284 Fn->setAlignment(Alignment);
4285 Fn->setSection(Section);
4287 Fn->setPersonalityFn(PersonalityFn);
4288 if (!GC.empty()) Fn->setGC(GC.c_str());
4289 Fn->setPrefixData(Prefix);
4290 Fn->setPrologueData(Prologue);
4291 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4293 // Add all of the arguments we parsed to the function.
4294 Function::arg_iterator ArgIt = Fn->arg_begin();
4295 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4296 // If the argument has a name, insert it into the argument symbol table.
4297 if (ArgList[i].Name.empty()) continue;
4299 // Set the name, if it conflicted, it will be auto-renamed.
4300 ArgIt->setName(ArgList[i].Name);
4302 if (ArgIt->getName() != ArgList[i].Name)
4303 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4304 ArgList[i].Name + "'");
4310 // Check the declaration has no block address forward references.
4312 if (FunctionName.empty()) {
4313 ID.Kind = ValID::t_GlobalID;
4314 ID.UIntVal = NumberedVals.size() - 1;
4316 ID.Kind = ValID::t_GlobalName;
4317 ID.StrVal = FunctionName;
4319 auto Blocks = ForwardRefBlockAddresses.find(ID);
4320 if (Blocks != ForwardRefBlockAddresses.end())
4321 return Error(Blocks->first.Loc,
4322 "cannot take blockaddress inside a declaration");
4326 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4328 if (FunctionNumber == -1) {
4329 ID.Kind = ValID::t_GlobalName;
4330 ID.StrVal = F.getName();
4332 ID.Kind = ValID::t_GlobalID;
4333 ID.UIntVal = FunctionNumber;
4336 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4337 if (Blocks == P.ForwardRefBlockAddresses.end())
4340 for (const auto &I : Blocks->second) {
4341 const ValID &BBID = I.first;
4342 GlobalValue *GV = I.second;
4344 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4345 "Expected local id or name");
4347 if (BBID.Kind == ValID::t_LocalName)
4348 BB = GetBB(BBID.StrVal, BBID.Loc);
4350 BB = GetBB(BBID.UIntVal, BBID.Loc);
4352 return P.Error(BBID.Loc, "referenced value is not a basic block");
4354 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4355 GV->eraseFromParent();
4358 P.ForwardRefBlockAddresses.erase(Blocks);
4362 /// ParseFunctionBody
4363 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4364 bool LLParser::ParseFunctionBody(Function &Fn) {
4365 if (Lex.getKind() != lltok::lbrace)
4366 return TokError("expected '{' in function body");
4367 Lex.Lex(); // eat the {.
4369 int FunctionNumber = -1;
4370 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4372 PerFunctionState PFS(*this, Fn, FunctionNumber);
4374 // Resolve block addresses and allow basic blocks to be forward-declared
4375 // within this function.
4376 if (PFS.resolveForwardRefBlockAddresses())
4378 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4380 // We need at least one basic block.
4381 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4382 return TokError("function body requires at least one basic block");
4384 while (Lex.getKind() != lltok::rbrace &&
4385 Lex.getKind() != lltok::kw_uselistorder)
4386 if (ParseBasicBlock(PFS)) return true;
4388 while (Lex.getKind() != lltok::rbrace)
4389 if (ParseUseListOrder(&PFS))
4395 // Verify function is ok.
4396 return PFS.FinishFunction();
4400 /// ::= LabelStr? Instruction*
4401 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4402 // If this basic block starts out with a name, remember it.
4404 LocTy NameLoc = Lex.getLoc();
4405 if (Lex.getKind() == lltok::LabelStr) {
4406 Name = Lex.getStrVal();
4410 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4412 return Error(NameLoc,
4413 "unable to create block named '" + Name + "'");
4415 std::string NameStr;
4417 // Parse the instructions in this block until we get a terminator.
4420 // This instruction may have three possibilities for a name: a) none
4421 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4422 LocTy NameLoc = Lex.getLoc();
4426 if (Lex.getKind() == lltok::LocalVarID) {
4427 NameID = Lex.getUIntVal();
4429 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4431 } else if (Lex.getKind() == lltok::LocalVar) {
4432 NameStr = Lex.getStrVal();
4434 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4438 switch (ParseInstruction(Inst, BB, PFS)) {
4439 default: llvm_unreachable("Unknown ParseInstruction result!");
4440 case InstError: return true;
4442 BB->getInstList().push_back(Inst);
4444 // With a normal result, we check to see if the instruction is followed by
4445 // a comma and metadata.
4446 if (EatIfPresent(lltok::comma))
4447 if (ParseInstructionMetadata(*Inst))
4450 case InstExtraComma:
4451 BB->getInstList().push_back(Inst);
4453 // If the instruction parser ate an extra comma at the end of it, it
4454 // *must* be followed by metadata.
4455 if (ParseInstructionMetadata(*Inst))
4460 // Set the name on the instruction.
4461 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4462 } while (!isa<TerminatorInst>(Inst));
4467 //===----------------------------------------------------------------------===//
4468 // Instruction Parsing.
4469 //===----------------------------------------------------------------------===//
4471 /// ParseInstruction - Parse one of the many different instructions.
4473 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4474 PerFunctionState &PFS) {
4475 lltok::Kind Token = Lex.getKind();
4476 if (Token == lltok::Eof)
4477 return TokError("found end of file when expecting more instructions");
4478 LocTy Loc = Lex.getLoc();
4479 unsigned KeywordVal = Lex.getUIntVal();
4480 Lex.Lex(); // Eat the keyword.
4483 default: return Error(Loc, "expected instruction opcode");
4484 // Terminator Instructions.
4485 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4486 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4487 case lltok::kw_br: return ParseBr(Inst, PFS);
4488 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4489 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4490 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4491 case lltok::kw_resume: return ParseResume(Inst, PFS);
4492 // Binary Operators.
4496 case lltok::kw_shl: {
4497 bool NUW = EatIfPresent(lltok::kw_nuw);
4498 bool NSW = EatIfPresent(lltok::kw_nsw);
4499 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4501 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4503 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4504 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4507 case lltok::kw_fadd:
4508 case lltok::kw_fsub:
4509 case lltok::kw_fmul:
4510 case lltok::kw_fdiv:
4511 case lltok::kw_frem: {
4512 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4513 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4517 Inst->setFastMathFlags(FMF);
4521 case lltok::kw_sdiv:
4522 case lltok::kw_udiv:
4523 case lltok::kw_lshr:
4524 case lltok::kw_ashr: {
4525 bool Exact = EatIfPresent(lltok::kw_exact);
4527 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4528 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4532 case lltok::kw_urem:
4533 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4536 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4537 case lltok::kw_icmp:
4538 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
4540 case lltok::kw_trunc:
4541 case lltok::kw_zext:
4542 case lltok::kw_sext:
4543 case lltok::kw_fptrunc:
4544 case lltok::kw_fpext:
4545 case lltok::kw_bitcast:
4546 case lltok::kw_addrspacecast:
4547 case lltok::kw_uitofp:
4548 case lltok::kw_sitofp:
4549 case lltok::kw_fptoui:
4550 case lltok::kw_fptosi:
4551 case lltok::kw_inttoptr:
4552 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4554 case lltok::kw_select: return ParseSelect(Inst, PFS);
4555 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4556 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4557 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4558 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4559 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4560 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4562 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4563 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4564 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4566 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4567 case lltok::kw_load: return ParseLoad(Inst, PFS);
4568 case lltok::kw_store: return ParseStore(Inst, PFS);
4569 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4570 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4571 case lltok::kw_fence: return ParseFence(Inst, PFS);
4572 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4573 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4574 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4578 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4579 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4580 if (Opc == Instruction::FCmp) {
4581 switch (Lex.getKind()) {
4582 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4583 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4584 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4585 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4586 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4587 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4588 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4589 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4590 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4591 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4592 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4593 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4594 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4595 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4596 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4597 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4598 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4601 switch (Lex.getKind()) {
4602 default: return TokError("expected icmp predicate (e.g. 'eq')");
4603 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4604 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4605 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4606 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4607 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4608 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4609 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4610 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4611 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4612 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4619 //===----------------------------------------------------------------------===//
4620 // Terminator Instructions.
4621 //===----------------------------------------------------------------------===//
4623 /// ParseRet - Parse a return instruction.
4624 /// ::= 'ret' void (',' !dbg, !1)*
4625 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4626 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4627 PerFunctionState &PFS) {
4628 SMLoc TypeLoc = Lex.getLoc();
4630 if (ParseType(Ty, true /*void allowed*/)) return true;
4632 Type *ResType = PFS.getFunction().getReturnType();
4634 if (Ty->isVoidTy()) {
4635 if (!ResType->isVoidTy())
4636 return Error(TypeLoc, "value doesn't match function result type '" +
4637 getTypeString(ResType) + "'");
4639 Inst = ReturnInst::Create(Context);
4644 if (ParseValue(Ty, RV, PFS)) return true;
4646 if (ResType != RV->getType())
4647 return Error(TypeLoc, "value doesn't match function result type '" +
4648 getTypeString(ResType) + "'");
4650 Inst = ReturnInst::Create(Context, RV);
4656 /// ::= 'br' TypeAndValue
4657 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4658 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4661 BasicBlock *Op1, *Op2;
4662 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4664 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4665 Inst = BranchInst::Create(BB);
4669 if (Op0->getType() != Type::getInt1Ty(Context))
4670 return Error(Loc, "branch condition must have 'i1' type");
4672 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4673 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4674 ParseToken(lltok::comma, "expected ',' after true destination") ||
4675 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4678 Inst = BranchInst::Create(Op1, Op2, Op0);
4684 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4686 /// ::= (TypeAndValue ',' TypeAndValue)*
4687 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4688 LocTy CondLoc, BBLoc;
4690 BasicBlock *DefaultBB;
4691 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4692 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4693 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4694 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4697 if (!Cond->getType()->isIntegerTy())
4698 return Error(CondLoc, "switch condition must have integer type");
4700 // Parse the jump table pairs.
4701 SmallPtrSet<Value*, 32> SeenCases;
4702 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4703 while (Lex.getKind() != lltok::rsquare) {
4707 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4708 ParseToken(lltok::comma, "expected ',' after case value") ||
4709 ParseTypeAndBasicBlock(DestBB, PFS))
4712 if (!SeenCases.insert(Constant).second)
4713 return Error(CondLoc, "duplicate case value in switch");
4714 if (!isa<ConstantInt>(Constant))
4715 return Error(CondLoc, "case value is not a constant integer");
4717 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4720 Lex.Lex(); // Eat the ']'.
4722 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4723 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4724 SI->addCase(Table[i].first, Table[i].second);
4731 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4732 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4735 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4736 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4737 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4740 if (!Address->getType()->isPointerTy())
4741 return Error(AddrLoc, "indirectbr address must have pointer type");
4743 // Parse the destination list.
4744 SmallVector<BasicBlock*, 16> DestList;
4746 if (Lex.getKind() != lltok::rsquare) {
4748 if (ParseTypeAndBasicBlock(DestBB, PFS))
4750 DestList.push_back(DestBB);
4752 while (EatIfPresent(lltok::comma)) {
4753 if (ParseTypeAndBasicBlock(DestBB, PFS))
4755 DestList.push_back(DestBB);
4759 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4762 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4763 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4764 IBI->addDestination(DestList[i]);
4771 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4772 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4773 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4774 LocTy CallLoc = Lex.getLoc();
4775 AttrBuilder RetAttrs, FnAttrs;
4776 std::vector<unsigned> FwdRefAttrGrps;
4779 Type *RetType = nullptr;
4782 SmallVector<ParamInfo, 16> ArgList;
4784 BasicBlock *NormalBB, *UnwindBB;
4785 if (ParseOptionalCallingConv(CC) ||
4786 ParseOptionalReturnAttrs(RetAttrs) ||
4787 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4788 ParseValID(CalleeID) ||
4789 ParseParameterList(ArgList, PFS) ||
4790 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4792 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4793 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4794 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4795 ParseTypeAndBasicBlock(UnwindBB, PFS))
4798 // If RetType is a non-function pointer type, then this is the short syntax
4799 // for the call, which means that RetType is just the return type. Infer the
4800 // rest of the function argument types from the arguments that are present.
4801 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4803 // Pull out the types of all of the arguments...
4804 std::vector<Type*> ParamTypes;
4805 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4806 ParamTypes.push_back(ArgList[i].V->getType());
4808 if (!FunctionType::isValidReturnType(RetType))
4809 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4811 Ty = FunctionType::get(RetType, ParamTypes, false);
4814 // Look up the callee.
4816 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4819 // Set up the Attribute for the function.
4820 SmallVector<AttributeSet, 8> Attrs;
4821 if (RetAttrs.hasAttributes())
4822 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4823 AttributeSet::ReturnIndex,
4826 SmallVector<Value*, 8> Args;
4828 // Loop through FunctionType's arguments and ensure they are specified
4829 // correctly. Also, gather any parameter attributes.
4830 FunctionType::param_iterator I = Ty->param_begin();
4831 FunctionType::param_iterator E = Ty->param_end();
4832 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4833 Type *ExpectedTy = nullptr;
4836 } else if (!Ty->isVarArg()) {
4837 return Error(ArgList[i].Loc, "too many arguments specified");
4840 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4841 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4842 getTypeString(ExpectedTy) + "'");
4843 Args.push_back(ArgList[i].V);
4844 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4845 AttrBuilder B(ArgList[i].Attrs, i + 1);
4846 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4851 return Error(CallLoc, "not enough parameters specified for call");
4853 if (FnAttrs.hasAttributes()) {
4854 if (FnAttrs.hasAlignmentAttr())
4855 return Error(CallLoc, "invoke instructions may not have an alignment");
4857 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4858 AttributeSet::FunctionIndex,
4862 // Finish off the Attribute and check them
4863 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4865 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4866 II->setCallingConv(CC);
4867 II->setAttributes(PAL);
4868 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4874 /// ::= 'resume' TypeAndValue
4875 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4876 Value *Exn; LocTy ExnLoc;
4877 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4880 ResumeInst *RI = ResumeInst::Create(Exn);
4885 //===----------------------------------------------------------------------===//
4886 // Binary Operators.
4887 //===----------------------------------------------------------------------===//
4890 /// ::= ArithmeticOps TypeAndValue ',' Value
4892 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4893 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4894 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4895 unsigned Opc, unsigned OperandType) {
4896 LocTy Loc; Value *LHS, *RHS;
4897 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4898 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4899 ParseValue(LHS->getType(), RHS, PFS))
4903 switch (OperandType) {
4904 default: llvm_unreachable("Unknown operand type!");
4905 case 0: // int or FP.
4906 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4907 LHS->getType()->isFPOrFPVectorTy();
4909 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4910 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4914 return Error(Loc, "invalid operand type for instruction");
4916 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4921 /// ::= ArithmeticOps TypeAndValue ',' Value {
4922 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4924 LocTy Loc; Value *LHS, *RHS;
4925 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4926 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4927 ParseValue(LHS->getType(), RHS, PFS))
4930 if (!LHS->getType()->isIntOrIntVectorTy())
4931 return Error(Loc,"instruction requires integer or integer vector operands");
4933 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4939 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4940 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4941 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4943 // Parse the integer/fp comparison predicate.
4947 if (ParseCmpPredicate(Pred, Opc) ||
4948 ParseTypeAndValue(LHS, Loc, PFS) ||
4949 ParseToken(lltok::comma, "expected ',' after compare value") ||
4950 ParseValue(LHS->getType(), RHS, PFS))
4953 if (Opc == Instruction::FCmp) {
4954 if (!LHS->getType()->isFPOrFPVectorTy())
4955 return Error(Loc, "fcmp requires floating point operands");
4956 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4958 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4959 if (!LHS->getType()->isIntOrIntVectorTy() &&
4960 !LHS->getType()->getScalarType()->isPointerTy())
4961 return Error(Loc, "icmp requires integer operands");
4962 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4967 //===----------------------------------------------------------------------===//
4968 // Other Instructions.
4969 //===----------------------------------------------------------------------===//
4973 /// ::= CastOpc TypeAndValue 'to' Type
4974 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4978 Type *DestTy = nullptr;
4979 if (ParseTypeAndValue(Op, Loc, PFS) ||
4980 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4984 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4985 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4986 return Error(Loc, "invalid cast opcode for cast from '" +
4987 getTypeString(Op->getType()) + "' to '" +
4988 getTypeString(DestTy) + "'");
4990 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4995 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4996 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4998 Value *Op0, *Op1, *Op2;
4999 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5000 ParseToken(lltok::comma, "expected ',' after select condition") ||
5001 ParseTypeAndValue(Op1, PFS) ||
5002 ParseToken(lltok::comma, "expected ',' after select value") ||
5003 ParseTypeAndValue(Op2, PFS))
5006 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5007 return Error(Loc, Reason);
5009 Inst = SelectInst::Create(Op0, Op1, Op2);
5014 /// ::= 'va_arg' TypeAndValue ',' Type
5015 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5017 Type *EltTy = nullptr;
5019 if (ParseTypeAndValue(Op, PFS) ||
5020 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5021 ParseType(EltTy, TypeLoc))
5024 if (!EltTy->isFirstClassType())
5025 return Error(TypeLoc, "va_arg requires operand with first class type");
5027 Inst = new VAArgInst(Op, EltTy);
5031 /// ParseExtractElement
5032 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5033 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5036 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5037 ParseToken(lltok::comma, "expected ',' after extract value") ||
5038 ParseTypeAndValue(Op1, PFS))
5041 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5042 return Error(Loc, "invalid extractelement operands");
5044 Inst = ExtractElementInst::Create(Op0, Op1);
5048 /// ParseInsertElement
5049 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5050 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5052 Value *Op0, *Op1, *Op2;
5053 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5054 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5055 ParseTypeAndValue(Op1, PFS) ||
5056 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5057 ParseTypeAndValue(Op2, PFS))
5060 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5061 return Error(Loc, "invalid insertelement operands");
5063 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5067 /// ParseShuffleVector
5068 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5069 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5071 Value *Op0, *Op1, *Op2;
5072 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5073 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5074 ParseTypeAndValue(Op1, PFS) ||
5075 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5076 ParseTypeAndValue(Op2, PFS))
5079 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5080 return Error(Loc, "invalid shufflevector operands");
5082 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5087 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5088 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5089 Type *Ty = nullptr; LocTy TypeLoc;
5092 if (ParseType(Ty, TypeLoc) ||
5093 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5094 ParseValue(Ty, Op0, PFS) ||
5095 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5096 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5097 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5100 bool AteExtraComma = false;
5101 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5103 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5105 if (!EatIfPresent(lltok::comma))
5108 if (Lex.getKind() == lltok::MetadataVar) {
5109 AteExtraComma = true;
5113 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5114 ParseValue(Ty, Op0, PFS) ||
5115 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5116 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5117 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5121 if (!Ty->isFirstClassType())
5122 return Error(TypeLoc, "phi node must have first class type");
5124 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5125 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5126 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5128 return AteExtraComma ? InstExtraComma : InstNormal;
5132 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5134 /// ::= 'catch' TypeAndValue
5136 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5137 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5138 Type *Ty = nullptr; LocTy TyLoc;
5140 if (ParseType(Ty, TyLoc))
5143 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5144 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5146 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5147 LandingPadInst::ClauseType CT;
5148 if (EatIfPresent(lltok::kw_catch))
5149 CT = LandingPadInst::Catch;
5150 else if (EatIfPresent(lltok::kw_filter))
5151 CT = LandingPadInst::Filter;
5153 return TokError("expected 'catch' or 'filter' clause type");
5157 if (ParseTypeAndValue(V, VLoc, PFS))
5160 // A 'catch' type expects a non-array constant. A filter clause expects an
5162 if (CT == LandingPadInst::Catch) {
5163 if (isa<ArrayType>(V->getType()))
5164 Error(VLoc, "'catch' clause has an invalid type");
5166 if (!isa<ArrayType>(V->getType()))
5167 Error(VLoc, "'filter' clause has an invalid type");
5170 Constant *CV = dyn_cast<Constant>(V);
5172 return Error(VLoc, "clause argument must be a constant");
5176 Inst = LP.release();
5181 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5182 /// ParameterList OptionalAttrs
5183 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5184 /// ParameterList OptionalAttrs
5185 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5186 /// ParameterList OptionalAttrs
5187 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5188 CallInst::TailCallKind TCK) {
5189 AttrBuilder RetAttrs, FnAttrs;
5190 std::vector<unsigned> FwdRefAttrGrps;
5193 Type *RetType = nullptr;
5196 SmallVector<ParamInfo, 16> ArgList;
5197 LocTy CallLoc = Lex.getLoc();
5199 if ((TCK != CallInst::TCK_None &&
5200 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5201 ParseOptionalCallingConv(CC) ||
5202 ParseOptionalReturnAttrs(RetAttrs) ||
5203 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5204 ParseValID(CalleeID) ||
5205 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5206 PFS.getFunction().isVarArg()) ||
5207 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5211 // If RetType is a non-function pointer type, then this is the short syntax
5212 // for the call, which means that RetType is just the return type. Infer the
5213 // rest of the function argument types from the arguments that are present.
5214 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5216 // Pull out the types of all of the arguments...
5217 std::vector<Type*> ParamTypes;
5218 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5219 ParamTypes.push_back(ArgList[i].V->getType());
5221 if (!FunctionType::isValidReturnType(RetType))
5222 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5224 Ty = FunctionType::get(RetType, ParamTypes, false);
5227 // Look up the callee.
5229 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5232 // Set up the Attribute for the function.
5233 SmallVector<AttributeSet, 8> Attrs;
5234 if (RetAttrs.hasAttributes())
5235 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5236 AttributeSet::ReturnIndex,
5239 SmallVector<Value*, 8> Args;
5241 // Loop through FunctionType's arguments and ensure they are specified
5242 // correctly. Also, gather any parameter attributes.
5243 FunctionType::param_iterator I = Ty->param_begin();
5244 FunctionType::param_iterator E = Ty->param_end();
5245 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5246 Type *ExpectedTy = nullptr;
5249 } else if (!Ty->isVarArg()) {
5250 return Error(ArgList[i].Loc, "too many arguments specified");
5253 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5254 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5255 getTypeString(ExpectedTy) + "'");
5256 Args.push_back(ArgList[i].V);
5257 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5258 AttrBuilder B(ArgList[i].Attrs, i + 1);
5259 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5264 return Error(CallLoc, "not enough parameters specified for call");
5266 if (FnAttrs.hasAttributes()) {
5267 if (FnAttrs.hasAlignmentAttr())
5268 return Error(CallLoc, "call instructions may not have an alignment");
5270 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5271 AttributeSet::FunctionIndex,
5275 // Finish off the Attribute and check them
5276 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5278 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5279 CI->setTailCallKind(TCK);
5280 CI->setCallingConv(CC);
5281 CI->setAttributes(PAL);
5282 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5287 //===----------------------------------------------------------------------===//
5288 // Memory Instructions.
5289 //===----------------------------------------------------------------------===//
5292 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5293 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5294 Value *Size = nullptr;
5295 LocTy SizeLoc, TyLoc;
5296 unsigned Alignment = 0;
5299 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5301 if (ParseType(Ty, TyLoc)) return true;
5303 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5304 return Error(TyLoc, "invalid type for alloca");
5306 bool AteExtraComma = false;
5307 if (EatIfPresent(lltok::comma)) {
5308 if (Lex.getKind() == lltok::kw_align) {
5309 if (ParseOptionalAlignment(Alignment)) return true;
5310 } else if (Lex.getKind() == lltok::MetadataVar) {
5311 AteExtraComma = true;
5313 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5314 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5319 if (Size && !Size->getType()->isIntegerTy())
5320 return Error(SizeLoc, "element count must have integer type");
5322 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5323 AI->setUsedWithInAlloca(IsInAlloca);
5325 return AteExtraComma ? InstExtraComma : InstNormal;
5329 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5330 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5331 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5332 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5333 Value *Val; LocTy Loc;
5334 unsigned Alignment = 0;
5335 bool AteExtraComma = false;
5336 bool isAtomic = false;
5337 AtomicOrdering Ordering = NotAtomic;
5338 SynchronizationScope Scope = CrossThread;
5340 if (Lex.getKind() == lltok::kw_atomic) {
5345 bool isVolatile = false;
5346 if (Lex.getKind() == lltok::kw_volatile) {
5352 LocTy ExplicitTypeLoc = Lex.getLoc();
5353 if (ParseType(Ty) ||
5354 ParseToken(lltok::comma, "expected comma after load's type") ||
5355 ParseTypeAndValue(Val, Loc, PFS) ||
5356 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5357 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5360 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5361 return Error(Loc, "load operand must be a pointer to a first class type");
5362 if (isAtomic && !Alignment)
5363 return Error(Loc, "atomic load must have explicit non-zero alignment");
5364 if (Ordering == Release || Ordering == AcquireRelease)
5365 return Error(Loc, "atomic load cannot use Release ordering");
5367 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5368 return Error(ExplicitTypeLoc,
5369 "explicit pointee type doesn't match operand's pointee type");
5371 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5372 return AteExtraComma ? InstExtraComma : InstNormal;
5377 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5378 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5379 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5380 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5381 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5382 unsigned Alignment = 0;
5383 bool AteExtraComma = false;
5384 bool isAtomic = false;
5385 AtomicOrdering Ordering = NotAtomic;
5386 SynchronizationScope Scope = CrossThread;
5388 if (Lex.getKind() == lltok::kw_atomic) {
5393 bool isVolatile = false;
5394 if (Lex.getKind() == lltok::kw_volatile) {
5399 if (ParseTypeAndValue(Val, Loc, PFS) ||
5400 ParseToken(lltok::comma, "expected ',' after store operand") ||
5401 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5402 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5403 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5406 if (!Ptr->getType()->isPointerTy())
5407 return Error(PtrLoc, "store operand must be a pointer");
5408 if (!Val->getType()->isFirstClassType())
5409 return Error(Loc, "store operand must be a first class value");
5410 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5411 return Error(Loc, "stored value and pointer type do not match");
5412 if (isAtomic && !Alignment)
5413 return Error(Loc, "atomic store must have explicit non-zero alignment");
5414 if (Ordering == Acquire || Ordering == AcquireRelease)
5415 return Error(Loc, "atomic store cannot use Acquire ordering");
5417 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5418 return AteExtraComma ? InstExtraComma : InstNormal;
5422 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5423 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5424 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5425 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5426 bool AteExtraComma = false;
5427 AtomicOrdering SuccessOrdering = NotAtomic;
5428 AtomicOrdering FailureOrdering = NotAtomic;
5429 SynchronizationScope Scope = CrossThread;
5430 bool isVolatile = false;
5431 bool isWeak = false;
5433 if (EatIfPresent(lltok::kw_weak))
5436 if (EatIfPresent(lltok::kw_volatile))
5439 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5440 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5441 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5442 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5443 ParseTypeAndValue(New, NewLoc, PFS) ||
5444 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5445 ParseOrdering(FailureOrdering))
5448 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5449 return TokError("cmpxchg cannot be unordered");
5450 if (SuccessOrdering < FailureOrdering)
5451 return TokError("cmpxchg must be at least as ordered on success as failure");
5452 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5453 return TokError("cmpxchg failure ordering cannot include release semantics");
5454 if (!Ptr->getType()->isPointerTy())
5455 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5456 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5457 return Error(CmpLoc, "compare value and pointer type do not match");
5458 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5459 return Error(NewLoc, "new value and pointer type do not match");
5460 if (!New->getType()->isIntegerTy())
5461 return Error(NewLoc, "cmpxchg operand must be an integer");
5462 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5463 if (Size < 8 || (Size & (Size - 1)))
5464 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5467 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5468 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5469 CXI->setVolatile(isVolatile);
5470 CXI->setWeak(isWeak);
5472 return AteExtraComma ? InstExtraComma : InstNormal;
5476 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5477 /// 'singlethread'? AtomicOrdering
5478 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5479 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5480 bool AteExtraComma = false;
5481 AtomicOrdering Ordering = NotAtomic;
5482 SynchronizationScope Scope = CrossThread;
5483 bool isVolatile = false;
5484 AtomicRMWInst::BinOp Operation;
5486 if (EatIfPresent(lltok::kw_volatile))
5489 switch (Lex.getKind()) {
5490 default: return TokError("expected binary operation in atomicrmw");
5491 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5492 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5493 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5494 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5495 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5496 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5497 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5498 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5499 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5500 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5501 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5503 Lex.Lex(); // Eat the operation.
5505 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5506 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5507 ParseTypeAndValue(Val, ValLoc, PFS) ||
5508 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5511 if (Ordering == Unordered)
5512 return TokError("atomicrmw cannot be unordered");
5513 if (!Ptr->getType()->isPointerTy())
5514 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5515 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5516 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5517 if (!Val->getType()->isIntegerTy())
5518 return Error(ValLoc, "atomicrmw operand must be an integer");
5519 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5520 if (Size < 8 || (Size & (Size - 1)))
5521 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5524 AtomicRMWInst *RMWI =
5525 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5526 RMWI->setVolatile(isVolatile);
5528 return AteExtraComma ? InstExtraComma : InstNormal;
5532 /// ::= 'fence' 'singlethread'? AtomicOrdering
5533 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5534 AtomicOrdering Ordering = NotAtomic;
5535 SynchronizationScope Scope = CrossThread;
5536 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5539 if (Ordering == Unordered)
5540 return TokError("fence cannot be unordered");
5541 if (Ordering == Monotonic)
5542 return TokError("fence cannot be monotonic");
5544 Inst = new FenceInst(Context, Ordering, Scope);
5548 /// ParseGetElementPtr
5549 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5550 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5551 Value *Ptr = nullptr;
5552 Value *Val = nullptr;
5555 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5558 LocTy ExplicitTypeLoc = Lex.getLoc();
5559 if (ParseType(Ty) ||
5560 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5561 ParseTypeAndValue(Ptr, Loc, PFS))
5564 Type *BaseType = Ptr->getType();
5565 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5566 if (!BasePointerType)
5567 return Error(Loc, "base of getelementptr must be a pointer");
5569 if (Ty != BasePointerType->getElementType())
5570 return Error(ExplicitTypeLoc,
5571 "explicit pointee type doesn't match operand's pointee type");
5573 SmallVector<Value*, 16> Indices;
5574 bool AteExtraComma = false;
5575 while (EatIfPresent(lltok::comma)) {
5576 if (Lex.getKind() == lltok::MetadataVar) {
5577 AteExtraComma = true;
5580 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5581 if (!Val->getType()->getScalarType()->isIntegerTy())
5582 return Error(EltLoc, "getelementptr index must be an integer");
5583 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5584 return Error(EltLoc, "getelementptr index type missmatch");
5585 if (Val->getType()->isVectorTy()) {
5586 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5587 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5588 if (ValNumEl != PtrNumEl)
5589 return Error(EltLoc,
5590 "getelementptr vector index has a wrong number of elements");
5592 Indices.push_back(Val);
5595 SmallPtrSet<const Type*, 4> Visited;
5596 if (!Indices.empty() && !Ty->isSized(&Visited))
5597 return Error(Loc, "base element of getelementptr must be sized");
5599 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5600 return Error(Loc, "invalid getelementptr indices");
5601 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5603 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5604 return AteExtraComma ? InstExtraComma : InstNormal;
5607 /// ParseExtractValue
5608 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5609 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5610 Value *Val; LocTy Loc;
5611 SmallVector<unsigned, 4> Indices;
5613 if (ParseTypeAndValue(Val, Loc, PFS) ||
5614 ParseIndexList(Indices, AteExtraComma))
5617 if (!Val->getType()->isAggregateType())
5618 return Error(Loc, "extractvalue operand must be aggregate type");
5620 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5621 return Error(Loc, "invalid indices for extractvalue");
5622 Inst = ExtractValueInst::Create(Val, Indices);
5623 return AteExtraComma ? InstExtraComma : InstNormal;
5626 /// ParseInsertValue
5627 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5628 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5629 Value *Val0, *Val1; LocTy Loc0, Loc1;
5630 SmallVector<unsigned, 4> Indices;
5632 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5633 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5634 ParseTypeAndValue(Val1, Loc1, PFS) ||
5635 ParseIndexList(Indices, AteExtraComma))
5638 if (!Val0->getType()->isAggregateType())
5639 return Error(Loc0, "insertvalue operand must be aggregate type");
5641 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5643 return Error(Loc0, "invalid indices for insertvalue");
5644 if (IndexedType != Val1->getType())
5645 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5646 getTypeString(Val1->getType()) + "' instead of '" +
5647 getTypeString(IndexedType) + "'");
5648 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5649 return AteExtraComma ? InstExtraComma : InstNormal;
5652 //===----------------------------------------------------------------------===//
5653 // Embedded metadata.
5654 //===----------------------------------------------------------------------===//
5656 /// ParseMDNodeVector
5657 /// ::= { Element (',' Element)* }
5659 /// ::= 'null' | TypeAndValue
5660 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5661 if (ParseToken(lltok::lbrace, "expected '{' here"))
5664 // Check for an empty list.
5665 if (EatIfPresent(lltok::rbrace))
5669 // Null is a special case since it is typeless.
5670 if (EatIfPresent(lltok::kw_null)) {
5671 Elts.push_back(nullptr);
5676 if (ParseMetadata(MD, nullptr))
5679 } while (EatIfPresent(lltok::comma));
5681 return ParseToken(lltok::rbrace, "expected end of metadata node");
5684 //===----------------------------------------------------------------------===//
5685 // Use-list order directives.
5686 //===----------------------------------------------------------------------===//
5687 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5690 return Error(Loc, "value has no uses");
5692 unsigned NumUses = 0;
5693 SmallDenseMap<const Use *, unsigned, 16> Order;
5694 for (const Use &U : V->uses()) {
5695 if (++NumUses > Indexes.size())
5697 Order[&U] = Indexes[NumUses - 1];
5700 return Error(Loc, "value only has one use");
5701 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5702 return Error(Loc, "wrong number of indexes, expected " +
5703 Twine(std::distance(V->use_begin(), V->use_end())));
5705 V->sortUseList([&](const Use &L, const Use &R) {
5706 return Order.lookup(&L) < Order.lookup(&R);
5711 /// ParseUseListOrderIndexes
5712 /// ::= '{' uint32 (',' uint32)+ '}'
5713 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5714 SMLoc Loc = Lex.getLoc();
5715 if (ParseToken(lltok::lbrace, "expected '{' here"))
5717 if (Lex.getKind() == lltok::rbrace)
5718 return Lex.Error("expected non-empty list of uselistorder indexes");
5720 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5721 // indexes should be distinct numbers in the range [0, size-1], and should
5723 unsigned Offset = 0;
5725 bool IsOrdered = true;
5726 assert(Indexes.empty() && "Expected empty order vector");
5729 if (ParseUInt32(Index))
5732 // Update consistency checks.
5733 Offset += Index - Indexes.size();
5734 Max = std::max(Max, Index);
5735 IsOrdered &= Index == Indexes.size();
5737 Indexes.push_back(Index);
5738 } while (EatIfPresent(lltok::comma));
5740 if (ParseToken(lltok::rbrace, "expected '}' here"))
5743 if (Indexes.size() < 2)
5744 return Error(Loc, "expected >= 2 uselistorder indexes");
5745 if (Offset != 0 || Max >= Indexes.size())
5746 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5748 return Error(Loc, "expected uselistorder indexes to change the order");
5753 /// ParseUseListOrder
5754 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5755 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5756 SMLoc Loc = Lex.getLoc();
5757 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5761 SmallVector<unsigned, 16> Indexes;
5762 if (ParseTypeAndValue(V, PFS) ||
5763 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5764 ParseUseListOrderIndexes(Indexes))
5767 return sortUseListOrder(V, Indexes, Loc);
5770 /// ParseUseListOrderBB
5771 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5772 bool LLParser::ParseUseListOrderBB() {
5773 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5774 SMLoc Loc = Lex.getLoc();
5778 SmallVector<unsigned, 16> Indexes;
5779 if (ParseValID(Fn) ||
5780 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5781 ParseValID(Label) ||
5782 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5783 ParseUseListOrderIndexes(Indexes))
5786 // Check the function.
5788 if (Fn.Kind == ValID::t_GlobalName)
5789 GV = M->getNamedValue(Fn.StrVal);
5790 else if (Fn.Kind == ValID::t_GlobalID)
5791 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5793 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5795 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5796 auto *F = dyn_cast<Function>(GV);
5798 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5799 if (F->isDeclaration())
5800 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5802 // Check the basic block.
5803 if (Label.Kind == ValID::t_LocalID)
5804 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5805 if (Label.Kind != ValID::t_LocalName)
5806 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5807 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5809 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5810 if (!isa<BasicBlock>(V))
5811 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5813 return sortUseListOrder(V, Indexes, Loc);