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/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/ValueSymbolTable.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/SaveAndRestore.h"
30 #include "llvm/Support/raw_ostream.h"
33 static std::string getTypeString(Type *T) {
35 raw_string_ostream Tmp(Result);
40 /// Run: module ::= toplevelentity*
41 bool LLParser::Run() {
45 return ParseTopLevelEntities() ||
46 ValidateEndOfModule();
49 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51 bool LLParser::ValidateEndOfModule() {
52 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
53 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55 // Handle any function attribute group forward references.
56 for (std::map<Value*, std::vector<unsigned> >::iterator
57 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
60 std::vector<unsigned> &Vec = I->second;
63 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65 B.merge(NumberedAttrBuilders[*VI]);
67 if (Function *Fn = dyn_cast<Function>(V)) {
68 AttributeSet AS = Fn->getAttributes();
69 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
70 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
71 AS.getFnAttributes());
75 // If the alignment was parsed as an attribute, move to the alignment
77 if (FnAttrs.hasAlignmentAttr()) {
78 Fn->setAlignment(FnAttrs.getAlignment());
79 FnAttrs.removeAttribute(Attribute::Alignment);
82 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
83 AttributeSet::get(Context,
84 AttributeSet::FunctionIndex,
86 Fn->setAttributes(AS);
87 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
88 AttributeSet AS = CI->getAttributes();
89 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
90 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
91 AS.getFnAttributes());
93 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
94 AttributeSet::get(Context,
95 AttributeSet::FunctionIndex,
97 CI->setAttributes(AS);
98 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
99 AttributeSet AS = II->getAttributes();
100 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
101 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
102 AS.getFnAttributes());
104 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
105 AttributeSet::get(Context,
106 AttributeSet::FunctionIndex,
108 II->setAttributes(AS);
110 llvm_unreachable("invalid object with forward attribute group reference");
114 // If there are entries in ForwardRefBlockAddresses at this point, the
115 // function was never defined.
116 if (!ForwardRefBlockAddresses.empty())
117 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
118 "expected function name in blockaddress");
120 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
121 if (NumberedTypes[i].second.isValid())
122 return Error(NumberedTypes[i].second,
123 "use of undefined type '%" + Twine(i) + "'");
125 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
126 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
127 if (I->second.second.isValid())
128 return Error(I->second.second,
129 "use of undefined type named '" + I->getKey() + "'");
131 if (!ForwardRefComdats.empty())
132 return Error(ForwardRefComdats.begin()->second,
133 "use of undefined comdat '$" +
134 ForwardRefComdats.begin()->first + "'");
136 if (!ForwardRefVals.empty())
137 return Error(ForwardRefVals.begin()->second.second,
138 "use of undefined value '@" + ForwardRefVals.begin()->first +
141 if (!ForwardRefValIDs.empty())
142 return Error(ForwardRefValIDs.begin()->second.second,
143 "use of undefined value '@" +
144 Twine(ForwardRefValIDs.begin()->first) + "'");
146 if (!ForwardRefMDNodes.empty())
147 return Error(ForwardRefMDNodes.begin()->second.second,
148 "use of undefined metadata '!" +
149 Twine(ForwardRefMDNodes.begin()->first) + "'");
151 // Resolve metadata cycles.
152 for (auto &N : NumberedMetadata)
153 if (N && !N->isResolved())
156 // Look for intrinsic functions and CallInst that need to be upgraded
157 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
158 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
160 UpgradeDebugInfo(*M);
165 //===----------------------------------------------------------------------===//
166 // Top-Level Entities
167 //===----------------------------------------------------------------------===//
169 bool LLParser::ParseTopLevelEntities() {
171 switch (Lex.getKind()) {
172 default: return TokError("expected top-level entity");
173 case lltok::Eof: return false;
174 case lltok::kw_declare: if (ParseDeclare()) return true; break;
175 case lltok::kw_define: if (ParseDefine()) return true; break;
176 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
177 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
178 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
179 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
180 case lltok::LocalVar: if (ParseNamedType()) return true; break;
181 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
182 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
183 case lltok::ComdatVar: if (parseComdat()) return true; break;
184 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
185 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
187 // The Global variable production with no name can have many different
188 // optional leading prefixes, the production is:
189 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
190 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
191 // ('constant'|'global') ...
192 case lltok::kw_private: // OptionalLinkage
193 case lltok::kw_internal: // OptionalLinkage
194 case lltok::kw_weak: // OptionalLinkage
195 case lltok::kw_weak_odr: // OptionalLinkage
196 case lltok::kw_linkonce: // OptionalLinkage
197 case lltok::kw_linkonce_odr: // OptionalLinkage
198 case lltok::kw_appending: // OptionalLinkage
199 case lltok::kw_common: // OptionalLinkage
200 case lltok::kw_extern_weak: // OptionalLinkage
201 case lltok::kw_external: // OptionalLinkage
202 case lltok::kw_default: // OptionalVisibility
203 case lltok::kw_hidden: // OptionalVisibility
204 case lltok::kw_protected: // OptionalVisibility
205 case lltok::kw_dllimport: // OptionalDLLStorageClass
206 case lltok::kw_dllexport: // OptionalDLLStorageClass
207 case lltok::kw_thread_local: // OptionalThreadLocal
208 case lltok::kw_addrspace: // OptionalAddrSpace
209 case lltok::kw_constant: // GlobalType
210 case lltok::kw_global: { // GlobalType
211 unsigned Linkage, Visibility, DLLStorageClass;
213 GlobalVariable::ThreadLocalMode TLM;
215 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
216 ParseOptionalVisibility(Visibility) ||
217 ParseOptionalDLLStorageClass(DLLStorageClass) ||
218 ParseOptionalThreadLocal(TLM) ||
219 parseOptionalUnnamedAddr(UnnamedAddr) ||
220 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
221 DLLStorageClass, TLM, UnnamedAddr))
226 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
227 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
228 case lltok::kw_uselistorder_bb:
229 if (ParseUseListOrderBB()) return true; break;
236 /// ::= 'module' 'asm' STRINGCONSTANT
237 bool LLParser::ParseModuleAsm() {
238 assert(Lex.getKind() == lltok::kw_module);
242 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
243 ParseStringConstant(AsmStr)) return true;
245 M->appendModuleInlineAsm(AsmStr);
250 /// ::= 'target' 'triple' '=' STRINGCONSTANT
251 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
252 bool LLParser::ParseTargetDefinition() {
253 assert(Lex.getKind() == lltok::kw_target);
256 default: return TokError("unknown target property");
257 case lltok::kw_triple:
259 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
260 ParseStringConstant(Str))
262 M->setTargetTriple(Str);
264 case lltok::kw_datalayout:
266 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
267 ParseStringConstant(Str))
269 M->setDataLayout(Str);
275 /// ::= 'deplibs' '=' '[' ']'
276 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
277 /// FIXME: Remove in 4.0. Currently parse, but ignore.
278 bool LLParser::ParseDepLibs() {
279 assert(Lex.getKind() == lltok::kw_deplibs);
281 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
282 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285 if (EatIfPresent(lltok::rsquare))
290 if (ParseStringConstant(Str)) return true;
291 } while (EatIfPresent(lltok::comma));
293 return ParseToken(lltok::rsquare, "expected ']' at end of list");
296 /// ParseUnnamedType:
297 /// ::= LocalVarID '=' 'type' type
298 bool LLParser::ParseUnnamedType() {
299 LocTy TypeLoc = Lex.getLoc();
300 unsigned TypeID = Lex.getUIntVal();
301 Lex.Lex(); // eat LocalVarID;
303 if (ParseToken(lltok::equal, "expected '=' after name") ||
304 ParseToken(lltok::kw_type, "expected 'type' after '='"))
307 if (TypeID >= NumberedTypes.size())
308 NumberedTypes.resize(TypeID+1);
310 Type *Result = nullptr;
311 if (ParseStructDefinition(TypeLoc, "",
312 NumberedTypes[TypeID], Result)) return true;
314 if (!isa<StructType>(Result)) {
315 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
317 return Error(TypeLoc, "non-struct types may not be recursive");
318 Entry.first = Result;
319 Entry.second = SMLoc();
327 /// ::= LocalVar '=' 'type' type
328 bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
331 Lex.Lex(); // eat LocalVar.
333 if (ParseToken(lltok::equal, "expected '=' after name") ||
334 ParseToken(lltok::kw_type, "expected 'type' after name"))
337 Type *Result = nullptr;
338 if (ParseStructDefinition(NameLoc, Name,
339 NamedTypes[Name], Result)) return true;
341 if (!isa<StructType>(Result)) {
342 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
344 return Error(NameLoc, "non-struct types may not be recursive");
345 Entry.first = Result;
346 Entry.second = SMLoc();
354 /// ::= 'declare' FunctionHeader
355 bool LLParser::ParseDeclare() {
356 assert(Lex.getKind() == lltok::kw_declare);
360 return ParseFunctionHeader(F, false);
364 /// ::= 'define' FunctionHeader '{' ...
365 bool LLParser::ParseDefine() {
366 assert(Lex.getKind() == lltok::kw_define);
370 return ParseFunctionHeader(F, true) ||
371 ParseFunctionBody(*F);
377 bool LLParser::ParseGlobalType(bool &IsConstant) {
378 if (Lex.getKind() == lltok::kw_constant)
380 else if (Lex.getKind() == lltok::kw_global)
384 return TokError("expected 'global' or 'constant'");
390 /// ParseUnnamedGlobal:
391 /// OptionalVisibility ALIAS ...
392 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
393 /// ... -> global variable
394 /// GlobalID '=' OptionalVisibility ALIAS ...
395 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
396 /// ... -> global variable
397 bool LLParser::ParseUnnamedGlobal() {
398 unsigned VarID = NumberedVals.size();
400 LocTy NameLoc = Lex.getLoc();
402 // Handle the GlobalID form.
403 if (Lex.getKind() == lltok::GlobalID) {
404 if (Lex.getUIntVal() != VarID)
405 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
407 Lex.Lex(); // eat GlobalID;
409 if (ParseToken(lltok::equal, "expected '=' after name"))
414 unsigned Linkage, Visibility, DLLStorageClass;
415 GlobalVariable::ThreadLocalMode TLM;
417 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
418 ParseOptionalVisibility(Visibility) ||
419 ParseOptionalDLLStorageClass(DLLStorageClass) ||
420 ParseOptionalThreadLocal(TLM) ||
421 parseOptionalUnnamedAddr(UnnamedAddr))
424 if (Lex.getKind() != lltok::kw_alias)
425 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
426 DLLStorageClass, TLM, UnnamedAddr);
427 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
431 /// ParseNamedGlobal:
432 /// GlobalVar '=' OptionalVisibility ALIAS ...
433 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434 /// ... -> global variable
435 bool LLParser::ParseNamedGlobal() {
436 assert(Lex.getKind() == lltok::GlobalVar);
437 LocTy NameLoc = Lex.getLoc();
438 std::string Name = Lex.getStrVal();
442 unsigned Linkage, Visibility, DLLStorageClass;
443 GlobalVariable::ThreadLocalMode TLM;
445 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
446 ParseOptionalLinkage(Linkage, HasLinkage) ||
447 ParseOptionalVisibility(Visibility) ||
448 ParseOptionalDLLStorageClass(DLLStorageClass) ||
449 ParseOptionalThreadLocal(TLM) ||
450 parseOptionalUnnamedAddr(UnnamedAddr))
453 if (Lex.getKind() != lltok::kw_alias)
454 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
455 DLLStorageClass, TLM, UnnamedAddr);
457 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
461 bool LLParser::parseComdat() {
462 assert(Lex.getKind() == lltok::ComdatVar);
463 std::string Name = Lex.getStrVal();
464 LocTy NameLoc = Lex.getLoc();
467 if (ParseToken(lltok::equal, "expected '=' here"))
470 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
471 return TokError("expected comdat type");
473 Comdat::SelectionKind SK;
474 switch (Lex.getKind()) {
476 return TokError("unknown selection kind");
480 case lltok::kw_exactmatch:
481 SK = Comdat::ExactMatch;
483 case lltok::kw_largest:
484 SK = Comdat::Largest;
486 case lltok::kw_noduplicates:
487 SK = Comdat::NoDuplicates;
489 case lltok::kw_samesize:
490 SK = Comdat::SameSize;
495 // See if the comdat was forward referenced, if so, use the comdat.
496 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
497 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
498 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
499 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
502 if (I != ComdatSymTab.end())
505 C = M->getOrInsertComdat(Name);
506 C->setSelectionKind(SK);
512 // ::= '!' STRINGCONSTANT
513 bool LLParser::ParseMDString(MDString *&Result) {
515 if (ParseStringConstant(Str)) return true;
516 llvm::UpgradeMDStringConstant(Str);
517 Result = MDString::get(Context, Str);
522 // ::= '!' MDNodeNumber
523 bool LLParser::ParseMDNodeID(MDNode *&Result) {
524 // !{ ..., !42, ... }
526 if (ParseUInt32(MID))
529 // If not a forward reference, just return it now.
530 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
531 Result = NumberedMetadata[MID];
535 // Otherwise, create MDNode forward reference.
536 auto &FwdRef = ForwardRefMDNodes[MID];
537 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
539 if (NumberedMetadata.size() <= MID)
540 NumberedMetadata.resize(MID+1);
541 Result = FwdRef.first.get();
542 NumberedMetadata[MID].reset(Result);
546 /// ParseNamedMetadata:
547 /// !foo = !{ !1, !2 }
548 bool LLParser::ParseNamedMetadata() {
549 assert(Lex.getKind() == lltok::MetadataVar);
550 std::string Name = Lex.getStrVal();
553 if (ParseToken(lltok::equal, "expected '=' here") ||
554 ParseToken(lltok::exclaim, "Expected '!' here") ||
555 ParseToken(lltok::lbrace, "Expected '{' here"))
558 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
559 if (Lex.getKind() != lltok::rbrace)
561 if (ParseToken(lltok::exclaim, "Expected '!' here"))
565 if (ParseMDNodeID(N)) return true;
567 } while (EatIfPresent(lltok::comma));
569 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
575 /// ParseStandaloneMetadata:
577 bool LLParser::ParseStandaloneMetadata() {
578 assert(Lex.getKind() == lltok::exclaim);
580 unsigned MetadataID = 0;
583 if (ParseUInt32(MetadataID) ||
584 ParseToken(lltok::equal, "expected '=' here"))
587 // Detect common error, from old metadata syntax.
588 if (Lex.getKind() == lltok::Type)
589 return TokError("unexpected type in metadata definition");
591 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
592 if (Lex.getKind() == lltok::MetadataVar) {
593 if (ParseSpecializedMDNode(Init, IsDistinct))
595 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
596 ParseMDTuple(Init, IsDistinct))
599 // See if this was forward referenced, if so, handle it.
600 auto FI = ForwardRefMDNodes.find(MetadataID);
601 if (FI != ForwardRefMDNodes.end()) {
602 FI->second.first->replaceAllUsesWith(Init);
603 ForwardRefMDNodes.erase(FI);
605 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
607 if (MetadataID >= NumberedMetadata.size())
608 NumberedMetadata.resize(MetadataID+1);
610 if (NumberedMetadata[MetadataID] != nullptr)
611 return TokError("Metadata id is already used");
612 NumberedMetadata[MetadataID].reset(Init);
618 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
619 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
620 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
624 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
625 /// OptionalDLLStorageClass OptionalThreadLocal
626 /// OptionalUnNammedAddr 'alias' Aliasee
631 /// Everything through OptionalUnNammedAddr has already been parsed.
633 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
634 unsigned Visibility, unsigned DLLStorageClass,
635 GlobalVariable::ThreadLocalMode TLM,
637 assert(Lex.getKind() == lltok::kw_alias);
640 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
642 if(!GlobalAlias::isValidLinkage(Linkage))
643 return Error(NameLoc, "invalid linkage type for alias");
645 if (!isValidVisibilityForLinkage(Visibility, L))
646 return Error(NameLoc,
647 "symbol with local linkage must have default visibility");
650 LocTy AliaseeLoc = Lex.getLoc();
651 if (Lex.getKind() != lltok::kw_bitcast &&
652 Lex.getKind() != lltok::kw_getelementptr &&
653 Lex.getKind() != lltok::kw_addrspacecast &&
654 Lex.getKind() != lltok::kw_inttoptr) {
655 if (ParseGlobalTypeAndValue(Aliasee))
658 // The bitcast dest type is not present, it is implied by the dest type.
662 if (ID.Kind != ValID::t_Constant)
663 return Error(AliaseeLoc, "invalid aliasee");
664 Aliasee = ID.ConstantVal;
667 Type *AliaseeType = Aliasee->getType();
668 auto *PTy = dyn_cast<PointerType>(AliaseeType);
670 return Error(AliaseeLoc, "An alias must have pointer type");
671 Type *Ty = PTy->getElementType();
672 unsigned AddrSpace = PTy->getAddressSpace();
674 // Okay, create the alias but do not insert it into the module yet.
675 std::unique_ptr<GlobalAlias> GA(
676 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
677 Name, Aliasee, /*Parent*/ nullptr));
678 GA->setThreadLocalMode(TLM);
679 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
680 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
681 GA->setUnnamedAddr(UnnamedAddr);
683 // See if this value already exists in the symbol table. If so, it is either
684 // a redefinition or a definition of a forward reference.
685 if (GlobalValue *Val = M->getNamedValue(Name)) {
686 // See if this was a redefinition. If so, there is no entry in
688 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
689 I = ForwardRefVals.find(Name);
690 if (I == ForwardRefVals.end())
691 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
693 // Otherwise, this was a definition of forward ref. Verify that types
695 if (Val->getType() != GA->getType())
696 return Error(NameLoc,
697 "forward reference and definition of alias have different types");
699 // If they agree, just RAUW the old value with the alias and remove the
701 Val->replaceAllUsesWith(GA.get());
702 Val->eraseFromParent();
703 ForwardRefVals.erase(I);
706 // Insert into the module, we know its name won't collide now.
707 M->getAliasList().push_back(GA.get());
708 assert(GA->getName() == Name && "Should not be a name conflict!");
710 // The module owns this now
717 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
718 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
719 /// OptionalExternallyInitialized GlobalType Type Const
720 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
721 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
722 /// OptionalExternallyInitialized GlobalType Type Const
724 /// Everything up to and including OptionalUnNammedAddr has been parsed
727 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
728 unsigned Linkage, bool HasLinkage,
729 unsigned Visibility, unsigned DLLStorageClass,
730 GlobalVariable::ThreadLocalMode TLM,
732 if (!isValidVisibilityForLinkage(Visibility, Linkage))
733 return Error(NameLoc,
734 "symbol with local linkage must have default visibility");
737 bool IsConstant, IsExternallyInitialized;
738 LocTy IsExternallyInitializedLoc;
742 if (ParseOptionalAddrSpace(AddrSpace) ||
743 ParseOptionalToken(lltok::kw_externally_initialized,
744 IsExternallyInitialized,
745 &IsExternallyInitializedLoc) ||
746 ParseGlobalType(IsConstant) ||
747 ParseType(Ty, TyLoc))
750 // If the linkage is specified and is external, then no initializer is
752 Constant *Init = nullptr;
753 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
754 Linkage != GlobalValue::ExternalLinkage)) {
755 if (ParseGlobalValue(Ty, Init))
759 if (Ty->isFunctionTy() || Ty->isLabelTy())
760 return Error(TyLoc, "invalid type for global variable");
762 GlobalValue *GVal = nullptr;
764 // See if the global was forward referenced, if so, use the global.
766 GVal = M->getNamedValue(Name);
768 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
769 return Error(NameLoc, "redefinition of global '@" + Name + "'");
772 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
773 I = ForwardRefValIDs.find(NumberedVals.size());
774 if (I != ForwardRefValIDs.end()) {
775 GVal = I->second.first;
776 ForwardRefValIDs.erase(I);
782 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
783 Name, nullptr, GlobalVariable::NotThreadLocal,
786 if (GVal->getType()->getElementType() != Ty)
788 "forward reference and definition of global have different types");
790 GV = cast<GlobalVariable>(GVal);
792 // Move the forward-reference to the correct spot in the module.
793 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
797 NumberedVals.push_back(GV);
799 // Set the parsed properties on the global.
801 GV->setInitializer(Init);
802 GV->setConstant(IsConstant);
803 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
804 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
805 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
806 GV->setExternallyInitialized(IsExternallyInitialized);
807 GV->setThreadLocalMode(TLM);
808 GV->setUnnamedAddr(UnnamedAddr);
810 // Parse attributes on the global.
811 while (Lex.getKind() == lltok::comma) {
814 if (Lex.getKind() == lltok::kw_section) {
816 GV->setSection(Lex.getStrVal());
817 if (ParseToken(lltok::StringConstant, "expected global section string"))
819 } else if (Lex.getKind() == lltok::kw_align) {
821 if (ParseOptionalAlignment(Alignment)) return true;
822 GV->setAlignment(Alignment);
825 if (parseOptionalComdat(Name, C))
830 return TokError("unknown global variable property!");
837 /// ParseUnnamedAttrGrp
838 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
839 bool LLParser::ParseUnnamedAttrGrp() {
840 assert(Lex.getKind() == lltok::kw_attributes);
841 LocTy AttrGrpLoc = Lex.getLoc();
844 if (Lex.getKind() != lltok::AttrGrpID)
845 return TokError("expected attribute group id");
847 unsigned VarID = Lex.getUIntVal();
848 std::vector<unsigned> unused;
852 if (ParseToken(lltok::equal, "expected '=' here") ||
853 ParseToken(lltok::lbrace, "expected '{' here") ||
854 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
856 ParseToken(lltok::rbrace, "expected end of attribute group"))
859 if (!NumberedAttrBuilders[VarID].hasAttributes())
860 return Error(AttrGrpLoc, "attribute group has no attributes");
865 /// ParseFnAttributeValuePairs
866 /// ::= <attr> | <attr> '=' <value>
867 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
868 std::vector<unsigned> &FwdRefAttrGrps,
869 bool inAttrGrp, LocTy &BuiltinLoc) {
870 bool HaveError = false;
875 lltok::Kind Token = Lex.getKind();
876 if (Token == lltok::kw_builtin)
877 BuiltinLoc = Lex.getLoc();
880 if (!inAttrGrp) return HaveError;
881 return Error(Lex.getLoc(), "unterminated attribute group");
886 case lltok::AttrGrpID: {
887 // Allow a function to reference an attribute group:
889 // define void @foo() #1 { ... }
893 "cannot have an attribute group reference in an attribute group");
895 unsigned AttrGrpNum = Lex.getUIntVal();
896 if (inAttrGrp) break;
898 // Save the reference to the attribute group. We'll fill it in later.
899 FwdRefAttrGrps.push_back(AttrGrpNum);
902 // Target-dependent attributes:
903 case lltok::StringConstant: {
904 std::string Attr = Lex.getStrVal();
907 if (EatIfPresent(lltok::equal) &&
908 ParseStringConstant(Val))
911 B.addAttribute(Attr, Val);
915 // Target-independent attributes:
916 case lltok::kw_align: {
917 // As a hack, we allow function alignment to be initially parsed as an
918 // attribute on a function declaration/definition or added to an attribute
919 // group and later moved to the alignment field.
923 if (ParseToken(lltok::equal, "expected '=' here") ||
924 ParseUInt32(Alignment))
927 if (ParseOptionalAlignment(Alignment))
930 B.addAlignmentAttr(Alignment);
933 case lltok::kw_alignstack: {
937 if (ParseToken(lltok::equal, "expected '=' here") ||
938 ParseUInt32(Alignment))
941 if (ParseOptionalStackAlignment(Alignment))
944 B.addStackAlignmentAttr(Alignment);
947 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
948 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
949 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
950 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
951 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
952 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
953 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
954 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
955 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
956 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
957 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
958 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
959 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
960 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
961 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
962 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
963 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
964 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
965 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
966 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
967 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
968 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
969 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
970 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
971 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
972 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
973 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
976 case lltok::kw_inreg:
977 case lltok::kw_signext:
978 case lltok::kw_zeroext:
981 "invalid use of attribute on a function");
983 case lltok::kw_byval:
984 case lltok::kw_dereferenceable:
985 case lltok::kw_inalloca:
987 case lltok::kw_noalias:
988 case lltok::kw_nocapture:
989 case lltok::kw_nonnull:
990 case lltok::kw_returned:
994 "invalid use of parameter-only attribute on a function");
1002 //===----------------------------------------------------------------------===//
1003 // GlobalValue Reference/Resolution Routines.
1004 //===----------------------------------------------------------------------===//
1006 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1007 /// forward reference record if needed. This can return null if the value
1008 /// exists but does not have the right type.
1009 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1011 PointerType *PTy = dyn_cast<PointerType>(Ty);
1013 Error(Loc, "global variable reference must have pointer type");
1017 // Look this name up in the normal function symbol table.
1019 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1021 // If this is a forward reference for the value, see if we already created a
1022 // forward ref record.
1024 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1025 I = ForwardRefVals.find(Name);
1026 if (I != ForwardRefVals.end())
1027 Val = I->second.first;
1030 // If we have the value in the symbol table or fwd-ref table, return it.
1032 if (Val->getType() == Ty) return Val;
1033 Error(Loc, "'@" + Name + "' defined with type '" +
1034 getTypeString(Val->getType()) + "'");
1038 // Otherwise, create a new forward reference for this value and remember it.
1039 GlobalValue *FwdVal;
1040 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1041 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1043 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1044 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1045 nullptr, GlobalVariable::NotThreadLocal,
1046 PTy->getAddressSpace());
1048 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1052 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1053 PointerType *PTy = dyn_cast<PointerType>(Ty);
1055 Error(Loc, "global variable reference must have pointer type");
1059 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1061 // If this is a forward reference for the value, see if we already created a
1062 // forward ref record.
1064 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1065 I = ForwardRefValIDs.find(ID);
1066 if (I != ForwardRefValIDs.end())
1067 Val = I->second.first;
1070 // If we have the value in the symbol table or fwd-ref table, return it.
1072 if (Val->getType() == Ty) return Val;
1073 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1074 getTypeString(Val->getType()) + "'");
1078 // Otherwise, create a new forward reference for this value and remember it.
1079 GlobalValue *FwdVal;
1080 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1081 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1083 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1084 GlobalValue::ExternalWeakLinkage, nullptr, "");
1086 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1091 //===----------------------------------------------------------------------===//
1092 // Comdat Reference/Resolution Routines.
1093 //===----------------------------------------------------------------------===//
1095 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1096 // Look this name up in the comdat symbol table.
1097 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1098 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1099 if (I != ComdatSymTab.end())
1102 // Otherwise, create a new forward reference for this value and remember it.
1103 Comdat *C = M->getOrInsertComdat(Name);
1104 ForwardRefComdats[Name] = Loc;
1109 //===----------------------------------------------------------------------===//
1111 //===----------------------------------------------------------------------===//
1113 /// ParseToken - If the current token has the specified kind, eat it and return
1114 /// success. Otherwise, emit the specified error and return failure.
1115 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1116 if (Lex.getKind() != T)
1117 return TokError(ErrMsg);
1122 /// ParseStringConstant
1123 /// ::= StringConstant
1124 bool LLParser::ParseStringConstant(std::string &Result) {
1125 if (Lex.getKind() != lltok::StringConstant)
1126 return TokError("expected string constant");
1127 Result = Lex.getStrVal();
1134 bool LLParser::ParseUInt32(unsigned &Val) {
1135 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1136 return TokError("expected integer");
1137 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1138 if (Val64 != unsigned(Val64))
1139 return TokError("expected 32-bit integer (too large)");
1147 bool LLParser::ParseUInt64(uint64_t &Val) {
1148 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1149 return TokError("expected integer");
1150 Val = Lex.getAPSIntVal().getLimitedValue();
1156 /// := 'localdynamic'
1157 /// := 'initialexec'
1159 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1160 switch (Lex.getKind()) {
1162 return TokError("expected localdynamic, initialexec or localexec");
1163 case lltok::kw_localdynamic:
1164 TLM = GlobalVariable::LocalDynamicTLSModel;
1166 case lltok::kw_initialexec:
1167 TLM = GlobalVariable::InitialExecTLSModel;
1169 case lltok::kw_localexec:
1170 TLM = GlobalVariable::LocalExecTLSModel;
1178 /// ParseOptionalThreadLocal
1180 /// := 'thread_local'
1181 /// := 'thread_local' '(' tlsmodel ')'
1182 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1183 TLM = GlobalVariable::NotThreadLocal;
1184 if (!EatIfPresent(lltok::kw_thread_local))
1187 TLM = GlobalVariable::GeneralDynamicTLSModel;
1188 if (Lex.getKind() == lltok::lparen) {
1190 return ParseTLSModel(TLM) ||
1191 ParseToken(lltok::rparen, "expected ')' after thread local model");
1196 /// ParseOptionalAddrSpace
1198 /// := 'addrspace' '(' uint32 ')'
1199 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1201 if (!EatIfPresent(lltok::kw_addrspace))
1203 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1204 ParseUInt32(AddrSpace) ||
1205 ParseToken(lltok::rparen, "expected ')' in address space");
1208 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1209 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1210 bool HaveError = false;
1215 lltok::Kind Token = Lex.getKind();
1217 default: // End of attributes.
1219 case lltok::kw_align: {
1221 if (ParseOptionalAlignment(Alignment))
1223 B.addAlignmentAttr(Alignment);
1226 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1227 case lltok::kw_dereferenceable: {
1229 if (ParseOptionalDereferenceableBytes(Bytes))
1231 B.addDereferenceableAttr(Bytes);
1234 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1235 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1236 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1237 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1238 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1239 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1240 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1241 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1242 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1243 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1244 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1245 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1247 case lltok::kw_alignstack:
1248 case lltok::kw_alwaysinline:
1249 case lltok::kw_builtin:
1250 case lltok::kw_inlinehint:
1251 case lltok::kw_jumptable:
1252 case lltok::kw_minsize:
1253 case lltok::kw_naked:
1254 case lltok::kw_nobuiltin:
1255 case lltok::kw_noduplicate:
1256 case lltok::kw_noimplicitfloat:
1257 case lltok::kw_noinline:
1258 case lltok::kw_nonlazybind:
1259 case lltok::kw_noredzone:
1260 case lltok::kw_noreturn:
1261 case lltok::kw_nounwind:
1262 case lltok::kw_optnone:
1263 case lltok::kw_optsize:
1264 case lltok::kw_returns_twice:
1265 case lltok::kw_sanitize_address:
1266 case lltok::kw_sanitize_memory:
1267 case lltok::kw_sanitize_thread:
1269 case lltok::kw_sspreq:
1270 case lltok::kw_sspstrong:
1271 case lltok::kw_uwtable:
1272 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1280 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1281 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1282 bool HaveError = false;
1287 lltok::Kind Token = Lex.getKind();
1289 default: // End of attributes.
1291 case lltok::kw_dereferenceable: {
1293 if (ParseOptionalDereferenceableBytes(Bytes))
1295 B.addDereferenceableAttr(Bytes);
1298 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1299 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1300 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1301 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1302 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1305 case lltok::kw_align:
1306 case lltok::kw_byval:
1307 case lltok::kw_inalloca:
1308 case lltok::kw_nest:
1309 case lltok::kw_nocapture:
1310 case lltok::kw_returned:
1311 case lltok::kw_sret:
1312 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1315 case lltok::kw_alignstack:
1316 case lltok::kw_alwaysinline:
1317 case lltok::kw_builtin:
1318 case lltok::kw_cold:
1319 case lltok::kw_inlinehint:
1320 case lltok::kw_jumptable:
1321 case lltok::kw_minsize:
1322 case lltok::kw_naked:
1323 case lltok::kw_nobuiltin:
1324 case lltok::kw_noduplicate:
1325 case lltok::kw_noimplicitfloat:
1326 case lltok::kw_noinline:
1327 case lltok::kw_nonlazybind:
1328 case lltok::kw_noredzone:
1329 case lltok::kw_noreturn:
1330 case lltok::kw_nounwind:
1331 case lltok::kw_optnone:
1332 case lltok::kw_optsize:
1333 case lltok::kw_returns_twice:
1334 case lltok::kw_sanitize_address:
1335 case lltok::kw_sanitize_memory:
1336 case lltok::kw_sanitize_thread:
1338 case lltok::kw_sspreq:
1339 case lltok::kw_sspstrong:
1340 case lltok::kw_uwtable:
1341 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1344 case lltok::kw_readnone:
1345 case lltok::kw_readonly:
1346 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1353 /// ParseOptionalLinkage
1360 /// ::= 'linkonce_odr'
1361 /// ::= 'available_externally'
1364 /// ::= 'extern_weak'
1366 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1368 switch (Lex.getKind()) {
1369 default: Res=GlobalValue::ExternalLinkage; return false;
1370 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1371 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1372 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1373 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1374 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1375 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1376 case lltok::kw_available_externally:
1377 Res = GlobalValue::AvailableExternallyLinkage;
1379 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1380 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1381 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1382 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1389 /// ParseOptionalVisibility
1395 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1396 switch (Lex.getKind()) {
1397 default: Res = GlobalValue::DefaultVisibility; return false;
1398 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1399 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1400 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1406 /// ParseOptionalDLLStorageClass
1411 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1412 switch (Lex.getKind()) {
1413 default: Res = GlobalValue::DefaultStorageClass; return false;
1414 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1415 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1421 /// ParseOptionalCallingConv
1425 /// ::= 'intel_ocl_bicc'
1427 /// ::= 'x86_stdcallcc'
1428 /// ::= 'x86_fastcallcc'
1429 /// ::= 'x86_thiscallcc'
1430 /// ::= 'x86_vectorcallcc'
1431 /// ::= 'arm_apcscc'
1432 /// ::= 'arm_aapcscc'
1433 /// ::= 'arm_aapcs_vfpcc'
1434 /// ::= 'msp430_intrcc'
1435 /// ::= 'ptx_kernel'
1436 /// ::= 'ptx_device'
1438 /// ::= 'spir_kernel'
1439 /// ::= 'x86_64_sysvcc'
1440 /// ::= 'x86_64_win64cc'
1441 /// ::= 'webkit_jscc'
1443 /// ::= 'preserve_mostcc'
1444 /// ::= 'preserve_allcc'
1448 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1449 switch (Lex.getKind()) {
1450 default: CC = CallingConv::C; return false;
1451 case lltok::kw_ccc: CC = CallingConv::C; break;
1452 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1453 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1454 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1455 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1456 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1457 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1458 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1459 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1460 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1461 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1462 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1463 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1464 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1465 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1466 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1467 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1468 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1469 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1470 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1471 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1472 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1473 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1474 case lltok::kw_cc: {
1476 return ParseUInt32(CC);
1484 /// ParseInstructionMetadata
1485 /// ::= !dbg !42 (',' !dbg !57)*
1486 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1487 PerFunctionState *PFS) {
1489 if (Lex.getKind() != lltok::MetadataVar)
1490 return TokError("expected metadata after comma");
1492 std::string Name = Lex.getStrVal();
1493 unsigned MDK = M->getMDKindID(Name);
1500 Inst->setMetadata(MDK, N);
1501 if (MDK == LLVMContext::MD_tbaa)
1502 InstsWithTBAATag.push_back(Inst);
1504 // If this is the end of the list, we're done.
1505 } while (EatIfPresent(lltok::comma));
1509 /// ParseOptionalAlignment
1512 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1514 if (!EatIfPresent(lltok::kw_align))
1516 LocTy AlignLoc = Lex.getLoc();
1517 if (ParseUInt32(Alignment)) return true;
1518 if (!isPowerOf2_32(Alignment))
1519 return Error(AlignLoc, "alignment is not a power of two");
1520 if (Alignment > Value::MaximumAlignment)
1521 return Error(AlignLoc, "huge alignments are not supported yet");
1525 /// ParseOptionalDereferenceableBytes
1527 /// ::= 'dereferenceable' '(' 4 ')'
1528 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1530 if (!EatIfPresent(lltok::kw_dereferenceable))
1532 LocTy ParenLoc = Lex.getLoc();
1533 if (!EatIfPresent(lltok::lparen))
1534 return Error(ParenLoc, "expected '('");
1535 LocTy DerefLoc = Lex.getLoc();
1536 if (ParseUInt64(Bytes)) return true;
1537 ParenLoc = Lex.getLoc();
1538 if (!EatIfPresent(lltok::rparen))
1539 return Error(ParenLoc, "expected ')'");
1541 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1545 /// ParseOptionalCommaAlign
1549 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1551 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1552 bool &AteExtraComma) {
1553 AteExtraComma = false;
1554 while (EatIfPresent(lltok::comma)) {
1555 // Metadata at the end is an early exit.
1556 if (Lex.getKind() == lltok::MetadataVar) {
1557 AteExtraComma = true;
1561 if (Lex.getKind() != lltok::kw_align)
1562 return Error(Lex.getLoc(), "expected metadata or 'align'");
1564 if (ParseOptionalAlignment(Alignment)) return true;
1570 /// ParseScopeAndOrdering
1571 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1574 /// This sets Scope and Ordering to the parsed values.
1575 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1576 AtomicOrdering &Ordering) {
1580 Scope = CrossThread;
1581 if (EatIfPresent(lltok::kw_singlethread))
1582 Scope = SingleThread;
1584 return ParseOrdering(Ordering);
1588 /// ::= AtomicOrdering
1590 /// This sets Ordering to the parsed value.
1591 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1592 switch (Lex.getKind()) {
1593 default: return TokError("Expected ordering on atomic instruction");
1594 case lltok::kw_unordered: Ordering = Unordered; break;
1595 case lltok::kw_monotonic: Ordering = Monotonic; break;
1596 case lltok::kw_acquire: Ordering = Acquire; break;
1597 case lltok::kw_release: Ordering = Release; break;
1598 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1599 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1605 /// ParseOptionalStackAlignment
1607 /// ::= 'alignstack' '(' 4 ')'
1608 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1610 if (!EatIfPresent(lltok::kw_alignstack))
1612 LocTy ParenLoc = Lex.getLoc();
1613 if (!EatIfPresent(lltok::lparen))
1614 return Error(ParenLoc, "expected '('");
1615 LocTy AlignLoc = Lex.getLoc();
1616 if (ParseUInt32(Alignment)) return true;
1617 ParenLoc = Lex.getLoc();
1618 if (!EatIfPresent(lltok::rparen))
1619 return Error(ParenLoc, "expected ')'");
1620 if (!isPowerOf2_32(Alignment))
1621 return Error(AlignLoc, "stack alignment is not a power of two");
1625 /// ParseIndexList - This parses the index list for an insert/extractvalue
1626 /// instruction. This sets AteExtraComma in the case where we eat an extra
1627 /// comma at the end of the line and find that it is followed by metadata.
1628 /// Clients that don't allow metadata can call the version of this function that
1629 /// only takes one argument.
1632 /// ::= (',' uint32)+
1634 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1635 bool &AteExtraComma) {
1636 AteExtraComma = false;
1638 if (Lex.getKind() != lltok::comma)
1639 return TokError("expected ',' as start of index list");
1641 while (EatIfPresent(lltok::comma)) {
1642 if (Lex.getKind() == lltok::MetadataVar) {
1643 AteExtraComma = true;
1647 if (ParseUInt32(Idx)) return true;
1648 Indices.push_back(Idx);
1654 //===----------------------------------------------------------------------===//
1656 //===----------------------------------------------------------------------===//
1658 /// ParseType - Parse a type.
1659 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1660 SMLoc TypeLoc = Lex.getLoc();
1661 switch (Lex.getKind()) {
1663 return TokError(Msg);
1665 // Type ::= 'float' | 'void' (etc)
1666 Result = Lex.getTyVal();
1670 // Type ::= StructType
1671 if (ParseAnonStructType(Result, false))
1674 case lltok::lsquare:
1675 // Type ::= '[' ... ']'
1676 Lex.Lex(); // eat the lsquare.
1677 if (ParseArrayVectorType(Result, false))
1680 case lltok::less: // Either vector or packed struct.
1681 // Type ::= '<' ... '>'
1683 if (Lex.getKind() == lltok::lbrace) {
1684 if (ParseAnonStructType(Result, true) ||
1685 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1687 } else if (ParseArrayVectorType(Result, true))
1690 case lltok::LocalVar: {
1692 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1694 // If the type hasn't been defined yet, create a forward definition and
1695 // remember where that forward def'n was seen (in case it never is defined).
1697 Entry.first = StructType::create(Context, Lex.getStrVal());
1698 Entry.second = Lex.getLoc();
1700 Result = Entry.first;
1705 case lltok::LocalVarID: {
1707 if (Lex.getUIntVal() >= NumberedTypes.size())
1708 NumberedTypes.resize(Lex.getUIntVal()+1);
1709 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1711 // If the type hasn't been defined yet, create a forward definition and
1712 // remember where that forward def'n was seen (in case it never is defined).
1714 Entry.first = StructType::create(Context);
1715 Entry.second = Lex.getLoc();
1717 Result = Entry.first;
1723 // Parse the type suffixes.
1725 switch (Lex.getKind()) {
1728 if (!AllowVoid && Result->isVoidTy())
1729 return Error(TypeLoc, "void type only allowed for function results");
1732 // Type ::= Type '*'
1734 if (Result->isLabelTy())
1735 return TokError("basic block pointers are invalid");
1736 if (Result->isVoidTy())
1737 return TokError("pointers to void are invalid - use i8* instead");
1738 if (!PointerType::isValidElementType(Result))
1739 return TokError("pointer to this type is invalid");
1740 Result = PointerType::getUnqual(Result);
1744 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1745 case lltok::kw_addrspace: {
1746 if (Result->isLabelTy())
1747 return TokError("basic block pointers are invalid");
1748 if (Result->isVoidTy())
1749 return TokError("pointers to void are invalid; use i8* instead");
1750 if (!PointerType::isValidElementType(Result))
1751 return TokError("pointer to this type is invalid");
1753 if (ParseOptionalAddrSpace(AddrSpace) ||
1754 ParseToken(lltok::star, "expected '*' in address space"))
1757 Result = PointerType::get(Result, AddrSpace);
1761 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1763 if (ParseFunctionType(Result))
1770 /// ParseParameterList
1772 /// ::= '(' Arg (',' Arg)* ')'
1774 /// ::= Type OptionalAttributes Value OptionalAttributes
1775 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1776 PerFunctionState &PFS, bool IsMustTailCall,
1777 bool InVarArgsFunc) {
1778 if (ParseToken(lltok::lparen, "expected '(' in call"))
1781 unsigned AttrIndex = 1;
1782 while (Lex.getKind() != lltok::rparen) {
1783 // If this isn't the first argument, we need a comma.
1784 if (!ArgList.empty() &&
1785 ParseToken(lltok::comma, "expected ',' in argument list"))
1788 // Parse an ellipsis if this is a musttail call in a variadic function.
1789 if (Lex.getKind() == lltok::dotdotdot) {
1790 const char *Msg = "unexpected ellipsis in argument list for ";
1791 if (!IsMustTailCall)
1792 return TokError(Twine(Msg) + "non-musttail call");
1794 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1795 Lex.Lex(); // Lex the '...', it is purely for readability.
1796 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1799 // Parse the argument.
1801 Type *ArgTy = nullptr;
1802 AttrBuilder ArgAttrs;
1804 if (ParseType(ArgTy, ArgLoc))
1807 if (ArgTy->isMetadataTy()) {
1808 if (ParseMetadataAsValue(V, PFS))
1811 // Otherwise, handle normal operands.
1812 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1815 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1820 if (IsMustTailCall && InVarArgsFunc)
1821 return TokError("expected '...' at end of argument list for musttail call "
1822 "in varargs function");
1824 Lex.Lex(); // Lex the ')'.
1830 /// ParseArgumentList - Parse the argument list for a function type or function
1832 /// ::= '(' ArgTypeListI ')'
1836 /// ::= ArgTypeList ',' '...'
1837 /// ::= ArgType (',' ArgType)*
1839 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1842 assert(Lex.getKind() == lltok::lparen);
1843 Lex.Lex(); // eat the (.
1845 if (Lex.getKind() == lltok::rparen) {
1847 } else if (Lex.getKind() == lltok::dotdotdot) {
1851 LocTy TypeLoc = Lex.getLoc();
1852 Type *ArgTy = nullptr;
1856 if (ParseType(ArgTy) ||
1857 ParseOptionalParamAttrs(Attrs)) return true;
1859 if (ArgTy->isVoidTy())
1860 return Error(TypeLoc, "argument can not have void type");
1862 if (Lex.getKind() == lltok::LocalVar) {
1863 Name = Lex.getStrVal();
1867 if (!FunctionType::isValidArgumentType(ArgTy))
1868 return Error(TypeLoc, "invalid type for function argument");
1870 unsigned AttrIndex = 1;
1871 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1872 AttributeSet::get(ArgTy->getContext(),
1873 AttrIndex++, Attrs), Name));
1875 while (EatIfPresent(lltok::comma)) {
1876 // Handle ... at end of arg list.
1877 if (EatIfPresent(lltok::dotdotdot)) {
1882 // Otherwise must be an argument type.
1883 TypeLoc = Lex.getLoc();
1884 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1886 if (ArgTy->isVoidTy())
1887 return Error(TypeLoc, "argument can not have void type");
1889 if (Lex.getKind() == lltok::LocalVar) {
1890 Name = Lex.getStrVal();
1896 if (!ArgTy->isFirstClassType())
1897 return Error(TypeLoc, "invalid type for function argument");
1899 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1900 AttributeSet::get(ArgTy->getContext(),
1901 AttrIndex++, Attrs),
1906 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1909 /// ParseFunctionType
1910 /// ::= Type ArgumentList OptionalAttrs
1911 bool LLParser::ParseFunctionType(Type *&Result) {
1912 assert(Lex.getKind() == lltok::lparen);
1914 if (!FunctionType::isValidReturnType(Result))
1915 return TokError("invalid function return type");
1917 SmallVector<ArgInfo, 8> ArgList;
1919 if (ParseArgumentList(ArgList, isVarArg))
1922 // Reject names on the arguments lists.
1923 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1924 if (!ArgList[i].Name.empty())
1925 return Error(ArgList[i].Loc, "argument name invalid in function type");
1926 if (ArgList[i].Attrs.hasAttributes(i + 1))
1927 return Error(ArgList[i].Loc,
1928 "argument attributes invalid in function type");
1931 SmallVector<Type*, 16> ArgListTy;
1932 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1933 ArgListTy.push_back(ArgList[i].Ty);
1935 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1939 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1941 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1942 SmallVector<Type*, 8> Elts;
1943 if (ParseStructBody(Elts)) return true;
1945 Result = StructType::get(Context, Elts, Packed);
1949 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1950 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1951 std::pair<Type*, LocTy> &Entry,
1953 // If the type was already defined, diagnose the redefinition.
1954 if (Entry.first && !Entry.second.isValid())
1955 return Error(TypeLoc, "redefinition of type");
1957 // If we have opaque, just return without filling in the definition for the
1958 // struct. This counts as a definition as far as the .ll file goes.
1959 if (EatIfPresent(lltok::kw_opaque)) {
1960 // This type is being defined, so clear the location to indicate this.
1961 Entry.second = SMLoc();
1963 // If this type number has never been uttered, create it.
1965 Entry.first = StructType::create(Context, Name);
1966 ResultTy = Entry.first;
1970 // If the type starts with '<', then it is either a packed struct or a vector.
1971 bool isPacked = EatIfPresent(lltok::less);
1973 // If we don't have a struct, then we have a random type alias, which we
1974 // accept for compatibility with old files. These types are not allowed to be
1975 // forward referenced and not allowed to be recursive.
1976 if (Lex.getKind() != lltok::lbrace) {
1978 return Error(TypeLoc, "forward references to non-struct type");
1982 return ParseArrayVectorType(ResultTy, true);
1983 return ParseType(ResultTy);
1986 // This type is being defined, so clear the location to indicate this.
1987 Entry.second = SMLoc();
1989 // If this type number has never been uttered, create it.
1991 Entry.first = StructType::create(Context, Name);
1993 StructType *STy = cast<StructType>(Entry.first);
1995 SmallVector<Type*, 8> Body;
1996 if (ParseStructBody(Body) ||
1997 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2000 STy->setBody(Body, isPacked);
2006 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2009 /// ::= '{' Type (',' Type)* '}'
2010 /// ::= '<' '{' '}' '>'
2011 /// ::= '<' '{' Type (',' Type)* '}' '>'
2012 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2013 assert(Lex.getKind() == lltok::lbrace);
2014 Lex.Lex(); // Consume the '{'
2016 // Handle the empty struct.
2017 if (EatIfPresent(lltok::rbrace))
2020 LocTy EltTyLoc = Lex.getLoc();
2022 if (ParseType(Ty)) return true;
2025 if (!StructType::isValidElementType(Ty))
2026 return Error(EltTyLoc, "invalid element type for struct");
2028 while (EatIfPresent(lltok::comma)) {
2029 EltTyLoc = Lex.getLoc();
2030 if (ParseType(Ty)) return true;
2032 if (!StructType::isValidElementType(Ty))
2033 return Error(EltTyLoc, "invalid element type for struct");
2038 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2041 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2042 /// token has already been consumed.
2044 /// ::= '[' APSINTVAL 'x' Types ']'
2045 /// ::= '<' APSINTVAL 'x' Types '>'
2046 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2047 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2048 Lex.getAPSIntVal().getBitWidth() > 64)
2049 return TokError("expected number in address space");
2051 LocTy SizeLoc = Lex.getLoc();
2052 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2055 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2058 LocTy TypeLoc = Lex.getLoc();
2059 Type *EltTy = nullptr;
2060 if (ParseType(EltTy)) return true;
2062 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2063 "expected end of sequential type"))
2068 return Error(SizeLoc, "zero element vector is illegal");
2069 if ((unsigned)Size != Size)
2070 return Error(SizeLoc, "size too large for vector");
2071 if (!VectorType::isValidElementType(EltTy))
2072 return Error(TypeLoc, "invalid vector element type");
2073 Result = VectorType::get(EltTy, unsigned(Size));
2075 if (!ArrayType::isValidElementType(EltTy))
2076 return Error(TypeLoc, "invalid array element type");
2077 Result = ArrayType::get(EltTy, Size);
2082 //===----------------------------------------------------------------------===//
2083 // Function Semantic Analysis.
2084 //===----------------------------------------------------------------------===//
2086 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2088 : P(p), F(f), FunctionNumber(functionNumber) {
2090 // Insert unnamed arguments into the NumberedVals list.
2091 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2094 NumberedVals.push_back(AI);
2097 LLParser::PerFunctionState::~PerFunctionState() {
2098 // If there were any forward referenced non-basicblock values, delete them.
2099 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2100 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2101 if (!isa<BasicBlock>(I->second.first)) {
2102 I->second.first->replaceAllUsesWith(
2103 UndefValue::get(I->second.first->getType()));
2104 delete I->second.first;
2105 I->second.first = nullptr;
2108 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2109 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2110 if (!isa<BasicBlock>(I->second.first)) {
2111 I->second.first->replaceAllUsesWith(
2112 UndefValue::get(I->second.first->getType()));
2113 delete I->second.first;
2114 I->second.first = nullptr;
2118 bool LLParser::PerFunctionState::FinishFunction() {
2119 if (!ForwardRefVals.empty())
2120 return P.Error(ForwardRefVals.begin()->second.second,
2121 "use of undefined value '%" + ForwardRefVals.begin()->first +
2123 if (!ForwardRefValIDs.empty())
2124 return P.Error(ForwardRefValIDs.begin()->second.second,
2125 "use of undefined value '%" +
2126 Twine(ForwardRefValIDs.begin()->first) + "'");
2131 /// GetVal - Get a value with the specified name or ID, creating a
2132 /// forward reference record if needed. This can return null if the value
2133 /// exists but does not have the right type.
2134 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2135 Type *Ty, LocTy Loc) {
2136 // Look this name up in the normal function symbol table.
2137 Value *Val = F.getValueSymbolTable().lookup(Name);
2139 // If this is a forward reference for the value, see if we already created a
2140 // forward ref record.
2142 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2143 I = ForwardRefVals.find(Name);
2144 if (I != ForwardRefVals.end())
2145 Val = I->second.first;
2148 // If we have the value in the symbol table or fwd-ref table, return it.
2150 if (Val->getType() == Ty) return Val;
2151 if (Ty->isLabelTy())
2152 P.Error(Loc, "'%" + Name + "' is not a basic block");
2154 P.Error(Loc, "'%" + Name + "' defined with type '" +
2155 getTypeString(Val->getType()) + "'");
2159 // Don't make placeholders with invalid type.
2160 if (!Ty->isFirstClassType()) {
2161 P.Error(Loc, "invalid use of a non-first-class type");
2165 // Otherwise, create a new forward reference for this value and remember it.
2167 if (Ty->isLabelTy())
2168 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2170 FwdVal = new Argument(Ty, Name);
2172 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2176 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2178 // Look this name up in the normal function symbol table.
2179 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2181 // If this is a forward reference for the value, see if we already created a
2182 // forward ref record.
2184 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2185 I = ForwardRefValIDs.find(ID);
2186 if (I != ForwardRefValIDs.end())
2187 Val = I->second.first;
2190 // If we have the value in the symbol table or fwd-ref table, return it.
2192 if (Val->getType() == Ty) return Val;
2193 if (Ty->isLabelTy())
2194 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2196 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2197 getTypeString(Val->getType()) + "'");
2201 if (!Ty->isFirstClassType()) {
2202 P.Error(Loc, "invalid use of a non-first-class type");
2206 // Otherwise, create a new forward reference for this value and remember it.
2208 if (Ty->isLabelTy())
2209 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2211 FwdVal = new Argument(Ty);
2213 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2217 /// SetInstName - After an instruction is parsed and inserted into its
2218 /// basic block, this installs its name.
2219 bool LLParser::PerFunctionState::SetInstName(int NameID,
2220 const std::string &NameStr,
2221 LocTy NameLoc, Instruction *Inst) {
2222 // If this instruction has void type, it cannot have a name or ID specified.
2223 if (Inst->getType()->isVoidTy()) {
2224 if (NameID != -1 || !NameStr.empty())
2225 return P.Error(NameLoc, "instructions returning void cannot have a name");
2229 // If this was a numbered instruction, verify that the instruction is the
2230 // expected value and resolve any forward references.
2231 if (NameStr.empty()) {
2232 // If neither a name nor an ID was specified, just use the next ID.
2234 NameID = NumberedVals.size();
2236 if (unsigned(NameID) != NumberedVals.size())
2237 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2238 Twine(NumberedVals.size()) + "'");
2240 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2241 ForwardRefValIDs.find(NameID);
2242 if (FI != ForwardRefValIDs.end()) {
2243 if (FI->second.first->getType() != Inst->getType())
2244 return P.Error(NameLoc, "instruction forward referenced with type '" +
2245 getTypeString(FI->second.first->getType()) + "'");
2246 FI->second.first->replaceAllUsesWith(Inst);
2247 delete FI->second.first;
2248 ForwardRefValIDs.erase(FI);
2251 NumberedVals.push_back(Inst);
2255 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2256 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2257 FI = ForwardRefVals.find(NameStr);
2258 if (FI != ForwardRefVals.end()) {
2259 if (FI->second.first->getType() != Inst->getType())
2260 return P.Error(NameLoc, "instruction forward referenced with type '" +
2261 getTypeString(FI->second.first->getType()) + "'");
2262 FI->second.first->replaceAllUsesWith(Inst);
2263 delete FI->second.first;
2264 ForwardRefVals.erase(FI);
2267 // Set the name on the instruction.
2268 Inst->setName(NameStr);
2270 if (Inst->getName() != NameStr)
2271 return P.Error(NameLoc, "multiple definition of local value named '" +
2276 /// GetBB - Get a basic block with the specified name or ID, creating a
2277 /// forward reference record if needed.
2278 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2280 return cast_or_null<BasicBlock>(GetVal(Name,
2281 Type::getLabelTy(F.getContext()), Loc));
2284 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2285 return cast_or_null<BasicBlock>(GetVal(ID,
2286 Type::getLabelTy(F.getContext()), Loc));
2289 /// DefineBB - Define the specified basic block, which is either named or
2290 /// unnamed. If there is an error, this returns null otherwise it returns
2291 /// the block being defined.
2292 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2296 BB = GetBB(NumberedVals.size(), Loc);
2298 BB = GetBB(Name, Loc);
2299 if (!BB) return nullptr; // Already diagnosed error.
2301 // Move the block to the end of the function. Forward ref'd blocks are
2302 // inserted wherever they happen to be referenced.
2303 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2305 // Remove the block from forward ref sets.
2307 ForwardRefValIDs.erase(NumberedVals.size());
2308 NumberedVals.push_back(BB);
2310 // BB forward references are already in the function symbol table.
2311 ForwardRefVals.erase(Name);
2317 //===----------------------------------------------------------------------===//
2319 //===----------------------------------------------------------------------===//
2321 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2322 /// type implied. For example, if we parse "4" we don't know what integer type
2323 /// it has. The value will later be combined with its type and checked for
2324 /// sanity. PFS is used to convert function-local operands of metadata (since
2325 /// metadata operands are not just parsed here but also converted to values).
2326 /// PFS can be null when we are not parsing metadata values inside a function.
2327 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2328 ID.Loc = Lex.getLoc();
2329 switch (Lex.getKind()) {
2330 default: return TokError("expected value token");
2331 case lltok::GlobalID: // @42
2332 ID.UIntVal = Lex.getUIntVal();
2333 ID.Kind = ValID::t_GlobalID;
2335 case lltok::GlobalVar: // @foo
2336 ID.StrVal = Lex.getStrVal();
2337 ID.Kind = ValID::t_GlobalName;
2339 case lltok::LocalVarID: // %42
2340 ID.UIntVal = Lex.getUIntVal();
2341 ID.Kind = ValID::t_LocalID;
2343 case lltok::LocalVar: // %foo
2344 ID.StrVal = Lex.getStrVal();
2345 ID.Kind = ValID::t_LocalName;
2348 ID.APSIntVal = Lex.getAPSIntVal();
2349 ID.Kind = ValID::t_APSInt;
2351 case lltok::APFloat:
2352 ID.APFloatVal = Lex.getAPFloatVal();
2353 ID.Kind = ValID::t_APFloat;
2355 case lltok::kw_true:
2356 ID.ConstantVal = ConstantInt::getTrue(Context);
2357 ID.Kind = ValID::t_Constant;
2359 case lltok::kw_false:
2360 ID.ConstantVal = ConstantInt::getFalse(Context);
2361 ID.Kind = ValID::t_Constant;
2363 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2364 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2365 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2367 case lltok::lbrace: {
2368 // ValID ::= '{' ConstVector '}'
2370 SmallVector<Constant*, 16> Elts;
2371 if (ParseGlobalValueVector(Elts) ||
2372 ParseToken(lltok::rbrace, "expected end of struct constant"))
2375 ID.ConstantStructElts = new Constant*[Elts.size()];
2376 ID.UIntVal = Elts.size();
2377 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2378 ID.Kind = ValID::t_ConstantStruct;
2382 // ValID ::= '<' ConstVector '>' --> Vector.
2383 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2385 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2387 SmallVector<Constant*, 16> Elts;
2388 LocTy FirstEltLoc = Lex.getLoc();
2389 if (ParseGlobalValueVector(Elts) ||
2391 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2392 ParseToken(lltok::greater, "expected end of constant"))
2395 if (isPackedStruct) {
2396 ID.ConstantStructElts = new Constant*[Elts.size()];
2397 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2398 ID.UIntVal = Elts.size();
2399 ID.Kind = ValID::t_PackedConstantStruct;
2404 return Error(ID.Loc, "constant vector must not be empty");
2406 if (!Elts[0]->getType()->isIntegerTy() &&
2407 !Elts[0]->getType()->isFloatingPointTy() &&
2408 !Elts[0]->getType()->isPointerTy())
2409 return Error(FirstEltLoc,
2410 "vector elements must have integer, pointer or floating point type");
2412 // Verify that all the vector elements have the same type.
2413 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2414 if (Elts[i]->getType() != Elts[0]->getType())
2415 return Error(FirstEltLoc,
2416 "vector element #" + Twine(i) +
2417 " is not of type '" + getTypeString(Elts[0]->getType()));
2419 ID.ConstantVal = ConstantVector::get(Elts);
2420 ID.Kind = ValID::t_Constant;
2423 case lltok::lsquare: { // Array Constant
2425 SmallVector<Constant*, 16> Elts;
2426 LocTy FirstEltLoc = Lex.getLoc();
2427 if (ParseGlobalValueVector(Elts) ||
2428 ParseToken(lltok::rsquare, "expected end of array constant"))
2431 // Handle empty element.
2433 // Use undef instead of an array because it's inconvenient to determine
2434 // the element type at this point, there being no elements to examine.
2435 ID.Kind = ValID::t_EmptyArray;
2439 if (!Elts[0]->getType()->isFirstClassType())
2440 return Error(FirstEltLoc, "invalid array element type: " +
2441 getTypeString(Elts[0]->getType()));
2443 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2445 // Verify all elements are correct type!
2446 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2447 if (Elts[i]->getType() != Elts[0]->getType())
2448 return Error(FirstEltLoc,
2449 "array element #" + Twine(i) +
2450 " is not of type '" + getTypeString(Elts[0]->getType()));
2453 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2454 ID.Kind = ValID::t_Constant;
2457 case lltok::kw_c: // c "foo"
2459 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2461 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2462 ID.Kind = ValID::t_Constant;
2465 case lltok::kw_asm: {
2466 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2468 bool HasSideEffect, AlignStack, AsmDialect;
2470 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2471 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2472 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2473 ParseStringConstant(ID.StrVal) ||
2474 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2475 ParseToken(lltok::StringConstant, "expected constraint string"))
2477 ID.StrVal2 = Lex.getStrVal();
2478 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2479 (unsigned(AsmDialect)<<2);
2480 ID.Kind = ValID::t_InlineAsm;
2484 case lltok::kw_blockaddress: {
2485 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2490 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2492 ParseToken(lltok::comma, "expected comma in block address expression")||
2493 ParseValID(Label) ||
2494 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2497 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2498 return Error(Fn.Loc, "expected function name in blockaddress");
2499 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2500 return Error(Label.Loc, "expected basic block name in blockaddress");
2502 // Try to find the function (but skip it if it's forward-referenced).
2503 GlobalValue *GV = nullptr;
2504 if (Fn.Kind == ValID::t_GlobalID) {
2505 if (Fn.UIntVal < NumberedVals.size())
2506 GV = NumberedVals[Fn.UIntVal];
2507 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2508 GV = M->getNamedValue(Fn.StrVal);
2510 Function *F = nullptr;
2512 // Confirm that it's actually a function with a definition.
2513 if (!isa<Function>(GV))
2514 return Error(Fn.Loc, "expected function name in blockaddress");
2515 F = cast<Function>(GV);
2516 if (F->isDeclaration())
2517 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2521 // Make a global variable as a placeholder for this reference.
2522 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2524 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2525 GlobalValue::InternalLinkage, nullptr, "");
2526 ID.ConstantVal = FwdRef;
2527 ID.Kind = ValID::t_Constant;
2531 // We found the function; now find the basic block. Don't use PFS, since we
2532 // might be inside a constant expression.
2534 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2535 if (Label.Kind == ValID::t_LocalID)
2536 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2538 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2540 return Error(Label.Loc, "referenced value is not a basic block");
2542 if (Label.Kind == ValID::t_LocalID)
2543 return Error(Label.Loc, "cannot take address of numeric label after "
2544 "the function is defined");
2545 BB = dyn_cast_or_null<BasicBlock>(
2546 F->getValueSymbolTable().lookup(Label.StrVal));
2548 return Error(Label.Loc, "referenced value is not a basic block");
2551 ID.ConstantVal = BlockAddress::get(F, BB);
2552 ID.Kind = ValID::t_Constant;
2556 case lltok::kw_trunc:
2557 case lltok::kw_zext:
2558 case lltok::kw_sext:
2559 case lltok::kw_fptrunc:
2560 case lltok::kw_fpext:
2561 case lltok::kw_bitcast:
2562 case lltok::kw_addrspacecast:
2563 case lltok::kw_uitofp:
2564 case lltok::kw_sitofp:
2565 case lltok::kw_fptoui:
2566 case lltok::kw_fptosi:
2567 case lltok::kw_inttoptr:
2568 case lltok::kw_ptrtoint: {
2569 unsigned Opc = Lex.getUIntVal();
2570 Type *DestTy = nullptr;
2573 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2574 ParseGlobalTypeAndValue(SrcVal) ||
2575 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2576 ParseType(DestTy) ||
2577 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2579 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2580 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2581 getTypeString(SrcVal->getType()) + "' to '" +
2582 getTypeString(DestTy) + "'");
2583 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2585 ID.Kind = ValID::t_Constant;
2588 case lltok::kw_extractvalue: {
2591 SmallVector<unsigned, 4> Indices;
2592 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2593 ParseGlobalTypeAndValue(Val) ||
2594 ParseIndexList(Indices) ||
2595 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2598 if (!Val->getType()->isAggregateType())
2599 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2600 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2601 return Error(ID.Loc, "invalid indices for extractvalue");
2602 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2603 ID.Kind = ValID::t_Constant;
2606 case lltok::kw_insertvalue: {
2608 Constant *Val0, *Val1;
2609 SmallVector<unsigned, 4> Indices;
2610 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2611 ParseGlobalTypeAndValue(Val0) ||
2612 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2613 ParseGlobalTypeAndValue(Val1) ||
2614 ParseIndexList(Indices) ||
2615 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2617 if (!Val0->getType()->isAggregateType())
2618 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2619 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2620 return Error(ID.Loc, "invalid indices for insertvalue");
2621 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2622 ID.Kind = ValID::t_Constant;
2625 case lltok::kw_icmp:
2626 case lltok::kw_fcmp: {
2627 unsigned PredVal, Opc = Lex.getUIntVal();
2628 Constant *Val0, *Val1;
2630 if (ParseCmpPredicate(PredVal, Opc) ||
2631 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2632 ParseGlobalTypeAndValue(Val0) ||
2633 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2634 ParseGlobalTypeAndValue(Val1) ||
2635 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2638 if (Val0->getType() != Val1->getType())
2639 return Error(ID.Loc, "compare operands must have the same type");
2641 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2643 if (Opc == Instruction::FCmp) {
2644 if (!Val0->getType()->isFPOrFPVectorTy())
2645 return Error(ID.Loc, "fcmp requires floating point operands");
2646 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2648 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2649 if (!Val0->getType()->isIntOrIntVectorTy() &&
2650 !Val0->getType()->getScalarType()->isPointerTy())
2651 return Error(ID.Loc, "icmp requires pointer or integer operands");
2652 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2654 ID.Kind = ValID::t_Constant;
2658 // Binary Operators.
2660 case lltok::kw_fadd:
2662 case lltok::kw_fsub:
2664 case lltok::kw_fmul:
2665 case lltok::kw_udiv:
2666 case lltok::kw_sdiv:
2667 case lltok::kw_fdiv:
2668 case lltok::kw_urem:
2669 case lltok::kw_srem:
2670 case lltok::kw_frem:
2672 case lltok::kw_lshr:
2673 case lltok::kw_ashr: {
2677 unsigned Opc = Lex.getUIntVal();
2678 Constant *Val0, *Val1;
2680 LocTy ModifierLoc = Lex.getLoc();
2681 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2682 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2683 if (EatIfPresent(lltok::kw_nuw))
2685 if (EatIfPresent(lltok::kw_nsw)) {
2687 if (EatIfPresent(lltok::kw_nuw))
2690 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2691 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2692 if (EatIfPresent(lltok::kw_exact))
2695 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2696 ParseGlobalTypeAndValue(Val0) ||
2697 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2698 ParseGlobalTypeAndValue(Val1) ||
2699 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2701 if (Val0->getType() != Val1->getType())
2702 return Error(ID.Loc, "operands of constexpr must have same type");
2703 if (!Val0->getType()->isIntOrIntVectorTy()) {
2705 return Error(ModifierLoc, "nuw only applies to integer operations");
2707 return Error(ModifierLoc, "nsw only applies to integer operations");
2709 // Check that the type is valid for the operator.
2711 case Instruction::Add:
2712 case Instruction::Sub:
2713 case Instruction::Mul:
2714 case Instruction::UDiv:
2715 case Instruction::SDiv:
2716 case Instruction::URem:
2717 case Instruction::SRem:
2718 case Instruction::Shl:
2719 case Instruction::AShr:
2720 case Instruction::LShr:
2721 if (!Val0->getType()->isIntOrIntVectorTy())
2722 return Error(ID.Loc, "constexpr requires integer operands");
2724 case Instruction::FAdd:
2725 case Instruction::FSub:
2726 case Instruction::FMul:
2727 case Instruction::FDiv:
2728 case Instruction::FRem:
2729 if (!Val0->getType()->isFPOrFPVectorTy())
2730 return Error(ID.Loc, "constexpr requires fp operands");
2732 default: llvm_unreachable("Unknown binary operator!");
2735 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2736 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2737 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2738 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2740 ID.Kind = ValID::t_Constant;
2744 // Logical Operations
2747 case lltok::kw_xor: {
2748 unsigned Opc = Lex.getUIntVal();
2749 Constant *Val0, *Val1;
2751 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2752 ParseGlobalTypeAndValue(Val0) ||
2753 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2754 ParseGlobalTypeAndValue(Val1) ||
2755 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2757 if (Val0->getType() != Val1->getType())
2758 return Error(ID.Loc, "operands of constexpr must have same type");
2759 if (!Val0->getType()->isIntOrIntVectorTy())
2760 return Error(ID.Loc,
2761 "constexpr requires integer or integer vector operands");
2762 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2763 ID.Kind = ValID::t_Constant;
2767 case lltok::kw_getelementptr:
2768 case lltok::kw_shufflevector:
2769 case lltok::kw_insertelement:
2770 case lltok::kw_extractelement:
2771 case lltok::kw_select: {
2772 unsigned Opc = Lex.getUIntVal();
2773 SmallVector<Constant*, 16> Elts;
2774 bool InBounds = false;
2776 if (Opc == Instruction::GetElementPtr)
2777 InBounds = EatIfPresent(lltok::kw_inbounds);
2778 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2779 ParseGlobalValueVector(Elts) ||
2780 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2783 if (Opc == Instruction::GetElementPtr) {
2784 if (Elts.size() == 0 ||
2785 !Elts[0]->getType()->getScalarType()->isPointerTy())
2786 return Error(ID.Loc, "getelementptr requires pointer operand");
2788 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2789 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2790 return Error(ID.Loc, "invalid indices for getelementptr");
2791 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2793 } else if (Opc == Instruction::Select) {
2794 if (Elts.size() != 3)
2795 return Error(ID.Loc, "expected three operands to select");
2796 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2798 return Error(ID.Loc, Reason);
2799 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2800 } else if (Opc == Instruction::ShuffleVector) {
2801 if (Elts.size() != 3)
2802 return Error(ID.Loc, "expected three operands to shufflevector");
2803 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2804 return Error(ID.Loc, "invalid operands to shufflevector");
2806 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2807 } else if (Opc == Instruction::ExtractElement) {
2808 if (Elts.size() != 2)
2809 return Error(ID.Loc, "expected two operands to extractelement");
2810 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2811 return Error(ID.Loc, "invalid extractelement operands");
2812 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2814 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2815 if (Elts.size() != 3)
2816 return Error(ID.Loc, "expected three operands to insertelement");
2817 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2818 return Error(ID.Loc, "invalid insertelement operands");
2820 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2823 ID.Kind = ValID::t_Constant;
2832 /// ParseGlobalValue - Parse a global value with the specified type.
2833 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2837 bool Parsed = ParseValID(ID) ||
2838 ConvertValIDToValue(Ty, ID, V, nullptr);
2839 if (V && !(C = dyn_cast<Constant>(V)))
2840 return Error(ID.Loc, "global values must be constants");
2844 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2846 return ParseType(Ty) ||
2847 ParseGlobalValue(Ty, V);
2850 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2853 LocTy KwLoc = Lex.getLoc();
2854 if (!EatIfPresent(lltok::kw_comdat))
2857 if (EatIfPresent(lltok::lparen)) {
2858 if (Lex.getKind() != lltok::ComdatVar)
2859 return TokError("expected comdat variable");
2860 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2862 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2865 if (GlobalName.empty())
2866 return TokError("comdat cannot be unnamed");
2867 C = getComdat(GlobalName, KwLoc);
2873 /// ParseGlobalValueVector
2875 /// ::= TypeAndValue (',' TypeAndValue)*
2876 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2878 if (Lex.getKind() == lltok::rbrace ||
2879 Lex.getKind() == lltok::rsquare ||
2880 Lex.getKind() == lltok::greater ||
2881 Lex.getKind() == lltok::rparen)
2885 if (ParseGlobalTypeAndValue(C)) return true;
2888 while (EatIfPresent(lltok::comma)) {
2889 if (ParseGlobalTypeAndValue(C)) return true;
2896 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2897 SmallVector<Metadata *, 16> Elts;
2898 if (ParseMDNodeVector(Elts))
2901 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2908 /// ::= !MDLocation(...)
2909 bool LLParser::ParseMDNode(MDNode *&N) {
2910 if (Lex.getKind() == lltok::MetadataVar)
2911 return ParseSpecializedMDNode(N);
2913 return ParseToken(lltok::exclaim, "expected '!' here") ||
2917 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2919 if (Lex.getKind() == lltok::lbrace)
2920 return ParseMDTuple(N);
2923 return ParseMDNodeID(N);
2928 /// Structure to represent an optional metadata field.
2929 template <class FieldTy> struct MDFieldImpl {
2930 typedef MDFieldImpl ImplTy;
2934 void assign(FieldTy Val) {
2936 this->Val = std::move(Val);
2939 explicit MDFieldImpl(FieldTy Default)
2940 : Val(std::move(Default)), Seen(false) {}
2942 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
2945 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
2946 : ImplTy(Default), Max(Max) {}
2948 struct LineField : public MDUnsignedField {
2949 LineField() : MDUnsignedField(0, UINT32_MAX) {}
2951 struct ColumnField : public MDUnsignedField {
2952 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
2954 struct DwarfTagField : public MDUnsignedField {
2955 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
2957 struct MDField : public MDFieldImpl<Metadata *> {
2958 MDField() : ImplTy(nullptr) {}
2960 struct MDStringField : public MDFieldImpl<std::string> {
2961 MDStringField() : ImplTy(std::string()) {}
2963 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
2964 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
2972 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
2973 MDUnsignedField &Result) {
2974 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2975 return TokError("expected unsigned integer");
2977 auto &U = Lex.getAPSIntVal();
2978 if (U.ugt(Result.Max))
2979 return TokError("value for '" + Name + "' too large, limit is " +
2981 Result.assign(U.getZExtValue());
2982 assert(Result.Val <= Result.Max && "Expected value in range");
2988 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
2989 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
2992 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
2993 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
2997 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
2998 if (Lex.getKind() == lltok::APSInt)
2999 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3001 if (Lex.getKind() != lltok::DwarfTag)
3002 return TokError("expected DWARF tag");
3004 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3005 if (Tag == dwarf::DW_TAG_invalid)
3006 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3007 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3015 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3017 if (ParseMetadata(MD, nullptr))
3025 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3027 if (ParseStringConstant(S))
3030 Result.assign(std::move(S));
3035 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3036 SmallVector<Metadata *, 4> MDs;
3037 if (ParseMDNodeVector(MDs))
3040 Result.assign(std::move(MDs));
3044 } // end namespace llvm
3046 template <class ParserTy>
3047 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3049 if (Lex.getKind() != lltok::LabelStr)
3050 return TokError("expected field label here");
3054 } while (EatIfPresent(lltok::comma));
3059 template <class ParserTy>
3060 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3061 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3064 if (ParseToken(lltok::lparen, "expected '(' here"))
3066 if (Lex.getKind() != lltok::rparen)
3067 if (ParseMDFieldsImplBody(parseField))
3070 ClosingLoc = Lex.getLoc();
3071 return ParseToken(lltok::rparen, "expected ')' here");
3074 template <class FieldTy>
3075 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3077 return TokError("field '" + Name + "' cannot be specified more than once");
3079 LocTy Loc = Lex.getLoc();
3081 return ParseMDField(Loc, Name, Result);
3084 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3085 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3086 #define DISPATCH_TO_PARSER(CLASS) \
3087 if (Lex.getStrVal() == #CLASS) \
3088 return Parse##CLASS(N, IsDistinct);
3090 DISPATCH_TO_PARSER(MDLocation);
3091 DISPATCH_TO_PARSER(GenericDebugNode);
3092 #undef DISPATCH_TO_PARSER
3094 return TokError("expected metadata type");
3097 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3098 #define NOP_FIELD(NAME, TYPE, INIT)
3099 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3101 return Error(ClosingLoc, "missing required field '" #NAME "'");
3102 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3103 if (Lex.getStrVal() == #NAME) \
3104 return ParseMDField(#NAME, NAME);
3105 #define PARSE_MD_FIELDS() \
3106 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3109 if (ParseMDFieldsImpl([&]() -> bool { \
3110 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3111 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3114 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3116 #define GET_OR_DISTINCT(CLASS, ARGS) \
3117 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3119 /// ParseMDLocationFields:
3120 /// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3121 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3122 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3123 OPTIONAL(line, LineField, ); \
3124 OPTIONAL(column, ColumnField, ); \
3125 REQUIRED(scope, MDField, ); \
3126 OPTIONAL(inlinedAt, MDField, );
3128 #undef VISIT_MD_FIELDS
3130 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3131 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3135 /// ParseGenericDebugNode:
3136 /// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3137 bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3138 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3139 REQUIRED(tag, DwarfTagField, ); \
3140 OPTIONAL(header, MDStringField, ); \
3141 OPTIONAL(operands, MDFieldList, );
3143 #undef VISIT_MD_FIELDS
3145 Result = GET_OR_DISTINCT(GenericDebugNode,
3146 (Context, tag.Val, header.Val, operands.Val));
3149 #undef PARSE_MD_FIELD
3151 #undef REQUIRE_FIELD
3152 #undef DECLARE_FIELD
3154 /// ParseMetadataAsValue
3155 /// ::= metadata i32 %local
3156 /// ::= metadata i32 @global
3157 /// ::= metadata i32 7
3159 /// ::= metadata !{...}
3160 /// ::= metadata !"string"
3161 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3162 // Note: the type 'metadata' has already been parsed.
3164 if (ParseMetadata(MD, &PFS))
3167 V = MetadataAsValue::get(Context, MD);
3171 /// ParseValueAsMetadata
3175 bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
3178 if (ParseType(Ty, "expected metadata operand", Loc))
3180 if (Ty->isMetadataTy())
3181 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3184 if (ParseValue(Ty, V, PFS))
3187 MD = ValueAsMetadata::get(V);
3198 /// ::= !MDLocation(...)
3199 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3200 if (Lex.getKind() == lltok::MetadataVar) {
3202 if (ParseSpecializedMDNode(N))
3210 if (Lex.getKind() != lltok::exclaim)
3211 return ParseValueAsMetadata(MD, PFS);
3214 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3218 // ::= '!' STRINGCONSTANT
3219 if (Lex.getKind() == lltok::StringConstant) {
3221 if (ParseMDString(S))
3231 if (ParseMDNodeTail(N))
3238 //===----------------------------------------------------------------------===//
3239 // Function Parsing.
3240 //===----------------------------------------------------------------------===//
3242 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3243 PerFunctionState *PFS) {
3244 if (Ty->isFunctionTy())
3245 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3248 case ValID::t_LocalID:
3249 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3250 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3251 return V == nullptr;
3252 case ValID::t_LocalName:
3253 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3254 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3255 return V == nullptr;
3256 case ValID::t_InlineAsm: {
3257 PointerType *PTy = dyn_cast<PointerType>(Ty);
3259 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3260 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3261 return Error(ID.Loc, "invalid type for inline asm constraint string");
3262 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3263 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3266 case ValID::t_GlobalName:
3267 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3268 return V == nullptr;
3269 case ValID::t_GlobalID:
3270 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3271 return V == nullptr;
3272 case ValID::t_APSInt:
3273 if (!Ty->isIntegerTy())
3274 return Error(ID.Loc, "integer constant must have integer type");
3275 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3276 V = ConstantInt::get(Context, ID.APSIntVal);
3278 case ValID::t_APFloat:
3279 if (!Ty->isFloatingPointTy() ||
3280 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3281 return Error(ID.Loc, "floating point constant invalid for type");
3283 // The lexer has no type info, so builds all half, float, and double FP
3284 // constants as double. Fix this here. Long double does not need this.
3285 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3288 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3290 else if (Ty->isFloatTy())
3291 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3294 V = ConstantFP::get(Context, ID.APFloatVal);
3296 if (V->getType() != Ty)
3297 return Error(ID.Loc, "floating point constant does not have type '" +
3298 getTypeString(Ty) + "'");
3302 if (!Ty->isPointerTy())
3303 return Error(ID.Loc, "null must be a pointer type");
3304 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3306 case ValID::t_Undef:
3307 // FIXME: LabelTy should not be a first-class type.
3308 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3309 return Error(ID.Loc, "invalid type for undef constant");
3310 V = UndefValue::get(Ty);
3312 case ValID::t_EmptyArray:
3313 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3314 return Error(ID.Loc, "invalid empty array initializer");
3315 V = UndefValue::get(Ty);
3318 // FIXME: LabelTy should not be a first-class type.
3319 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3320 return Error(ID.Loc, "invalid type for null constant");
3321 V = Constant::getNullValue(Ty);
3323 case ValID::t_Constant:
3324 if (ID.ConstantVal->getType() != Ty)
3325 return Error(ID.Loc, "constant expression type mismatch");
3329 case ValID::t_ConstantStruct:
3330 case ValID::t_PackedConstantStruct:
3331 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3332 if (ST->getNumElements() != ID.UIntVal)
3333 return Error(ID.Loc,
3334 "initializer with struct type has wrong # elements");
3335 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3336 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3338 // Verify that the elements are compatible with the structtype.
3339 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3340 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3341 return Error(ID.Loc, "element " + Twine(i) +
3342 " of struct initializer doesn't match struct element type");
3344 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3347 return Error(ID.Loc, "constant expression type mismatch");
3350 llvm_unreachable("Invalid ValID");
3353 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3356 return ParseValID(ID, PFS) ||
3357 ConvertValIDToValue(Ty, ID, V, PFS);
3360 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3362 return ParseType(Ty) ||
3363 ParseValue(Ty, V, PFS);
3366 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3367 PerFunctionState &PFS) {
3370 if (ParseTypeAndValue(V, PFS)) return true;
3371 if (!isa<BasicBlock>(V))
3372 return Error(Loc, "expected a basic block");
3373 BB = cast<BasicBlock>(V);
3379 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3380 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3381 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3382 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3383 // Parse the linkage.
3384 LocTy LinkageLoc = Lex.getLoc();
3387 unsigned Visibility;
3388 unsigned DLLStorageClass;
3389 AttrBuilder RetAttrs;
3391 Type *RetType = nullptr;
3392 LocTy RetTypeLoc = Lex.getLoc();
3393 if (ParseOptionalLinkage(Linkage) ||
3394 ParseOptionalVisibility(Visibility) ||
3395 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3396 ParseOptionalCallingConv(CC) ||
3397 ParseOptionalReturnAttrs(RetAttrs) ||
3398 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3401 // Verify that the linkage is ok.
3402 switch ((GlobalValue::LinkageTypes)Linkage) {
3403 case GlobalValue::ExternalLinkage:
3404 break; // always ok.
3405 case GlobalValue::ExternalWeakLinkage:
3407 return Error(LinkageLoc, "invalid linkage for function definition");
3409 case GlobalValue::PrivateLinkage:
3410 case GlobalValue::InternalLinkage:
3411 case GlobalValue::AvailableExternallyLinkage:
3412 case GlobalValue::LinkOnceAnyLinkage:
3413 case GlobalValue::LinkOnceODRLinkage:
3414 case GlobalValue::WeakAnyLinkage:
3415 case GlobalValue::WeakODRLinkage:
3417 return Error(LinkageLoc, "invalid linkage for function declaration");
3419 case GlobalValue::AppendingLinkage:
3420 case GlobalValue::CommonLinkage:
3421 return Error(LinkageLoc, "invalid function linkage type");
3424 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3425 return Error(LinkageLoc,
3426 "symbol with local linkage must have default visibility");
3428 if (!FunctionType::isValidReturnType(RetType))
3429 return Error(RetTypeLoc, "invalid function return type");
3431 LocTy NameLoc = Lex.getLoc();
3433 std::string FunctionName;
3434 if (Lex.getKind() == lltok::GlobalVar) {
3435 FunctionName = Lex.getStrVal();
3436 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3437 unsigned NameID = Lex.getUIntVal();
3439 if (NameID != NumberedVals.size())
3440 return TokError("function expected to be numbered '%" +
3441 Twine(NumberedVals.size()) + "'");
3443 return TokError("expected function name");
3448 if (Lex.getKind() != lltok::lparen)
3449 return TokError("expected '(' in function argument list");
3451 SmallVector<ArgInfo, 8> ArgList;
3453 AttrBuilder FuncAttrs;
3454 std::vector<unsigned> FwdRefAttrGrps;
3456 std::string Section;
3460 LocTy UnnamedAddrLoc;
3461 Constant *Prefix = nullptr;
3462 Constant *Prologue = nullptr;
3465 if (ParseArgumentList(ArgList, isVarArg) ||
3466 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3468 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3470 (EatIfPresent(lltok::kw_section) &&
3471 ParseStringConstant(Section)) ||
3472 parseOptionalComdat(FunctionName, C) ||
3473 ParseOptionalAlignment(Alignment) ||
3474 (EatIfPresent(lltok::kw_gc) &&
3475 ParseStringConstant(GC)) ||
3476 (EatIfPresent(lltok::kw_prefix) &&
3477 ParseGlobalTypeAndValue(Prefix)) ||
3478 (EatIfPresent(lltok::kw_prologue) &&
3479 ParseGlobalTypeAndValue(Prologue)))
3482 if (FuncAttrs.contains(Attribute::Builtin))
3483 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3485 // If the alignment was parsed as an attribute, move to the alignment field.
3486 if (FuncAttrs.hasAlignmentAttr()) {
3487 Alignment = FuncAttrs.getAlignment();
3488 FuncAttrs.removeAttribute(Attribute::Alignment);
3491 // Okay, if we got here, the function is syntactically valid. Convert types
3492 // and do semantic checks.
3493 std::vector<Type*> ParamTypeList;
3494 SmallVector<AttributeSet, 8> Attrs;
3496 if (RetAttrs.hasAttributes())
3497 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3498 AttributeSet::ReturnIndex,
3501 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3502 ParamTypeList.push_back(ArgList[i].Ty);
3503 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3504 AttrBuilder B(ArgList[i].Attrs, i + 1);
3505 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3509 if (FuncAttrs.hasAttributes())
3510 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3511 AttributeSet::FunctionIndex,
3514 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3516 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3517 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3520 FunctionType::get(RetType, ParamTypeList, isVarArg);
3521 PointerType *PFT = PointerType::getUnqual(FT);
3524 if (!FunctionName.empty()) {
3525 // If this was a definition of a forward reference, remove the definition
3526 // from the forward reference table and fill in the forward ref.
3527 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3528 ForwardRefVals.find(FunctionName);
3529 if (FRVI != ForwardRefVals.end()) {
3530 Fn = M->getFunction(FunctionName);
3532 return Error(FRVI->second.second, "invalid forward reference to "
3533 "function as global value!");
3534 if (Fn->getType() != PFT)
3535 return Error(FRVI->second.second, "invalid forward reference to "
3536 "function '" + FunctionName + "' with wrong type!");
3538 ForwardRefVals.erase(FRVI);
3539 } else if ((Fn = M->getFunction(FunctionName))) {
3540 // Reject redefinitions.
3541 return Error(NameLoc, "invalid redefinition of function '" +
3542 FunctionName + "'");
3543 } else if (M->getNamedValue(FunctionName)) {
3544 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3548 // If this is a definition of a forward referenced function, make sure the
3550 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3551 = ForwardRefValIDs.find(NumberedVals.size());
3552 if (I != ForwardRefValIDs.end()) {
3553 Fn = cast<Function>(I->second.first);
3554 if (Fn->getType() != PFT)
3555 return Error(NameLoc, "type of definition and forward reference of '@" +
3556 Twine(NumberedVals.size()) + "' disagree");
3557 ForwardRefValIDs.erase(I);
3562 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3563 else // Move the forward-reference to the correct spot in the module.
3564 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3566 if (FunctionName.empty())
3567 NumberedVals.push_back(Fn);
3569 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3570 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3571 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3572 Fn->setCallingConv(CC);
3573 Fn->setAttributes(PAL);
3574 Fn->setUnnamedAddr(UnnamedAddr);
3575 Fn->setAlignment(Alignment);
3576 Fn->setSection(Section);
3578 if (!GC.empty()) Fn->setGC(GC.c_str());
3579 Fn->setPrefixData(Prefix);
3580 Fn->setPrologueData(Prologue);
3581 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3583 // Add all of the arguments we parsed to the function.
3584 Function::arg_iterator ArgIt = Fn->arg_begin();
3585 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3586 // If the argument has a name, insert it into the argument symbol table.
3587 if (ArgList[i].Name.empty()) continue;
3589 // Set the name, if it conflicted, it will be auto-renamed.
3590 ArgIt->setName(ArgList[i].Name);
3592 if (ArgIt->getName() != ArgList[i].Name)
3593 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3594 ArgList[i].Name + "'");
3600 // Check the declaration has no block address forward references.
3602 if (FunctionName.empty()) {
3603 ID.Kind = ValID::t_GlobalID;
3604 ID.UIntVal = NumberedVals.size() - 1;
3606 ID.Kind = ValID::t_GlobalName;
3607 ID.StrVal = FunctionName;
3609 auto Blocks = ForwardRefBlockAddresses.find(ID);
3610 if (Blocks != ForwardRefBlockAddresses.end())
3611 return Error(Blocks->first.Loc,
3612 "cannot take blockaddress inside a declaration");
3616 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3618 if (FunctionNumber == -1) {
3619 ID.Kind = ValID::t_GlobalName;
3620 ID.StrVal = F.getName();
3622 ID.Kind = ValID::t_GlobalID;
3623 ID.UIntVal = FunctionNumber;
3626 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3627 if (Blocks == P.ForwardRefBlockAddresses.end())
3630 for (const auto &I : Blocks->second) {
3631 const ValID &BBID = I.first;
3632 GlobalValue *GV = I.second;
3634 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3635 "Expected local id or name");
3637 if (BBID.Kind == ValID::t_LocalName)
3638 BB = GetBB(BBID.StrVal, BBID.Loc);
3640 BB = GetBB(BBID.UIntVal, BBID.Loc);
3642 return P.Error(BBID.Loc, "referenced value is not a basic block");
3644 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3645 GV->eraseFromParent();
3648 P.ForwardRefBlockAddresses.erase(Blocks);
3652 /// ParseFunctionBody
3653 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
3654 bool LLParser::ParseFunctionBody(Function &Fn) {
3655 if (Lex.getKind() != lltok::lbrace)
3656 return TokError("expected '{' in function body");
3657 Lex.Lex(); // eat the {.
3659 int FunctionNumber = -1;
3660 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3662 PerFunctionState PFS(*this, Fn, FunctionNumber);
3664 // Resolve block addresses and allow basic blocks to be forward-declared
3665 // within this function.
3666 if (PFS.resolveForwardRefBlockAddresses())
3668 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3670 // We need at least one basic block.
3671 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
3672 return TokError("function body requires at least one basic block");
3674 while (Lex.getKind() != lltok::rbrace &&
3675 Lex.getKind() != lltok::kw_uselistorder)
3676 if (ParseBasicBlock(PFS)) return true;
3678 while (Lex.getKind() != lltok::rbrace)
3679 if (ParseUseListOrder(&PFS))
3685 // Verify function is ok.
3686 return PFS.FinishFunction();
3690 /// ::= LabelStr? Instruction*
3691 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3692 // If this basic block starts out with a name, remember it.
3694 LocTy NameLoc = Lex.getLoc();
3695 if (Lex.getKind() == lltok::LabelStr) {
3696 Name = Lex.getStrVal();
3700 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3701 if (!BB) return true;
3703 std::string NameStr;
3705 // Parse the instructions in this block until we get a terminator.
3708 // This instruction may have three possibilities for a name: a) none
3709 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3710 LocTy NameLoc = Lex.getLoc();
3714 if (Lex.getKind() == lltok::LocalVarID) {
3715 NameID = Lex.getUIntVal();
3717 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3719 } else if (Lex.getKind() == lltok::LocalVar) {
3720 NameStr = Lex.getStrVal();
3722 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3726 switch (ParseInstruction(Inst, BB, PFS)) {
3727 default: llvm_unreachable("Unknown ParseInstruction result!");
3728 case InstError: return true;
3730 BB->getInstList().push_back(Inst);
3732 // With a normal result, we check to see if the instruction is followed by
3733 // a comma and metadata.
3734 if (EatIfPresent(lltok::comma))
3735 if (ParseInstructionMetadata(Inst, &PFS))
3738 case InstExtraComma:
3739 BB->getInstList().push_back(Inst);
3741 // If the instruction parser ate an extra comma at the end of it, it
3742 // *must* be followed by metadata.
3743 if (ParseInstructionMetadata(Inst, &PFS))
3748 // Set the name on the instruction.
3749 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3750 } while (!isa<TerminatorInst>(Inst));
3755 //===----------------------------------------------------------------------===//
3756 // Instruction Parsing.
3757 //===----------------------------------------------------------------------===//
3759 /// ParseInstruction - Parse one of the many different instructions.
3761 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3762 PerFunctionState &PFS) {
3763 lltok::Kind Token = Lex.getKind();
3764 if (Token == lltok::Eof)
3765 return TokError("found end of file when expecting more instructions");
3766 LocTy Loc = Lex.getLoc();
3767 unsigned KeywordVal = Lex.getUIntVal();
3768 Lex.Lex(); // Eat the keyword.
3771 default: return Error(Loc, "expected instruction opcode");
3772 // Terminator Instructions.
3773 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3774 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3775 case lltok::kw_br: return ParseBr(Inst, PFS);
3776 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3777 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3778 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3779 case lltok::kw_resume: return ParseResume(Inst, PFS);
3780 // Binary Operators.
3784 case lltok::kw_shl: {
3785 bool NUW = EatIfPresent(lltok::kw_nuw);
3786 bool NSW = EatIfPresent(lltok::kw_nsw);
3787 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3789 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3791 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3792 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3795 case lltok::kw_fadd:
3796 case lltok::kw_fsub:
3797 case lltok::kw_fmul:
3798 case lltok::kw_fdiv:
3799 case lltok::kw_frem: {
3800 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3801 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3805 Inst->setFastMathFlags(FMF);
3809 case lltok::kw_sdiv:
3810 case lltok::kw_udiv:
3811 case lltok::kw_lshr:
3812 case lltok::kw_ashr: {
3813 bool Exact = EatIfPresent(lltok::kw_exact);
3815 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3816 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3820 case lltok::kw_urem:
3821 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3824 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3825 case lltok::kw_icmp:
3826 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3828 case lltok::kw_trunc:
3829 case lltok::kw_zext:
3830 case lltok::kw_sext:
3831 case lltok::kw_fptrunc:
3832 case lltok::kw_fpext:
3833 case lltok::kw_bitcast:
3834 case lltok::kw_addrspacecast:
3835 case lltok::kw_uitofp:
3836 case lltok::kw_sitofp:
3837 case lltok::kw_fptoui:
3838 case lltok::kw_fptosi:
3839 case lltok::kw_inttoptr:
3840 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3842 case lltok::kw_select: return ParseSelect(Inst, PFS);
3843 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3844 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3845 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3846 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3847 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3848 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3850 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3851 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3852 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3854 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3855 case lltok::kw_load: return ParseLoad(Inst, PFS);
3856 case lltok::kw_store: return ParseStore(Inst, PFS);
3857 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3858 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3859 case lltok::kw_fence: return ParseFence(Inst, PFS);
3860 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3861 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3862 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3866 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3867 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3868 if (Opc == Instruction::FCmp) {
3869 switch (Lex.getKind()) {
3870 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3871 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3872 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3873 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3874 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3875 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3876 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3877 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3878 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3879 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3880 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3881 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3882 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3883 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3884 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3885 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3886 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3889 switch (Lex.getKind()) {
3890 default: return TokError("expected icmp predicate (e.g. 'eq')");
3891 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3892 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3893 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3894 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3895 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3896 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3897 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3898 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3899 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3900 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3907 //===----------------------------------------------------------------------===//
3908 // Terminator Instructions.
3909 //===----------------------------------------------------------------------===//
3911 /// ParseRet - Parse a return instruction.
3912 /// ::= 'ret' void (',' !dbg, !1)*
3913 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3914 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3915 PerFunctionState &PFS) {
3916 SMLoc TypeLoc = Lex.getLoc();
3918 if (ParseType(Ty, true /*void allowed*/)) return true;
3920 Type *ResType = PFS.getFunction().getReturnType();
3922 if (Ty->isVoidTy()) {
3923 if (!ResType->isVoidTy())
3924 return Error(TypeLoc, "value doesn't match function result type '" +
3925 getTypeString(ResType) + "'");
3927 Inst = ReturnInst::Create(Context);
3932 if (ParseValue(Ty, RV, PFS)) return true;
3934 if (ResType != RV->getType())
3935 return Error(TypeLoc, "value doesn't match function result type '" +
3936 getTypeString(ResType) + "'");
3938 Inst = ReturnInst::Create(Context, RV);
3944 /// ::= 'br' TypeAndValue
3945 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3946 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3949 BasicBlock *Op1, *Op2;
3950 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3952 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3953 Inst = BranchInst::Create(BB);
3957 if (Op0->getType() != Type::getInt1Ty(Context))
3958 return Error(Loc, "branch condition must have 'i1' type");
3960 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3961 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3962 ParseToken(lltok::comma, "expected ',' after true destination") ||
3963 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3966 Inst = BranchInst::Create(Op1, Op2, Op0);
3972 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3974 /// ::= (TypeAndValue ',' TypeAndValue)*
3975 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3976 LocTy CondLoc, BBLoc;
3978 BasicBlock *DefaultBB;
3979 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3980 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3981 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3982 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3985 if (!Cond->getType()->isIntegerTy())
3986 return Error(CondLoc, "switch condition must have integer type");
3988 // Parse the jump table pairs.
3989 SmallPtrSet<Value*, 32> SeenCases;
3990 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3991 while (Lex.getKind() != lltok::rsquare) {
3995 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3996 ParseToken(lltok::comma, "expected ',' after case value") ||
3997 ParseTypeAndBasicBlock(DestBB, PFS))
4000 if (!SeenCases.insert(Constant).second)
4001 return Error(CondLoc, "duplicate case value in switch");
4002 if (!isa<ConstantInt>(Constant))
4003 return Error(CondLoc, "case value is not a constant integer");
4005 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4008 Lex.Lex(); // Eat the ']'.
4010 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4011 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4012 SI->addCase(Table[i].first, Table[i].second);
4019 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4020 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4023 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4024 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4025 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4028 if (!Address->getType()->isPointerTy())
4029 return Error(AddrLoc, "indirectbr address must have pointer type");
4031 // Parse the destination list.
4032 SmallVector<BasicBlock*, 16> DestList;
4034 if (Lex.getKind() != lltok::rsquare) {
4036 if (ParseTypeAndBasicBlock(DestBB, PFS))
4038 DestList.push_back(DestBB);
4040 while (EatIfPresent(lltok::comma)) {
4041 if (ParseTypeAndBasicBlock(DestBB, PFS))
4043 DestList.push_back(DestBB);
4047 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4050 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4051 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4052 IBI->addDestination(DestList[i]);
4059 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4060 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4061 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4062 LocTy CallLoc = Lex.getLoc();
4063 AttrBuilder RetAttrs, FnAttrs;
4064 std::vector<unsigned> FwdRefAttrGrps;
4067 Type *RetType = nullptr;
4070 SmallVector<ParamInfo, 16> ArgList;
4072 BasicBlock *NormalBB, *UnwindBB;
4073 if (ParseOptionalCallingConv(CC) ||
4074 ParseOptionalReturnAttrs(RetAttrs) ||
4075 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4076 ParseValID(CalleeID) ||
4077 ParseParameterList(ArgList, PFS) ||
4078 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4080 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4081 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4082 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4083 ParseTypeAndBasicBlock(UnwindBB, PFS))
4086 // If RetType is a non-function pointer type, then this is the short syntax
4087 // for the call, which means that RetType is just the return type. Infer the
4088 // rest of the function argument types from the arguments that are present.
4089 PointerType *PFTy = nullptr;
4090 FunctionType *Ty = nullptr;
4091 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4092 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4093 // Pull out the types of all of the arguments...
4094 std::vector<Type*> ParamTypes;
4095 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4096 ParamTypes.push_back(ArgList[i].V->getType());
4098 if (!FunctionType::isValidReturnType(RetType))
4099 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4101 Ty = FunctionType::get(RetType, ParamTypes, false);
4102 PFTy = PointerType::getUnqual(Ty);
4105 // Look up the callee.
4107 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4109 // Set up the Attribute for the function.
4110 SmallVector<AttributeSet, 8> Attrs;
4111 if (RetAttrs.hasAttributes())
4112 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4113 AttributeSet::ReturnIndex,
4116 SmallVector<Value*, 8> Args;
4118 // Loop through FunctionType's arguments and ensure they are specified
4119 // correctly. Also, gather any parameter attributes.
4120 FunctionType::param_iterator I = Ty->param_begin();
4121 FunctionType::param_iterator E = Ty->param_end();
4122 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4123 Type *ExpectedTy = nullptr;
4126 } else if (!Ty->isVarArg()) {
4127 return Error(ArgList[i].Loc, "too many arguments specified");
4130 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4131 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4132 getTypeString(ExpectedTy) + "'");
4133 Args.push_back(ArgList[i].V);
4134 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4135 AttrBuilder B(ArgList[i].Attrs, i + 1);
4136 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4141 return Error(CallLoc, "not enough parameters specified for call");
4143 if (FnAttrs.hasAttributes())
4144 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4145 AttributeSet::FunctionIndex,
4148 // Finish off the Attribute and check them
4149 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4151 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4152 II->setCallingConv(CC);
4153 II->setAttributes(PAL);
4154 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4160 /// ::= 'resume' TypeAndValue
4161 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4162 Value *Exn; LocTy ExnLoc;
4163 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4166 ResumeInst *RI = ResumeInst::Create(Exn);
4171 //===----------------------------------------------------------------------===//
4172 // Binary Operators.
4173 //===----------------------------------------------------------------------===//
4176 /// ::= ArithmeticOps TypeAndValue ',' Value
4178 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4179 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4180 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4181 unsigned Opc, unsigned OperandType) {
4182 LocTy Loc; Value *LHS, *RHS;
4183 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4184 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4185 ParseValue(LHS->getType(), RHS, PFS))
4189 switch (OperandType) {
4190 default: llvm_unreachable("Unknown operand type!");
4191 case 0: // int or FP.
4192 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4193 LHS->getType()->isFPOrFPVectorTy();
4195 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4196 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4200 return Error(Loc, "invalid operand type for instruction");
4202 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4207 /// ::= ArithmeticOps TypeAndValue ',' Value {
4208 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4210 LocTy Loc; Value *LHS, *RHS;
4211 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4212 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4213 ParseValue(LHS->getType(), RHS, PFS))
4216 if (!LHS->getType()->isIntOrIntVectorTy())
4217 return Error(Loc,"instruction requires integer or integer vector operands");
4219 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4225 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4226 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4227 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4229 // Parse the integer/fp comparison predicate.
4233 if (ParseCmpPredicate(Pred, Opc) ||
4234 ParseTypeAndValue(LHS, Loc, PFS) ||
4235 ParseToken(lltok::comma, "expected ',' after compare value") ||
4236 ParseValue(LHS->getType(), RHS, PFS))
4239 if (Opc == Instruction::FCmp) {
4240 if (!LHS->getType()->isFPOrFPVectorTy())
4241 return Error(Loc, "fcmp requires floating point operands");
4242 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4244 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4245 if (!LHS->getType()->isIntOrIntVectorTy() &&
4246 !LHS->getType()->getScalarType()->isPointerTy())
4247 return Error(Loc, "icmp requires integer operands");
4248 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4253 //===----------------------------------------------------------------------===//
4254 // Other Instructions.
4255 //===----------------------------------------------------------------------===//
4259 /// ::= CastOpc TypeAndValue 'to' Type
4260 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4264 Type *DestTy = nullptr;
4265 if (ParseTypeAndValue(Op, Loc, PFS) ||
4266 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4270 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4271 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4272 return Error(Loc, "invalid cast opcode for cast from '" +
4273 getTypeString(Op->getType()) + "' to '" +
4274 getTypeString(DestTy) + "'");
4276 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4281 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4282 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4284 Value *Op0, *Op1, *Op2;
4285 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4286 ParseToken(lltok::comma, "expected ',' after select condition") ||
4287 ParseTypeAndValue(Op1, PFS) ||
4288 ParseToken(lltok::comma, "expected ',' after select value") ||
4289 ParseTypeAndValue(Op2, PFS))
4292 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4293 return Error(Loc, Reason);
4295 Inst = SelectInst::Create(Op0, Op1, Op2);
4300 /// ::= 'va_arg' TypeAndValue ',' Type
4301 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4303 Type *EltTy = nullptr;
4305 if (ParseTypeAndValue(Op, PFS) ||
4306 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4307 ParseType(EltTy, TypeLoc))
4310 if (!EltTy->isFirstClassType())
4311 return Error(TypeLoc, "va_arg requires operand with first class type");
4313 Inst = new VAArgInst(Op, EltTy);
4317 /// ParseExtractElement
4318 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4319 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4322 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4323 ParseToken(lltok::comma, "expected ',' after extract value") ||
4324 ParseTypeAndValue(Op1, PFS))
4327 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4328 return Error(Loc, "invalid extractelement operands");
4330 Inst = ExtractElementInst::Create(Op0, Op1);
4334 /// ParseInsertElement
4335 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4336 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4338 Value *Op0, *Op1, *Op2;
4339 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4340 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4341 ParseTypeAndValue(Op1, PFS) ||
4342 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4343 ParseTypeAndValue(Op2, PFS))
4346 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4347 return Error(Loc, "invalid insertelement operands");
4349 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4353 /// ParseShuffleVector
4354 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4355 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4357 Value *Op0, *Op1, *Op2;
4358 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4359 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4360 ParseTypeAndValue(Op1, PFS) ||
4361 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4362 ParseTypeAndValue(Op2, PFS))
4365 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4366 return Error(Loc, "invalid shufflevector operands");
4368 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4373 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4374 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4375 Type *Ty = nullptr; LocTy TypeLoc;
4378 if (ParseType(Ty, TypeLoc) ||
4379 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4380 ParseValue(Ty, Op0, PFS) ||
4381 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4382 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4383 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4386 bool AteExtraComma = false;
4387 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4389 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4391 if (!EatIfPresent(lltok::comma))
4394 if (Lex.getKind() == lltok::MetadataVar) {
4395 AteExtraComma = true;
4399 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4400 ParseValue(Ty, Op0, PFS) ||
4401 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4402 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4403 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4407 if (!Ty->isFirstClassType())
4408 return Error(TypeLoc, "phi node must have first class type");
4410 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4411 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4412 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4414 return AteExtraComma ? InstExtraComma : InstNormal;
4418 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4420 /// ::= 'catch' TypeAndValue
4422 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4423 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4424 Type *Ty = nullptr; LocTy TyLoc;
4425 Value *PersFn; LocTy PersFnLoc;
4427 if (ParseType(Ty, TyLoc) ||
4428 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4429 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4432 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4433 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4435 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4436 LandingPadInst::ClauseType CT;
4437 if (EatIfPresent(lltok::kw_catch))
4438 CT = LandingPadInst::Catch;
4439 else if (EatIfPresent(lltok::kw_filter))
4440 CT = LandingPadInst::Filter;
4442 return TokError("expected 'catch' or 'filter' clause type");
4446 if (ParseTypeAndValue(V, VLoc, PFS)) {
4451 // A 'catch' type expects a non-array constant. A filter clause expects an
4453 if (CT == LandingPadInst::Catch) {
4454 if (isa<ArrayType>(V->getType()))
4455 Error(VLoc, "'catch' clause has an invalid type");
4457 if (!isa<ArrayType>(V->getType()))
4458 Error(VLoc, "'filter' clause has an invalid type");
4461 LP->addClause(cast<Constant>(V));
4469 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4470 /// ParameterList OptionalAttrs
4471 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4472 /// ParameterList OptionalAttrs
4473 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4474 /// ParameterList OptionalAttrs
4475 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4476 CallInst::TailCallKind TCK) {
4477 AttrBuilder RetAttrs, FnAttrs;
4478 std::vector<unsigned> FwdRefAttrGrps;
4481 Type *RetType = nullptr;
4484 SmallVector<ParamInfo, 16> ArgList;
4485 LocTy CallLoc = Lex.getLoc();
4487 if ((TCK != CallInst::TCK_None &&
4488 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4489 ParseOptionalCallingConv(CC) ||
4490 ParseOptionalReturnAttrs(RetAttrs) ||
4491 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4492 ParseValID(CalleeID) ||
4493 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4494 PFS.getFunction().isVarArg()) ||
4495 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4499 // If RetType is a non-function pointer type, then this is the short syntax
4500 // for the call, which means that RetType is just the return type. Infer the
4501 // rest of the function argument types from the arguments that are present.
4502 PointerType *PFTy = nullptr;
4503 FunctionType *Ty = nullptr;
4504 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4505 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4506 // Pull out the types of all of the arguments...
4507 std::vector<Type*> ParamTypes;
4508 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4509 ParamTypes.push_back(ArgList[i].V->getType());
4511 if (!FunctionType::isValidReturnType(RetType))
4512 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4514 Ty = FunctionType::get(RetType, ParamTypes, false);
4515 PFTy = PointerType::getUnqual(Ty);
4518 // Look up the callee.
4520 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4522 // Set up the Attribute for the function.
4523 SmallVector<AttributeSet, 8> Attrs;
4524 if (RetAttrs.hasAttributes())
4525 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4526 AttributeSet::ReturnIndex,
4529 SmallVector<Value*, 8> Args;
4531 // Loop through FunctionType's arguments and ensure they are specified
4532 // correctly. Also, gather any parameter attributes.
4533 FunctionType::param_iterator I = Ty->param_begin();
4534 FunctionType::param_iterator E = Ty->param_end();
4535 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4536 Type *ExpectedTy = nullptr;
4539 } else if (!Ty->isVarArg()) {
4540 return Error(ArgList[i].Loc, "too many arguments specified");
4543 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4544 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4545 getTypeString(ExpectedTy) + "'");
4546 Args.push_back(ArgList[i].V);
4547 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4548 AttrBuilder B(ArgList[i].Attrs, i + 1);
4549 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4554 return Error(CallLoc, "not enough parameters specified for call");
4556 if (FnAttrs.hasAttributes())
4557 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4558 AttributeSet::FunctionIndex,
4561 // Finish off the Attribute and check them
4562 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4564 CallInst *CI = CallInst::Create(Callee, Args);
4565 CI->setTailCallKind(TCK);
4566 CI->setCallingConv(CC);
4567 CI->setAttributes(PAL);
4568 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4573 //===----------------------------------------------------------------------===//
4574 // Memory Instructions.
4575 //===----------------------------------------------------------------------===//
4578 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4579 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4580 Value *Size = nullptr;
4582 unsigned Alignment = 0;
4585 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4587 if (ParseType(Ty)) return true;
4589 bool AteExtraComma = false;
4590 if (EatIfPresent(lltok::comma)) {
4591 if (Lex.getKind() == lltok::kw_align) {
4592 if (ParseOptionalAlignment(Alignment)) return true;
4593 } else if (Lex.getKind() == lltok::MetadataVar) {
4594 AteExtraComma = true;
4596 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4597 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4602 if (Size && !Size->getType()->isIntegerTy())
4603 return Error(SizeLoc, "element count must have integer type");
4605 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4606 AI->setUsedWithInAlloca(IsInAlloca);
4608 return AteExtraComma ? InstExtraComma : InstNormal;
4612 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4613 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4614 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4615 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4616 Value *Val; LocTy Loc;
4617 unsigned Alignment = 0;
4618 bool AteExtraComma = false;
4619 bool isAtomic = false;
4620 AtomicOrdering Ordering = NotAtomic;
4621 SynchronizationScope Scope = CrossThread;
4623 if (Lex.getKind() == lltok::kw_atomic) {
4628 bool isVolatile = false;
4629 if (Lex.getKind() == lltok::kw_volatile) {
4634 if (ParseTypeAndValue(Val, Loc, PFS) ||
4635 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4636 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4639 if (!Val->getType()->isPointerTy() ||
4640 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4641 return Error(Loc, "load operand must be a pointer to a first class type");
4642 if (isAtomic && !Alignment)
4643 return Error(Loc, "atomic load must have explicit non-zero alignment");
4644 if (Ordering == Release || Ordering == AcquireRelease)
4645 return Error(Loc, "atomic load cannot use Release ordering");
4647 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4648 return AteExtraComma ? InstExtraComma : InstNormal;
4653 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4654 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4655 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4656 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4657 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4658 unsigned Alignment = 0;
4659 bool AteExtraComma = false;
4660 bool isAtomic = false;
4661 AtomicOrdering Ordering = NotAtomic;
4662 SynchronizationScope Scope = CrossThread;
4664 if (Lex.getKind() == lltok::kw_atomic) {
4669 bool isVolatile = false;
4670 if (Lex.getKind() == lltok::kw_volatile) {
4675 if (ParseTypeAndValue(Val, Loc, PFS) ||
4676 ParseToken(lltok::comma, "expected ',' after store operand") ||
4677 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4678 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4679 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4682 if (!Ptr->getType()->isPointerTy())
4683 return Error(PtrLoc, "store operand must be a pointer");
4684 if (!Val->getType()->isFirstClassType())
4685 return Error(Loc, "store operand must be a first class value");
4686 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4687 return Error(Loc, "stored value and pointer type do not match");
4688 if (isAtomic && !Alignment)
4689 return Error(Loc, "atomic store must have explicit non-zero alignment");
4690 if (Ordering == Acquire || Ordering == AcquireRelease)
4691 return Error(Loc, "atomic store cannot use Acquire ordering");
4693 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4694 return AteExtraComma ? InstExtraComma : InstNormal;
4698 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4699 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4700 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4701 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4702 bool AteExtraComma = false;
4703 AtomicOrdering SuccessOrdering = NotAtomic;
4704 AtomicOrdering FailureOrdering = NotAtomic;
4705 SynchronizationScope Scope = CrossThread;
4706 bool isVolatile = false;
4707 bool isWeak = false;
4709 if (EatIfPresent(lltok::kw_weak))
4712 if (EatIfPresent(lltok::kw_volatile))
4715 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4716 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4717 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4718 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4719 ParseTypeAndValue(New, NewLoc, PFS) ||
4720 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4721 ParseOrdering(FailureOrdering))
4724 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4725 return TokError("cmpxchg cannot be unordered");
4726 if (SuccessOrdering < FailureOrdering)
4727 return TokError("cmpxchg must be at least as ordered on success as failure");
4728 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4729 return TokError("cmpxchg failure ordering cannot include release semantics");
4730 if (!Ptr->getType()->isPointerTy())
4731 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4732 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4733 return Error(CmpLoc, "compare value and pointer type do not match");
4734 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4735 return Error(NewLoc, "new value and pointer type do not match");
4736 if (!New->getType()->isIntegerTy())
4737 return Error(NewLoc, "cmpxchg operand must be an integer");
4738 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4739 if (Size < 8 || (Size & (Size - 1)))
4740 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4743 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4744 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4745 CXI->setVolatile(isVolatile);
4746 CXI->setWeak(isWeak);
4748 return AteExtraComma ? InstExtraComma : InstNormal;
4752 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4753 /// 'singlethread'? AtomicOrdering
4754 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4755 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4756 bool AteExtraComma = false;
4757 AtomicOrdering Ordering = NotAtomic;
4758 SynchronizationScope Scope = CrossThread;
4759 bool isVolatile = false;
4760 AtomicRMWInst::BinOp Operation;
4762 if (EatIfPresent(lltok::kw_volatile))
4765 switch (Lex.getKind()) {
4766 default: return TokError("expected binary operation in atomicrmw");
4767 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4768 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4769 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4770 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4771 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4772 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4773 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4774 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4775 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4776 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4777 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4779 Lex.Lex(); // Eat the operation.
4781 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4782 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4783 ParseTypeAndValue(Val, ValLoc, PFS) ||
4784 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4787 if (Ordering == Unordered)
4788 return TokError("atomicrmw cannot be unordered");
4789 if (!Ptr->getType()->isPointerTy())
4790 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4791 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4792 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4793 if (!Val->getType()->isIntegerTy())
4794 return Error(ValLoc, "atomicrmw operand must be an integer");
4795 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4796 if (Size < 8 || (Size & (Size - 1)))
4797 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4800 AtomicRMWInst *RMWI =
4801 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4802 RMWI->setVolatile(isVolatile);
4804 return AteExtraComma ? InstExtraComma : InstNormal;
4808 /// ::= 'fence' 'singlethread'? AtomicOrdering
4809 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4810 AtomicOrdering Ordering = NotAtomic;
4811 SynchronizationScope Scope = CrossThread;
4812 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4815 if (Ordering == Unordered)
4816 return TokError("fence cannot be unordered");
4817 if (Ordering == Monotonic)
4818 return TokError("fence cannot be monotonic");
4820 Inst = new FenceInst(Context, Ordering, Scope);
4824 /// ParseGetElementPtr
4825 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4826 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4827 Value *Ptr = nullptr;
4828 Value *Val = nullptr;
4831 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4833 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4835 Type *BaseType = Ptr->getType();
4836 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4837 if (!BasePointerType)
4838 return Error(Loc, "base of getelementptr must be a pointer");
4840 SmallVector<Value*, 16> Indices;
4841 bool AteExtraComma = false;
4842 while (EatIfPresent(lltok::comma)) {
4843 if (Lex.getKind() == lltok::MetadataVar) {
4844 AteExtraComma = true;
4847 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4848 if (!Val->getType()->getScalarType()->isIntegerTy())
4849 return Error(EltLoc, "getelementptr index must be an integer");
4850 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4851 return Error(EltLoc, "getelementptr index type missmatch");
4852 if (Val->getType()->isVectorTy()) {
4853 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4854 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4855 if (ValNumEl != PtrNumEl)
4856 return Error(EltLoc,
4857 "getelementptr vector index has a wrong number of elements");
4859 Indices.push_back(Val);
4862 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4863 return Error(Loc, "base element of getelementptr must be sized");
4865 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4866 return Error(Loc, "invalid getelementptr indices");
4867 Inst = GetElementPtrInst::Create(Ptr, Indices);
4869 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4870 return AteExtraComma ? InstExtraComma : InstNormal;
4873 /// ParseExtractValue
4874 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4875 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4876 Value *Val; LocTy Loc;
4877 SmallVector<unsigned, 4> Indices;
4879 if (ParseTypeAndValue(Val, Loc, PFS) ||
4880 ParseIndexList(Indices, AteExtraComma))
4883 if (!Val->getType()->isAggregateType())
4884 return Error(Loc, "extractvalue operand must be aggregate type");
4886 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4887 return Error(Loc, "invalid indices for extractvalue");
4888 Inst = ExtractValueInst::Create(Val, Indices);
4889 return AteExtraComma ? InstExtraComma : InstNormal;
4892 /// ParseInsertValue
4893 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4894 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4895 Value *Val0, *Val1; LocTy Loc0, Loc1;
4896 SmallVector<unsigned, 4> Indices;
4898 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4899 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4900 ParseTypeAndValue(Val1, Loc1, PFS) ||
4901 ParseIndexList(Indices, AteExtraComma))
4904 if (!Val0->getType()->isAggregateType())
4905 return Error(Loc0, "insertvalue operand must be aggregate type");
4907 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4908 return Error(Loc0, "invalid indices for insertvalue");
4909 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4910 return AteExtraComma ? InstExtraComma : InstNormal;
4913 //===----------------------------------------------------------------------===//
4914 // Embedded metadata.
4915 //===----------------------------------------------------------------------===//
4917 /// ParseMDNodeVector
4918 /// ::= { Element (',' Element)* }
4920 /// ::= 'null' | TypeAndValue
4921 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
4922 if (ParseToken(lltok::lbrace, "expected '{' here"))
4925 // Check for an empty list.
4926 if (EatIfPresent(lltok::rbrace))
4930 // Null is a special case since it is typeless.
4931 if (EatIfPresent(lltok::kw_null)) {
4932 Elts.push_back(nullptr);
4937 if (ParseMetadata(MD, nullptr))
4940 } while (EatIfPresent(lltok::comma));
4942 return ParseToken(lltok::rbrace, "expected end of metadata node");
4945 //===----------------------------------------------------------------------===//
4946 // Use-list order directives.
4947 //===----------------------------------------------------------------------===//
4948 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4951 return Error(Loc, "value has no uses");
4953 unsigned NumUses = 0;
4954 SmallDenseMap<const Use *, unsigned, 16> Order;
4955 for (const Use &U : V->uses()) {
4956 if (++NumUses > Indexes.size())
4958 Order[&U] = Indexes[NumUses - 1];
4961 return Error(Loc, "value only has one use");
4962 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4963 return Error(Loc, "wrong number of indexes, expected " +
4964 Twine(std::distance(V->use_begin(), V->use_end())));
4966 V->sortUseList([&](const Use &L, const Use &R) {
4967 return Order.lookup(&L) < Order.lookup(&R);
4972 /// ParseUseListOrderIndexes
4973 /// ::= '{' uint32 (',' uint32)+ '}'
4974 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4975 SMLoc Loc = Lex.getLoc();
4976 if (ParseToken(lltok::lbrace, "expected '{' here"))
4978 if (Lex.getKind() == lltok::rbrace)
4979 return Lex.Error("expected non-empty list of uselistorder indexes");
4981 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4982 // indexes should be distinct numbers in the range [0, size-1], and should
4984 unsigned Offset = 0;
4986 bool IsOrdered = true;
4987 assert(Indexes.empty() && "Expected empty order vector");
4990 if (ParseUInt32(Index))
4993 // Update consistency checks.
4994 Offset += Index - Indexes.size();
4995 Max = std::max(Max, Index);
4996 IsOrdered &= Index == Indexes.size();
4998 Indexes.push_back(Index);
4999 } while (EatIfPresent(lltok::comma));
5001 if (ParseToken(lltok::rbrace, "expected '}' here"))
5004 if (Indexes.size() < 2)
5005 return Error(Loc, "expected >= 2 uselistorder indexes");
5006 if (Offset != 0 || Max >= Indexes.size())
5007 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5009 return Error(Loc, "expected uselistorder indexes to change the order");
5014 /// ParseUseListOrder
5015 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5016 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5017 SMLoc Loc = Lex.getLoc();
5018 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5022 SmallVector<unsigned, 16> Indexes;
5023 if (ParseTypeAndValue(V, PFS) ||
5024 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5025 ParseUseListOrderIndexes(Indexes))
5028 return sortUseListOrder(V, Indexes, Loc);
5031 /// ParseUseListOrderBB
5032 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5033 bool LLParser::ParseUseListOrderBB() {
5034 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5035 SMLoc Loc = Lex.getLoc();
5039 SmallVector<unsigned, 16> Indexes;
5040 if (ParseValID(Fn) ||
5041 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5042 ParseValID(Label) ||
5043 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5044 ParseUseListOrderIndexes(Indexes))
5047 // Check the function.
5049 if (Fn.Kind == ValID::t_GlobalName)
5050 GV = M->getNamedValue(Fn.StrVal);
5051 else if (Fn.Kind == ValID::t_GlobalID)
5052 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5054 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5056 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5057 auto *F = dyn_cast<Function>(GV);
5059 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5060 if (F->isDeclaration())
5061 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5063 // Check the basic block.
5064 if (Label.Kind == ValID::t_LocalID)
5065 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5066 if (Label.Kind != ValID::t_LocalName)
5067 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5068 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5070 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5071 if (!isa<BasicBlock>(V))
5072 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5074 return sortUseListOrder(V, Indexes, Loc);