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/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SaveAndRestore.h"
28 #include "llvm/Support/raw_ostream.h"
31 static std::string getTypeString(Type *T) {
33 raw_string_ostream Tmp(Result);
38 /// Run: module ::= toplevelentity*
39 bool LLParser::Run() {
43 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
47 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
49 bool LLParser::ValidateEndOfModule() {
50 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
51 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
53 // Handle any function attribute group forward references.
54 for (std::map<Value*, std::vector<unsigned> >::iterator
55 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
58 std::vector<unsigned> &Vec = I->second;
61 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
63 B.merge(NumberedAttrBuilders[*VI]);
65 if (Function *Fn = dyn_cast<Function>(V)) {
66 AttributeSet AS = Fn->getAttributes();
67 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
68 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
69 AS.getFnAttributes());
73 // If the alignment was parsed as an attribute, move to the alignment
75 if (FnAttrs.hasAlignmentAttr()) {
76 Fn->setAlignment(FnAttrs.getAlignment());
77 FnAttrs.removeAttribute(Attribute::Alignment);
80 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
81 AttributeSet::get(Context,
82 AttributeSet::FunctionIndex,
84 Fn->setAttributes(AS);
85 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
86 AttributeSet AS = CI->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
91 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
92 AttributeSet::get(Context,
93 AttributeSet::FunctionIndex,
95 CI->setAttributes(AS);
96 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
97 AttributeSet AS = II->getAttributes();
98 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100 AS.getFnAttributes());
102 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
103 AttributeSet::get(Context,
104 AttributeSet::FunctionIndex,
106 II->setAttributes(AS);
108 llvm_unreachable("invalid object with forward attribute group reference");
112 // If there are entries in ForwardRefBlockAddresses at this point, the
113 // function was never defined.
114 if (!ForwardRefBlockAddresses.empty())
115 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
116 "expected function name in blockaddress");
118 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
119 if (NumberedTypes[i].second.isValid())
120 return Error(NumberedTypes[i].second,
121 "use of undefined type '%" + Twine(i) + "'");
123 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
124 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
125 if (I->second.second.isValid())
126 return Error(I->second.second,
127 "use of undefined type named '" + I->getKey() + "'");
129 if (!ForwardRefComdats.empty())
130 return Error(ForwardRefComdats.begin()->second,
131 "use of undefined comdat '$" +
132 ForwardRefComdats.begin()->first + "'");
134 if (!ForwardRefVals.empty())
135 return Error(ForwardRefVals.begin()->second.second,
136 "use of undefined value '@" + ForwardRefVals.begin()->first +
139 if (!ForwardRefValIDs.empty())
140 return Error(ForwardRefValIDs.begin()->second.second,
141 "use of undefined value '@" +
142 Twine(ForwardRefValIDs.begin()->first) + "'");
144 if (!ForwardRefMDNodes.empty())
145 return Error(ForwardRefMDNodes.begin()->second.second,
146 "use of undefined metadata '!" +
147 Twine(ForwardRefMDNodes.begin()->first) + "'");
149 // Resolve metadata cycles.
150 for (auto &N : NumberedMetadata)
151 if (auto *U = cast_or_null<UniquableMDNode>(N))
154 // Look for intrinsic functions and CallInst that need to be upgraded
155 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
156 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
158 UpgradeDebugInfo(*M);
163 //===----------------------------------------------------------------------===//
164 // Top-Level Entities
165 //===----------------------------------------------------------------------===//
167 bool LLParser::ParseTopLevelEntities() {
169 switch (Lex.getKind()) {
170 default: return TokError("expected top-level entity");
171 case lltok::Eof: return false;
172 case lltok::kw_declare: if (ParseDeclare()) return true; break;
173 case lltok::kw_define: if (ParseDefine()) return true; break;
174 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
175 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
176 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
177 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
178 case lltok::LocalVar: if (ParseNamedType()) return true; break;
179 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
180 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
181 case lltok::ComdatVar: if (parseComdat()) return true; break;
182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
183 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
188 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
189 // ('constant'|'global') ...
190 case lltok::kw_private: // OptionalLinkage
191 case lltok::kw_internal: // OptionalLinkage
192 case lltok::kw_weak: // OptionalLinkage
193 case lltok::kw_weak_odr: // OptionalLinkage
194 case lltok::kw_linkonce: // OptionalLinkage
195 case lltok::kw_linkonce_odr: // OptionalLinkage
196 case lltok::kw_appending: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: // OptionalLinkage
200 case lltok::kw_default: // OptionalVisibility
201 case lltok::kw_hidden: // OptionalVisibility
202 case lltok::kw_protected: // OptionalVisibility
203 case lltok::kw_dllimport: // OptionalDLLStorageClass
204 case lltok::kw_dllexport: // OptionalDLLStorageClass
205 case lltok::kw_thread_local: // OptionalThreadLocal
206 case lltok::kw_addrspace: // OptionalAddrSpace
207 case lltok::kw_constant: // GlobalType
208 case lltok::kw_global: { // GlobalType
209 unsigned Linkage, Visibility, DLLStorageClass;
211 GlobalVariable::ThreadLocalMode TLM;
213 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
214 ParseOptionalVisibility(Visibility) ||
215 ParseOptionalDLLStorageClass(DLLStorageClass) ||
216 ParseOptionalThreadLocal(TLM) ||
217 parseOptionalUnnamedAddr(UnnamedAddr) ||
218 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
219 DLLStorageClass, TLM, UnnamedAddr))
224 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
225 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
226 case lltok::kw_uselistorder_bb:
227 if (ParseUseListOrderBB()) return true; break;
234 /// ::= 'module' 'asm' STRINGCONSTANT
235 bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
243 M->appendModuleInlineAsm(AsmStr);
248 /// ::= 'target' 'triple' '=' STRINGCONSTANT
249 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250 bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
260 M->setTargetTriple(Str);
262 case lltok::kw_datalayout:
264 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
265 ParseStringConstant(Str))
267 M->setDataLayout(Str);
273 /// ::= 'deplibs' '=' '[' ']'
274 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
275 /// FIXME: Remove in 4.0. Currently parse, but ignore.
276 bool LLParser::ParseDepLibs() {
277 assert(Lex.getKind() == lltok::kw_deplibs);
279 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
280 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
283 if (EatIfPresent(lltok::rsquare))
288 if (ParseStringConstant(Str)) return true;
289 } while (EatIfPresent(lltok::comma));
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
294 /// ParseUnnamedType:
295 /// ::= LocalVarID '=' 'type' type
296 bool LLParser::ParseUnnamedType() {
297 LocTy TypeLoc = Lex.getLoc();
298 unsigned TypeID = Lex.getUIntVal();
299 Lex.Lex(); // eat LocalVarID;
301 if (ParseToken(lltok::equal, "expected '=' after name") ||
302 ParseToken(lltok::kw_type, "expected 'type' after '='"))
305 if (TypeID >= NumberedTypes.size())
306 NumberedTypes.resize(TypeID+1);
308 Type *Result = nullptr;
309 if (ParseStructDefinition(TypeLoc, "",
310 NumberedTypes[TypeID], Result)) return true;
312 if (!isa<StructType>(Result)) {
313 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315 return Error(TypeLoc, "non-struct types may not be recursive");
316 Entry.first = Result;
317 Entry.second = SMLoc();
325 /// ::= LocalVar '=' 'type' type
326 bool LLParser::ParseNamedType() {
327 std::string Name = Lex.getStrVal();
328 LocTy NameLoc = Lex.getLoc();
329 Lex.Lex(); // eat LocalVar.
331 if (ParseToken(lltok::equal, "expected '=' after name") ||
332 ParseToken(lltok::kw_type, "expected 'type' after name"))
335 Type *Result = nullptr;
336 if (ParseStructDefinition(NameLoc, Name,
337 NamedTypes[Name], Result)) return true;
339 if (!isa<StructType>(Result)) {
340 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342 return Error(NameLoc, "non-struct types may not be recursive");
343 Entry.first = Result;
344 Entry.second = SMLoc();
352 /// ::= 'declare' FunctionHeader
353 bool LLParser::ParseDeclare() {
354 assert(Lex.getKind() == lltok::kw_declare);
358 return ParseFunctionHeader(F, false);
362 /// ::= 'define' FunctionHeader '{' ...
363 bool LLParser::ParseDefine() {
364 assert(Lex.getKind() == lltok::kw_define);
368 return ParseFunctionHeader(F, true) ||
369 ParseFunctionBody(*F);
375 bool LLParser::ParseGlobalType(bool &IsConstant) {
376 if (Lex.getKind() == lltok::kw_constant)
378 else if (Lex.getKind() == lltok::kw_global)
382 return TokError("expected 'global' or 'constant'");
388 /// ParseUnnamedGlobal:
389 /// OptionalVisibility ALIAS ...
390 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
391 /// ... -> global variable
392 /// GlobalID '=' OptionalVisibility ALIAS ...
393 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
394 /// ... -> global variable
395 bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
398 LocTy NameLoc = Lex.getLoc();
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
405 Lex.Lex(); // eat GlobalID;
407 if (ParseToken(lltok::equal, "expected '=' after name"))
412 unsigned Linkage, Visibility, DLLStorageClass;
413 GlobalVariable::ThreadLocalMode TLM;
415 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
416 ParseOptionalVisibility(Visibility) ||
417 ParseOptionalDLLStorageClass(DLLStorageClass) ||
418 ParseOptionalThreadLocal(TLM) ||
419 parseOptionalUnnamedAddr(UnnamedAddr))
422 if (Lex.getKind() != lltok::kw_alias)
423 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
424 DLLStorageClass, TLM, UnnamedAddr);
425 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
429 /// ParseNamedGlobal:
430 /// GlobalVar '=' OptionalVisibility ALIAS ...
431 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
432 /// ... -> global variable
433 bool LLParser::ParseNamedGlobal() {
434 assert(Lex.getKind() == lltok::GlobalVar);
435 LocTy NameLoc = Lex.getLoc();
436 std::string Name = Lex.getStrVal();
440 unsigned Linkage, Visibility, DLLStorageClass;
441 GlobalVariable::ThreadLocalMode TLM;
443 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
444 ParseOptionalLinkage(Linkage, HasLinkage) ||
445 ParseOptionalVisibility(Visibility) ||
446 ParseOptionalDLLStorageClass(DLLStorageClass) ||
447 ParseOptionalThreadLocal(TLM) ||
448 parseOptionalUnnamedAddr(UnnamedAddr))
451 if (Lex.getKind() != lltok::kw_alias)
452 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
453 DLLStorageClass, TLM, UnnamedAddr);
455 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
459 bool LLParser::parseComdat() {
460 assert(Lex.getKind() == lltok::ComdatVar);
461 std::string Name = Lex.getStrVal();
462 LocTy NameLoc = Lex.getLoc();
465 if (ParseToken(lltok::equal, "expected '=' here"))
468 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
469 return TokError("expected comdat type");
471 Comdat::SelectionKind SK;
472 switch (Lex.getKind()) {
474 return TokError("unknown selection kind");
478 case lltok::kw_exactmatch:
479 SK = Comdat::ExactMatch;
481 case lltok::kw_largest:
482 SK = Comdat::Largest;
484 case lltok::kw_noduplicates:
485 SK = Comdat::NoDuplicates;
487 case lltok::kw_samesize:
488 SK = Comdat::SameSize;
493 // See if the comdat was forward referenced, if so, use the comdat.
494 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
495 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
496 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
497 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
500 if (I != ComdatSymTab.end())
503 C = M->getOrInsertComdat(Name);
504 C->setSelectionKind(SK);
510 // ::= '!' STRINGCONSTANT
511 bool LLParser::ParseMDString(MDString *&Result) {
513 if (ParseStringConstant(Str)) return true;
514 llvm::UpgradeMDStringConstant(Str);
515 Result = MDString::get(Context, Str);
520 // ::= '!' MDNodeNumber
521 bool LLParser::ParseMDNodeID(MDNode *&Result) {
522 // !{ ..., !42, ... }
524 if (ParseUInt32(MID))
527 // If not a forward reference, just return it now.
528 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
529 Result = NumberedMetadata[MID];
533 // Otherwise, create MDNode forward reference.
534 MDNodeFwdDecl *FwdNode = MDNode::getTemporary(Context, None);
535 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
537 if (NumberedMetadata.size() <= MID)
538 NumberedMetadata.resize(MID+1);
539 NumberedMetadata[MID].reset(FwdNode);
544 /// ParseNamedMetadata:
545 /// !foo = !{ !1, !2 }
546 bool LLParser::ParseNamedMetadata() {
547 assert(Lex.getKind() == lltok::MetadataVar);
548 std::string Name = Lex.getStrVal();
551 if (ParseToken(lltok::equal, "expected '=' here") ||
552 ParseToken(lltok::exclaim, "Expected '!' here") ||
553 ParseToken(lltok::lbrace, "Expected '{' here"))
556 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
557 if (Lex.getKind() != lltok::rbrace)
559 if (ParseToken(lltok::exclaim, "Expected '!' here"))
563 if (ParseMDNodeID(N)) return true;
565 } while (EatIfPresent(lltok::comma));
567 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
573 /// ParseStandaloneMetadata:
575 bool LLParser::ParseStandaloneMetadata() {
576 assert(Lex.getKind() == lltok::exclaim);
578 unsigned MetadataID = 0;
581 if (ParseUInt32(MetadataID) ||
582 ParseToken(lltok::equal, "expected '=' here"))
585 // Detect common error, from old metadata syntax.
586 if (Lex.getKind() == lltok::Type)
587 return TokError("unexpected type in metadata definition");
589 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
590 if (ParseToken(lltok::exclaim, "Expected '!' here") ||
591 ParseMDTuple(Init, IsDistinct))
594 // See if this was forward referenced, if so, handle it.
595 auto FI = ForwardRefMDNodes.find(MetadataID);
596 if (FI != ForwardRefMDNodes.end()) {
597 auto *Temp = FI->second.first;
598 Temp->replaceAllUsesWith(Init);
599 MDNode::deleteTemporary(Temp);
600 ForwardRefMDNodes.erase(FI);
602 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
604 if (MetadataID >= NumberedMetadata.size())
605 NumberedMetadata.resize(MetadataID+1);
607 if (NumberedMetadata[MetadataID] != nullptr)
608 return TokError("Metadata id is already used");
609 NumberedMetadata[MetadataID].reset(Init);
615 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
616 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
617 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
621 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
622 /// OptionalDLLStorageClass OptionalThreadLocal
623 /// OptionalUnNammedAddr 'alias' Aliasee
628 /// Everything through OptionalUnNammedAddr has already been parsed.
630 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
631 unsigned Visibility, unsigned DLLStorageClass,
632 GlobalVariable::ThreadLocalMode TLM,
634 assert(Lex.getKind() == lltok::kw_alias);
637 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
639 if(!GlobalAlias::isValidLinkage(Linkage))
640 return Error(NameLoc, "invalid linkage type for alias");
642 if (!isValidVisibilityForLinkage(Visibility, L))
643 return Error(NameLoc,
644 "symbol with local linkage must have default visibility");
647 LocTy AliaseeLoc = Lex.getLoc();
648 if (Lex.getKind() != lltok::kw_bitcast &&
649 Lex.getKind() != lltok::kw_getelementptr &&
650 Lex.getKind() != lltok::kw_addrspacecast &&
651 Lex.getKind() != lltok::kw_inttoptr) {
652 if (ParseGlobalTypeAndValue(Aliasee))
655 // The bitcast dest type is not present, it is implied by the dest type.
659 if (ID.Kind != ValID::t_Constant)
660 return Error(AliaseeLoc, "invalid aliasee");
661 Aliasee = ID.ConstantVal;
664 Type *AliaseeType = Aliasee->getType();
665 auto *PTy = dyn_cast<PointerType>(AliaseeType);
667 return Error(AliaseeLoc, "An alias must have pointer type");
668 Type *Ty = PTy->getElementType();
669 unsigned AddrSpace = PTy->getAddressSpace();
671 // Okay, create the alias but do not insert it into the module yet.
672 std::unique_ptr<GlobalAlias> GA(
673 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
674 Name, Aliasee, /*Parent*/ nullptr));
675 GA->setThreadLocalMode(TLM);
676 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
677 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
678 GA->setUnnamedAddr(UnnamedAddr);
680 // See if this value already exists in the symbol table. If so, it is either
681 // a redefinition or a definition of a forward reference.
682 if (GlobalValue *Val = M->getNamedValue(Name)) {
683 // See if this was a redefinition. If so, there is no entry in
685 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefVals.find(Name);
687 if (I == ForwardRefVals.end())
688 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
690 // Otherwise, this was a definition of forward ref. Verify that types
692 if (Val->getType() != GA->getType())
693 return Error(NameLoc,
694 "forward reference and definition of alias have different types");
696 // If they agree, just RAUW the old value with the alias and remove the
698 Val->replaceAllUsesWith(GA.get());
699 Val->eraseFromParent();
700 ForwardRefVals.erase(I);
703 // Insert into the module, we know its name won't collide now.
704 M->getAliasList().push_back(GA.get());
705 assert(GA->getName() == Name && "Should not be a name conflict!");
707 // The module owns this now
714 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
715 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
716 /// OptionalExternallyInitialized GlobalType Type Const
717 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
718 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
719 /// OptionalExternallyInitialized GlobalType Type Const
721 /// Everything up to and including OptionalUnNammedAddr has been parsed
724 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
725 unsigned Linkage, bool HasLinkage,
726 unsigned Visibility, unsigned DLLStorageClass,
727 GlobalVariable::ThreadLocalMode TLM,
729 if (!isValidVisibilityForLinkage(Visibility, Linkage))
730 return Error(NameLoc,
731 "symbol with local linkage must have default visibility");
734 bool IsConstant, IsExternallyInitialized;
735 LocTy IsExternallyInitializedLoc;
739 if (ParseOptionalAddrSpace(AddrSpace) ||
740 ParseOptionalToken(lltok::kw_externally_initialized,
741 IsExternallyInitialized,
742 &IsExternallyInitializedLoc) ||
743 ParseGlobalType(IsConstant) ||
744 ParseType(Ty, TyLoc))
747 // If the linkage is specified and is external, then no initializer is
749 Constant *Init = nullptr;
750 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
751 Linkage != GlobalValue::ExternalLinkage)) {
752 if (ParseGlobalValue(Ty, Init))
756 if (Ty->isFunctionTy() || Ty->isLabelTy())
757 return Error(TyLoc, "invalid type for global variable");
759 GlobalValue *GVal = nullptr;
761 // See if the global was forward referenced, if so, use the global.
763 GVal = M->getNamedValue(Name);
765 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
766 return Error(NameLoc, "redefinition of global '@" + Name + "'");
769 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
770 I = ForwardRefValIDs.find(NumberedVals.size());
771 if (I != ForwardRefValIDs.end()) {
772 GVal = I->second.first;
773 ForwardRefValIDs.erase(I);
779 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
780 Name, nullptr, GlobalVariable::NotThreadLocal,
783 if (GVal->getType()->getElementType() != Ty)
785 "forward reference and definition of global have different types");
787 GV = cast<GlobalVariable>(GVal);
789 // Move the forward-reference to the correct spot in the module.
790 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
794 NumberedVals.push_back(GV);
796 // Set the parsed properties on the global.
798 GV->setInitializer(Init);
799 GV->setConstant(IsConstant);
800 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
801 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
802 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
803 GV->setExternallyInitialized(IsExternallyInitialized);
804 GV->setThreadLocalMode(TLM);
805 GV->setUnnamedAddr(UnnamedAddr);
807 // Parse attributes on the global.
808 while (Lex.getKind() == lltok::comma) {
811 if (Lex.getKind() == lltok::kw_section) {
813 GV->setSection(Lex.getStrVal());
814 if (ParseToken(lltok::StringConstant, "expected global section string"))
816 } else if (Lex.getKind() == lltok::kw_align) {
818 if (ParseOptionalAlignment(Alignment)) return true;
819 GV->setAlignment(Alignment);
822 if (parseOptionalComdat(Name, C))
827 return TokError("unknown global variable property!");
834 /// ParseUnnamedAttrGrp
835 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
836 bool LLParser::ParseUnnamedAttrGrp() {
837 assert(Lex.getKind() == lltok::kw_attributes);
838 LocTy AttrGrpLoc = Lex.getLoc();
841 if (Lex.getKind() != lltok::AttrGrpID)
842 return TokError("expected attribute group id");
844 unsigned VarID = Lex.getUIntVal();
845 std::vector<unsigned> unused;
849 if (ParseToken(lltok::equal, "expected '=' here") ||
850 ParseToken(lltok::lbrace, "expected '{' here") ||
851 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
853 ParseToken(lltok::rbrace, "expected end of attribute group"))
856 if (!NumberedAttrBuilders[VarID].hasAttributes())
857 return Error(AttrGrpLoc, "attribute group has no attributes");
862 /// ParseFnAttributeValuePairs
863 /// ::= <attr> | <attr> '=' <value>
864 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
865 std::vector<unsigned> &FwdRefAttrGrps,
866 bool inAttrGrp, LocTy &BuiltinLoc) {
867 bool HaveError = false;
872 lltok::Kind Token = Lex.getKind();
873 if (Token == lltok::kw_builtin)
874 BuiltinLoc = Lex.getLoc();
877 if (!inAttrGrp) return HaveError;
878 return Error(Lex.getLoc(), "unterminated attribute group");
883 case lltok::AttrGrpID: {
884 // Allow a function to reference an attribute group:
886 // define void @foo() #1 { ... }
890 "cannot have an attribute group reference in an attribute group");
892 unsigned AttrGrpNum = Lex.getUIntVal();
893 if (inAttrGrp) break;
895 // Save the reference to the attribute group. We'll fill it in later.
896 FwdRefAttrGrps.push_back(AttrGrpNum);
899 // Target-dependent attributes:
900 case lltok::StringConstant: {
901 std::string Attr = Lex.getStrVal();
904 if (EatIfPresent(lltok::equal) &&
905 ParseStringConstant(Val))
908 B.addAttribute(Attr, Val);
912 // Target-independent attributes:
913 case lltok::kw_align: {
914 // As a hack, we allow function alignment to be initially parsed as an
915 // attribute on a function declaration/definition or added to an attribute
916 // group and later moved to the alignment field.
920 if (ParseToken(lltok::equal, "expected '=' here") ||
921 ParseUInt32(Alignment))
924 if (ParseOptionalAlignment(Alignment))
927 B.addAlignmentAttr(Alignment);
930 case lltok::kw_alignstack: {
934 if (ParseToken(lltok::equal, "expected '=' here") ||
935 ParseUInt32(Alignment))
938 if (ParseOptionalStackAlignment(Alignment))
941 B.addStackAlignmentAttr(Alignment);
944 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
945 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
946 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
947 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
948 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
949 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
950 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
951 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
952 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
953 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
954 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
955 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
956 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
957 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
958 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
959 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
960 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
961 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
962 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
963 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
964 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
965 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
966 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
967 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
968 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
969 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
970 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
973 case lltok::kw_inreg:
974 case lltok::kw_signext:
975 case lltok::kw_zeroext:
978 "invalid use of attribute on a function");
980 case lltok::kw_byval:
981 case lltok::kw_dereferenceable:
982 case lltok::kw_inalloca:
984 case lltok::kw_noalias:
985 case lltok::kw_nocapture:
986 case lltok::kw_nonnull:
987 case lltok::kw_returned:
991 "invalid use of parameter-only attribute on a function");
999 //===----------------------------------------------------------------------===//
1000 // GlobalValue Reference/Resolution Routines.
1001 //===----------------------------------------------------------------------===//
1003 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1004 /// forward reference record if needed. This can return null if the value
1005 /// exists but does not have the right type.
1006 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1008 PointerType *PTy = dyn_cast<PointerType>(Ty);
1010 Error(Loc, "global variable reference must have pointer type");
1014 // Look this name up in the normal function symbol table.
1016 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1018 // If this is a forward reference for the value, see if we already created a
1019 // forward ref record.
1021 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1022 I = ForwardRefVals.find(Name);
1023 if (I != ForwardRefVals.end())
1024 Val = I->second.first;
1027 // If we have the value in the symbol table or fwd-ref table, return it.
1029 if (Val->getType() == Ty) return Val;
1030 Error(Loc, "'@" + Name + "' defined with type '" +
1031 getTypeString(Val->getType()) + "'");
1035 // Otherwise, create a new forward reference for this value and remember it.
1036 GlobalValue *FwdVal;
1037 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1038 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1040 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1041 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1042 nullptr, GlobalVariable::NotThreadLocal,
1043 PTy->getAddressSpace());
1045 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1049 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1050 PointerType *PTy = dyn_cast<PointerType>(Ty);
1052 Error(Loc, "global variable reference must have pointer type");
1056 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1058 // If this is a forward reference for the value, see if we already created a
1059 // forward ref record.
1061 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1062 I = ForwardRefValIDs.find(ID);
1063 if (I != ForwardRefValIDs.end())
1064 Val = I->second.first;
1067 // If we have the value in the symbol table or fwd-ref table, return it.
1069 if (Val->getType() == Ty) return Val;
1070 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1071 getTypeString(Val->getType()) + "'");
1075 // Otherwise, create a new forward reference for this value and remember it.
1076 GlobalValue *FwdVal;
1077 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1078 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1080 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1081 GlobalValue::ExternalWeakLinkage, nullptr, "");
1083 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1088 //===----------------------------------------------------------------------===//
1089 // Comdat Reference/Resolution Routines.
1090 //===----------------------------------------------------------------------===//
1092 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1093 // Look this name up in the comdat symbol table.
1094 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1095 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1096 if (I != ComdatSymTab.end())
1099 // Otherwise, create a new forward reference for this value and remember it.
1100 Comdat *C = M->getOrInsertComdat(Name);
1101 ForwardRefComdats[Name] = Loc;
1106 //===----------------------------------------------------------------------===//
1108 //===----------------------------------------------------------------------===//
1110 /// ParseToken - If the current token has the specified kind, eat it and return
1111 /// success. Otherwise, emit the specified error and return failure.
1112 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1113 if (Lex.getKind() != T)
1114 return TokError(ErrMsg);
1119 /// ParseStringConstant
1120 /// ::= StringConstant
1121 bool LLParser::ParseStringConstant(std::string &Result) {
1122 if (Lex.getKind() != lltok::StringConstant)
1123 return TokError("expected string constant");
1124 Result = Lex.getStrVal();
1131 bool LLParser::ParseUInt32(unsigned &Val) {
1132 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1133 return TokError("expected integer");
1134 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1135 if (Val64 != unsigned(Val64))
1136 return TokError("expected 32-bit integer (too large)");
1144 bool LLParser::ParseUInt64(uint64_t &Val) {
1145 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1146 return TokError("expected integer");
1147 Val = Lex.getAPSIntVal().getLimitedValue();
1153 /// := 'localdynamic'
1154 /// := 'initialexec'
1156 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1157 switch (Lex.getKind()) {
1159 return TokError("expected localdynamic, initialexec or localexec");
1160 case lltok::kw_localdynamic:
1161 TLM = GlobalVariable::LocalDynamicTLSModel;
1163 case lltok::kw_initialexec:
1164 TLM = GlobalVariable::InitialExecTLSModel;
1166 case lltok::kw_localexec:
1167 TLM = GlobalVariable::LocalExecTLSModel;
1175 /// ParseOptionalThreadLocal
1177 /// := 'thread_local'
1178 /// := 'thread_local' '(' tlsmodel ')'
1179 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1180 TLM = GlobalVariable::NotThreadLocal;
1181 if (!EatIfPresent(lltok::kw_thread_local))
1184 TLM = GlobalVariable::GeneralDynamicTLSModel;
1185 if (Lex.getKind() == lltok::lparen) {
1187 return ParseTLSModel(TLM) ||
1188 ParseToken(lltok::rparen, "expected ')' after thread local model");
1193 /// ParseOptionalAddrSpace
1195 /// := 'addrspace' '(' uint32 ')'
1196 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1198 if (!EatIfPresent(lltok::kw_addrspace))
1200 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1201 ParseUInt32(AddrSpace) ||
1202 ParseToken(lltok::rparen, "expected ')' in address space");
1205 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1206 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1207 bool HaveError = false;
1212 lltok::Kind Token = Lex.getKind();
1214 default: // End of attributes.
1216 case lltok::kw_align: {
1218 if (ParseOptionalAlignment(Alignment))
1220 B.addAlignmentAttr(Alignment);
1223 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1224 case lltok::kw_dereferenceable: {
1226 if (ParseOptionalDereferenceableBytes(Bytes))
1228 B.addDereferenceableAttr(Bytes);
1231 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1232 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1233 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1234 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1235 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1236 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1237 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1238 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1239 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1240 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1241 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1242 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1244 case lltok::kw_alignstack:
1245 case lltok::kw_alwaysinline:
1246 case lltok::kw_builtin:
1247 case lltok::kw_inlinehint:
1248 case lltok::kw_jumptable:
1249 case lltok::kw_minsize:
1250 case lltok::kw_naked:
1251 case lltok::kw_nobuiltin:
1252 case lltok::kw_noduplicate:
1253 case lltok::kw_noimplicitfloat:
1254 case lltok::kw_noinline:
1255 case lltok::kw_nonlazybind:
1256 case lltok::kw_noredzone:
1257 case lltok::kw_noreturn:
1258 case lltok::kw_nounwind:
1259 case lltok::kw_optnone:
1260 case lltok::kw_optsize:
1261 case lltok::kw_returns_twice:
1262 case lltok::kw_sanitize_address:
1263 case lltok::kw_sanitize_memory:
1264 case lltok::kw_sanitize_thread:
1266 case lltok::kw_sspreq:
1267 case lltok::kw_sspstrong:
1268 case lltok::kw_uwtable:
1269 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1277 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1278 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1279 bool HaveError = false;
1284 lltok::Kind Token = Lex.getKind();
1286 default: // End of attributes.
1288 case lltok::kw_dereferenceable: {
1290 if (ParseOptionalDereferenceableBytes(Bytes))
1292 B.addDereferenceableAttr(Bytes);
1295 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1296 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1297 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1298 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1299 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1302 case lltok::kw_align:
1303 case lltok::kw_byval:
1304 case lltok::kw_inalloca:
1305 case lltok::kw_nest:
1306 case lltok::kw_nocapture:
1307 case lltok::kw_returned:
1308 case lltok::kw_sret:
1309 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1312 case lltok::kw_alignstack:
1313 case lltok::kw_alwaysinline:
1314 case lltok::kw_builtin:
1315 case lltok::kw_cold:
1316 case lltok::kw_inlinehint:
1317 case lltok::kw_jumptable:
1318 case lltok::kw_minsize:
1319 case lltok::kw_naked:
1320 case lltok::kw_nobuiltin:
1321 case lltok::kw_noduplicate:
1322 case lltok::kw_noimplicitfloat:
1323 case lltok::kw_noinline:
1324 case lltok::kw_nonlazybind:
1325 case lltok::kw_noredzone:
1326 case lltok::kw_noreturn:
1327 case lltok::kw_nounwind:
1328 case lltok::kw_optnone:
1329 case lltok::kw_optsize:
1330 case lltok::kw_returns_twice:
1331 case lltok::kw_sanitize_address:
1332 case lltok::kw_sanitize_memory:
1333 case lltok::kw_sanitize_thread:
1335 case lltok::kw_sspreq:
1336 case lltok::kw_sspstrong:
1337 case lltok::kw_uwtable:
1338 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1341 case lltok::kw_readnone:
1342 case lltok::kw_readonly:
1343 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1350 /// ParseOptionalLinkage
1357 /// ::= 'linkonce_odr'
1358 /// ::= 'available_externally'
1361 /// ::= 'extern_weak'
1363 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1365 switch (Lex.getKind()) {
1366 default: Res=GlobalValue::ExternalLinkage; return false;
1367 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1368 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1369 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1370 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1371 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1372 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1373 case lltok::kw_available_externally:
1374 Res = GlobalValue::AvailableExternallyLinkage;
1376 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1377 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1378 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1379 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1386 /// ParseOptionalVisibility
1392 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1393 switch (Lex.getKind()) {
1394 default: Res = GlobalValue::DefaultVisibility; return false;
1395 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1396 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1397 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1403 /// ParseOptionalDLLStorageClass
1408 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1409 switch (Lex.getKind()) {
1410 default: Res = GlobalValue::DefaultStorageClass; return false;
1411 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1412 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1418 /// ParseOptionalCallingConv
1422 /// ::= 'intel_ocl_bicc'
1424 /// ::= 'x86_stdcallcc'
1425 /// ::= 'x86_fastcallcc'
1426 /// ::= 'x86_thiscallcc'
1427 /// ::= 'x86_vectorcallcc'
1428 /// ::= 'arm_apcscc'
1429 /// ::= 'arm_aapcscc'
1430 /// ::= 'arm_aapcs_vfpcc'
1431 /// ::= 'msp430_intrcc'
1432 /// ::= 'ptx_kernel'
1433 /// ::= 'ptx_device'
1435 /// ::= 'spir_kernel'
1436 /// ::= 'x86_64_sysvcc'
1437 /// ::= 'x86_64_win64cc'
1438 /// ::= 'webkit_jscc'
1440 /// ::= 'preserve_mostcc'
1441 /// ::= 'preserve_allcc'
1445 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1446 switch (Lex.getKind()) {
1447 default: CC = CallingConv::C; return false;
1448 case lltok::kw_ccc: CC = CallingConv::C; break;
1449 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1450 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1451 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1452 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1453 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1454 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1455 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1456 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1457 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1458 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1459 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1460 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1461 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1462 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1463 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1464 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1465 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1466 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1467 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1468 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1469 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1470 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1471 case lltok::kw_cc: {
1473 return ParseUInt32(CC);
1481 /// ParseInstructionMetadata
1482 /// ::= !dbg !42 (',' !dbg !57)*
1483 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1484 PerFunctionState *PFS) {
1486 if (Lex.getKind() != lltok::MetadataVar)
1487 return TokError("expected metadata after comma");
1489 std::string Name = Lex.getStrVal();
1490 unsigned MDK = M->getMDKindID(Name);
1493 if (ParseToken(lltok::exclaim, "expected '!' here"))
1496 // This code is similar to that of ParseMetadata. However, only MDNodes
1497 // are supported here.
1498 if (Lex.getKind() == lltok::lbrace) {
1500 if (ParseMDTuple(N))
1502 Inst->setMetadata(MDK, N);
1505 if (ParseMDNodeID(Node))
1507 // If we got the node, add it to the instruction.
1508 Inst->setMetadata(MDK, Node);
1511 if (MDK == LLVMContext::MD_tbaa)
1512 InstsWithTBAATag.push_back(Inst);
1514 // If this is the end of the list, we're done.
1515 } while (EatIfPresent(lltok::comma));
1519 /// ParseOptionalAlignment
1522 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1524 if (!EatIfPresent(lltok::kw_align))
1526 LocTy AlignLoc = Lex.getLoc();
1527 if (ParseUInt32(Alignment)) return true;
1528 if (!isPowerOf2_32(Alignment))
1529 return Error(AlignLoc, "alignment is not a power of two");
1530 if (Alignment > Value::MaximumAlignment)
1531 return Error(AlignLoc, "huge alignments are not supported yet");
1535 /// ParseOptionalDereferenceableBytes
1537 /// ::= 'dereferenceable' '(' 4 ')'
1538 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1540 if (!EatIfPresent(lltok::kw_dereferenceable))
1542 LocTy ParenLoc = Lex.getLoc();
1543 if (!EatIfPresent(lltok::lparen))
1544 return Error(ParenLoc, "expected '('");
1545 LocTy DerefLoc = Lex.getLoc();
1546 if (ParseUInt64(Bytes)) return true;
1547 ParenLoc = Lex.getLoc();
1548 if (!EatIfPresent(lltok::rparen))
1549 return Error(ParenLoc, "expected ')'");
1551 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1555 /// ParseOptionalCommaAlign
1559 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1561 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1562 bool &AteExtraComma) {
1563 AteExtraComma = false;
1564 while (EatIfPresent(lltok::comma)) {
1565 // Metadata at the end is an early exit.
1566 if (Lex.getKind() == lltok::MetadataVar) {
1567 AteExtraComma = true;
1571 if (Lex.getKind() != lltok::kw_align)
1572 return Error(Lex.getLoc(), "expected metadata or 'align'");
1574 if (ParseOptionalAlignment(Alignment)) return true;
1580 /// ParseScopeAndOrdering
1581 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1584 /// This sets Scope and Ordering to the parsed values.
1585 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1586 AtomicOrdering &Ordering) {
1590 Scope = CrossThread;
1591 if (EatIfPresent(lltok::kw_singlethread))
1592 Scope = SingleThread;
1594 return ParseOrdering(Ordering);
1598 /// ::= AtomicOrdering
1600 /// This sets Ordering to the parsed value.
1601 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1602 switch (Lex.getKind()) {
1603 default: return TokError("Expected ordering on atomic instruction");
1604 case lltok::kw_unordered: Ordering = Unordered; break;
1605 case lltok::kw_monotonic: Ordering = Monotonic; break;
1606 case lltok::kw_acquire: Ordering = Acquire; break;
1607 case lltok::kw_release: Ordering = Release; break;
1608 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1609 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1615 /// ParseOptionalStackAlignment
1617 /// ::= 'alignstack' '(' 4 ')'
1618 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1620 if (!EatIfPresent(lltok::kw_alignstack))
1622 LocTy ParenLoc = Lex.getLoc();
1623 if (!EatIfPresent(lltok::lparen))
1624 return Error(ParenLoc, "expected '('");
1625 LocTy AlignLoc = Lex.getLoc();
1626 if (ParseUInt32(Alignment)) return true;
1627 ParenLoc = Lex.getLoc();
1628 if (!EatIfPresent(lltok::rparen))
1629 return Error(ParenLoc, "expected ')'");
1630 if (!isPowerOf2_32(Alignment))
1631 return Error(AlignLoc, "stack alignment is not a power of two");
1635 /// ParseIndexList - This parses the index list for an insert/extractvalue
1636 /// instruction. This sets AteExtraComma in the case where we eat an extra
1637 /// comma at the end of the line and find that it is followed by metadata.
1638 /// Clients that don't allow metadata can call the version of this function that
1639 /// only takes one argument.
1642 /// ::= (',' uint32)+
1644 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1645 bool &AteExtraComma) {
1646 AteExtraComma = false;
1648 if (Lex.getKind() != lltok::comma)
1649 return TokError("expected ',' as start of index list");
1651 while (EatIfPresent(lltok::comma)) {
1652 if (Lex.getKind() == lltok::MetadataVar) {
1653 AteExtraComma = true;
1657 if (ParseUInt32(Idx)) return true;
1658 Indices.push_back(Idx);
1664 //===----------------------------------------------------------------------===//
1666 //===----------------------------------------------------------------------===//
1668 /// ParseType - Parse a type.
1669 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1670 SMLoc TypeLoc = Lex.getLoc();
1671 switch (Lex.getKind()) {
1673 return TokError(Msg);
1675 // Type ::= 'float' | 'void' (etc)
1676 Result = Lex.getTyVal();
1680 // Type ::= StructType
1681 if (ParseAnonStructType(Result, false))
1684 case lltok::lsquare:
1685 // Type ::= '[' ... ']'
1686 Lex.Lex(); // eat the lsquare.
1687 if (ParseArrayVectorType(Result, false))
1690 case lltok::less: // Either vector or packed struct.
1691 // Type ::= '<' ... '>'
1693 if (Lex.getKind() == lltok::lbrace) {
1694 if (ParseAnonStructType(Result, true) ||
1695 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1697 } else if (ParseArrayVectorType(Result, true))
1700 case lltok::LocalVar: {
1702 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1704 // If the type hasn't been defined yet, create a forward definition and
1705 // remember where that forward def'n was seen (in case it never is defined).
1707 Entry.first = StructType::create(Context, Lex.getStrVal());
1708 Entry.second = Lex.getLoc();
1710 Result = Entry.first;
1715 case lltok::LocalVarID: {
1717 if (Lex.getUIntVal() >= NumberedTypes.size())
1718 NumberedTypes.resize(Lex.getUIntVal()+1);
1719 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1721 // If the type hasn't been defined yet, create a forward definition and
1722 // remember where that forward def'n was seen (in case it never is defined).
1724 Entry.first = StructType::create(Context);
1725 Entry.second = Lex.getLoc();
1727 Result = Entry.first;
1733 // Parse the type suffixes.
1735 switch (Lex.getKind()) {
1738 if (!AllowVoid && Result->isVoidTy())
1739 return Error(TypeLoc, "void type only allowed for function results");
1742 // Type ::= Type '*'
1744 if (Result->isLabelTy())
1745 return TokError("basic block pointers are invalid");
1746 if (Result->isVoidTy())
1747 return TokError("pointers to void are invalid - use i8* instead");
1748 if (!PointerType::isValidElementType(Result))
1749 return TokError("pointer to this type is invalid");
1750 Result = PointerType::getUnqual(Result);
1754 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1755 case lltok::kw_addrspace: {
1756 if (Result->isLabelTy())
1757 return TokError("basic block pointers are invalid");
1758 if (Result->isVoidTy())
1759 return TokError("pointers to void are invalid; use i8* instead");
1760 if (!PointerType::isValidElementType(Result))
1761 return TokError("pointer to this type is invalid");
1763 if (ParseOptionalAddrSpace(AddrSpace) ||
1764 ParseToken(lltok::star, "expected '*' in address space"))
1767 Result = PointerType::get(Result, AddrSpace);
1771 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1773 if (ParseFunctionType(Result))
1780 /// ParseParameterList
1782 /// ::= '(' Arg (',' Arg)* ')'
1784 /// ::= Type OptionalAttributes Value OptionalAttributes
1785 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1786 PerFunctionState &PFS, bool IsMustTailCall,
1787 bool InVarArgsFunc) {
1788 if (ParseToken(lltok::lparen, "expected '(' in call"))
1791 unsigned AttrIndex = 1;
1792 while (Lex.getKind() != lltok::rparen) {
1793 // If this isn't the first argument, we need a comma.
1794 if (!ArgList.empty() &&
1795 ParseToken(lltok::comma, "expected ',' in argument list"))
1798 // Parse an ellipsis if this is a musttail call in a variadic function.
1799 if (Lex.getKind() == lltok::dotdotdot) {
1800 const char *Msg = "unexpected ellipsis in argument list for ";
1801 if (!IsMustTailCall)
1802 return TokError(Twine(Msg) + "non-musttail call");
1804 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1805 Lex.Lex(); // Lex the '...', it is purely for readability.
1806 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1809 // Parse the argument.
1811 Type *ArgTy = nullptr;
1812 AttrBuilder ArgAttrs;
1814 if (ParseType(ArgTy, ArgLoc))
1817 if (ArgTy->isMetadataTy()) {
1818 if (ParseMetadataAsValue(V, PFS))
1821 // Otherwise, handle normal operands.
1822 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1825 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1830 if (IsMustTailCall && InVarArgsFunc)
1831 return TokError("expected '...' at end of argument list for musttail call "
1832 "in varargs function");
1834 Lex.Lex(); // Lex the ')'.
1840 /// ParseArgumentList - Parse the argument list for a function type or function
1842 /// ::= '(' ArgTypeListI ')'
1846 /// ::= ArgTypeList ',' '...'
1847 /// ::= ArgType (',' ArgType)*
1849 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1852 assert(Lex.getKind() == lltok::lparen);
1853 Lex.Lex(); // eat the (.
1855 if (Lex.getKind() == lltok::rparen) {
1857 } else if (Lex.getKind() == lltok::dotdotdot) {
1861 LocTy TypeLoc = Lex.getLoc();
1862 Type *ArgTy = nullptr;
1866 if (ParseType(ArgTy) ||
1867 ParseOptionalParamAttrs(Attrs)) return true;
1869 if (ArgTy->isVoidTy())
1870 return Error(TypeLoc, "argument can not have void type");
1872 if (Lex.getKind() == lltok::LocalVar) {
1873 Name = Lex.getStrVal();
1877 if (!FunctionType::isValidArgumentType(ArgTy))
1878 return Error(TypeLoc, "invalid type for function argument");
1880 unsigned AttrIndex = 1;
1881 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1882 AttributeSet::get(ArgTy->getContext(),
1883 AttrIndex++, Attrs), Name));
1885 while (EatIfPresent(lltok::comma)) {
1886 // Handle ... at end of arg list.
1887 if (EatIfPresent(lltok::dotdotdot)) {
1892 // Otherwise must be an argument type.
1893 TypeLoc = Lex.getLoc();
1894 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1896 if (ArgTy->isVoidTy())
1897 return Error(TypeLoc, "argument can not have void type");
1899 if (Lex.getKind() == lltok::LocalVar) {
1900 Name = Lex.getStrVal();
1906 if (!ArgTy->isFirstClassType())
1907 return Error(TypeLoc, "invalid type for function argument");
1909 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1910 AttributeSet::get(ArgTy->getContext(),
1911 AttrIndex++, Attrs),
1916 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1919 /// ParseFunctionType
1920 /// ::= Type ArgumentList OptionalAttrs
1921 bool LLParser::ParseFunctionType(Type *&Result) {
1922 assert(Lex.getKind() == lltok::lparen);
1924 if (!FunctionType::isValidReturnType(Result))
1925 return TokError("invalid function return type");
1927 SmallVector<ArgInfo, 8> ArgList;
1929 if (ParseArgumentList(ArgList, isVarArg))
1932 // Reject names on the arguments lists.
1933 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1934 if (!ArgList[i].Name.empty())
1935 return Error(ArgList[i].Loc, "argument name invalid in function type");
1936 if (ArgList[i].Attrs.hasAttributes(i + 1))
1937 return Error(ArgList[i].Loc,
1938 "argument attributes invalid in function type");
1941 SmallVector<Type*, 16> ArgListTy;
1942 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1943 ArgListTy.push_back(ArgList[i].Ty);
1945 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1949 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1951 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1952 SmallVector<Type*, 8> Elts;
1953 if (ParseStructBody(Elts)) return true;
1955 Result = StructType::get(Context, Elts, Packed);
1959 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1960 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1961 std::pair<Type*, LocTy> &Entry,
1963 // If the type was already defined, diagnose the redefinition.
1964 if (Entry.first && !Entry.second.isValid())
1965 return Error(TypeLoc, "redefinition of type");
1967 // If we have opaque, just return without filling in the definition for the
1968 // struct. This counts as a definition as far as the .ll file goes.
1969 if (EatIfPresent(lltok::kw_opaque)) {
1970 // This type is being defined, so clear the location to indicate this.
1971 Entry.second = SMLoc();
1973 // If this type number has never been uttered, create it.
1975 Entry.first = StructType::create(Context, Name);
1976 ResultTy = Entry.first;
1980 // If the type starts with '<', then it is either a packed struct or a vector.
1981 bool isPacked = EatIfPresent(lltok::less);
1983 // If we don't have a struct, then we have a random type alias, which we
1984 // accept for compatibility with old files. These types are not allowed to be
1985 // forward referenced and not allowed to be recursive.
1986 if (Lex.getKind() != lltok::lbrace) {
1988 return Error(TypeLoc, "forward references to non-struct type");
1992 return ParseArrayVectorType(ResultTy, true);
1993 return ParseType(ResultTy);
1996 // This type is being defined, so clear the location to indicate this.
1997 Entry.second = SMLoc();
1999 // If this type number has never been uttered, create it.
2001 Entry.first = StructType::create(Context, Name);
2003 StructType *STy = cast<StructType>(Entry.first);
2005 SmallVector<Type*, 8> Body;
2006 if (ParseStructBody(Body) ||
2007 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2010 STy->setBody(Body, isPacked);
2016 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2019 /// ::= '{' Type (',' Type)* '}'
2020 /// ::= '<' '{' '}' '>'
2021 /// ::= '<' '{' Type (',' Type)* '}' '>'
2022 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2023 assert(Lex.getKind() == lltok::lbrace);
2024 Lex.Lex(); // Consume the '{'
2026 // Handle the empty struct.
2027 if (EatIfPresent(lltok::rbrace))
2030 LocTy EltTyLoc = Lex.getLoc();
2032 if (ParseType(Ty)) return true;
2035 if (!StructType::isValidElementType(Ty))
2036 return Error(EltTyLoc, "invalid element type for struct");
2038 while (EatIfPresent(lltok::comma)) {
2039 EltTyLoc = Lex.getLoc();
2040 if (ParseType(Ty)) return true;
2042 if (!StructType::isValidElementType(Ty))
2043 return Error(EltTyLoc, "invalid element type for struct");
2048 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2051 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2052 /// token has already been consumed.
2054 /// ::= '[' APSINTVAL 'x' Types ']'
2055 /// ::= '<' APSINTVAL 'x' Types '>'
2056 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2057 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2058 Lex.getAPSIntVal().getBitWidth() > 64)
2059 return TokError("expected number in address space");
2061 LocTy SizeLoc = Lex.getLoc();
2062 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2065 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2068 LocTy TypeLoc = Lex.getLoc();
2069 Type *EltTy = nullptr;
2070 if (ParseType(EltTy)) return true;
2072 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2073 "expected end of sequential type"))
2078 return Error(SizeLoc, "zero element vector is illegal");
2079 if ((unsigned)Size != Size)
2080 return Error(SizeLoc, "size too large for vector");
2081 if (!VectorType::isValidElementType(EltTy))
2082 return Error(TypeLoc, "invalid vector element type");
2083 Result = VectorType::get(EltTy, unsigned(Size));
2085 if (!ArrayType::isValidElementType(EltTy))
2086 return Error(TypeLoc, "invalid array element type");
2087 Result = ArrayType::get(EltTy, Size);
2092 //===----------------------------------------------------------------------===//
2093 // Function Semantic Analysis.
2094 //===----------------------------------------------------------------------===//
2096 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2098 : P(p), F(f), FunctionNumber(functionNumber) {
2100 // Insert unnamed arguments into the NumberedVals list.
2101 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2104 NumberedVals.push_back(AI);
2107 LLParser::PerFunctionState::~PerFunctionState() {
2108 // If there were any forward referenced non-basicblock values, delete them.
2109 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2110 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2111 if (!isa<BasicBlock>(I->second.first)) {
2112 I->second.first->replaceAllUsesWith(
2113 UndefValue::get(I->second.first->getType()));
2114 delete I->second.first;
2115 I->second.first = nullptr;
2118 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2119 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2120 if (!isa<BasicBlock>(I->second.first)) {
2121 I->second.first->replaceAllUsesWith(
2122 UndefValue::get(I->second.first->getType()));
2123 delete I->second.first;
2124 I->second.first = nullptr;
2128 bool LLParser::PerFunctionState::FinishFunction() {
2129 if (!ForwardRefVals.empty())
2130 return P.Error(ForwardRefVals.begin()->second.second,
2131 "use of undefined value '%" + ForwardRefVals.begin()->first +
2133 if (!ForwardRefValIDs.empty())
2134 return P.Error(ForwardRefValIDs.begin()->second.second,
2135 "use of undefined value '%" +
2136 Twine(ForwardRefValIDs.begin()->first) + "'");
2141 /// GetVal - Get a value with the specified name or ID, creating a
2142 /// forward reference record if needed. This can return null if the value
2143 /// exists but does not have the right type.
2144 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2145 Type *Ty, LocTy Loc) {
2146 // Look this name up in the normal function symbol table.
2147 Value *Val = F.getValueSymbolTable().lookup(Name);
2149 // If this is a forward reference for the value, see if we already created a
2150 // forward ref record.
2152 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2153 I = ForwardRefVals.find(Name);
2154 if (I != ForwardRefVals.end())
2155 Val = I->second.first;
2158 // If we have the value in the symbol table or fwd-ref table, return it.
2160 if (Val->getType() == Ty) return Val;
2161 if (Ty->isLabelTy())
2162 P.Error(Loc, "'%" + Name + "' is not a basic block");
2164 P.Error(Loc, "'%" + Name + "' defined with type '" +
2165 getTypeString(Val->getType()) + "'");
2169 // Don't make placeholders with invalid type.
2170 if (!Ty->isFirstClassType()) {
2171 P.Error(Loc, "invalid use of a non-first-class type");
2175 // Otherwise, create a new forward reference for this value and remember it.
2177 if (Ty->isLabelTy())
2178 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2180 FwdVal = new Argument(Ty, Name);
2182 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2186 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2188 // Look this name up in the normal function symbol table.
2189 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2191 // If this is a forward reference for the value, see if we already created a
2192 // forward ref record.
2194 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2195 I = ForwardRefValIDs.find(ID);
2196 if (I != ForwardRefValIDs.end())
2197 Val = I->second.first;
2200 // If we have the value in the symbol table or fwd-ref table, return it.
2202 if (Val->getType() == Ty) return Val;
2203 if (Ty->isLabelTy())
2204 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2206 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2207 getTypeString(Val->getType()) + "'");
2211 if (!Ty->isFirstClassType()) {
2212 P.Error(Loc, "invalid use of a non-first-class type");
2216 // Otherwise, create a new forward reference for this value and remember it.
2218 if (Ty->isLabelTy())
2219 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2221 FwdVal = new Argument(Ty);
2223 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2227 /// SetInstName - After an instruction is parsed and inserted into its
2228 /// basic block, this installs its name.
2229 bool LLParser::PerFunctionState::SetInstName(int NameID,
2230 const std::string &NameStr,
2231 LocTy NameLoc, Instruction *Inst) {
2232 // If this instruction has void type, it cannot have a name or ID specified.
2233 if (Inst->getType()->isVoidTy()) {
2234 if (NameID != -1 || !NameStr.empty())
2235 return P.Error(NameLoc, "instructions returning void cannot have a name");
2239 // If this was a numbered instruction, verify that the instruction is the
2240 // expected value and resolve any forward references.
2241 if (NameStr.empty()) {
2242 // If neither a name nor an ID was specified, just use the next ID.
2244 NameID = NumberedVals.size();
2246 if (unsigned(NameID) != NumberedVals.size())
2247 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2248 Twine(NumberedVals.size()) + "'");
2250 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2251 ForwardRefValIDs.find(NameID);
2252 if (FI != ForwardRefValIDs.end()) {
2253 if (FI->second.first->getType() != Inst->getType())
2254 return P.Error(NameLoc, "instruction forward referenced with type '" +
2255 getTypeString(FI->second.first->getType()) + "'");
2256 FI->second.first->replaceAllUsesWith(Inst);
2257 delete FI->second.first;
2258 ForwardRefValIDs.erase(FI);
2261 NumberedVals.push_back(Inst);
2265 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2266 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2267 FI = ForwardRefVals.find(NameStr);
2268 if (FI != ForwardRefVals.end()) {
2269 if (FI->second.first->getType() != Inst->getType())
2270 return P.Error(NameLoc, "instruction forward referenced with type '" +
2271 getTypeString(FI->second.first->getType()) + "'");
2272 FI->second.first->replaceAllUsesWith(Inst);
2273 delete FI->second.first;
2274 ForwardRefVals.erase(FI);
2277 // Set the name on the instruction.
2278 Inst->setName(NameStr);
2280 if (Inst->getName() != NameStr)
2281 return P.Error(NameLoc, "multiple definition of local value named '" +
2286 /// GetBB - Get a basic block with the specified name or ID, creating a
2287 /// forward reference record if needed.
2288 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2290 return cast_or_null<BasicBlock>(GetVal(Name,
2291 Type::getLabelTy(F.getContext()), Loc));
2294 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2295 return cast_or_null<BasicBlock>(GetVal(ID,
2296 Type::getLabelTy(F.getContext()), Loc));
2299 /// DefineBB - Define the specified basic block, which is either named or
2300 /// unnamed. If there is an error, this returns null otherwise it returns
2301 /// the block being defined.
2302 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2306 BB = GetBB(NumberedVals.size(), Loc);
2308 BB = GetBB(Name, Loc);
2309 if (!BB) return nullptr; // Already diagnosed error.
2311 // Move the block to the end of the function. Forward ref'd blocks are
2312 // inserted wherever they happen to be referenced.
2313 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2315 // Remove the block from forward ref sets.
2317 ForwardRefValIDs.erase(NumberedVals.size());
2318 NumberedVals.push_back(BB);
2320 // BB forward references are already in the function symbol table.
2321 ForwardRefVals.erase(Name);
2327 //===----------------------------------------------------------------------===//
2329 //===----------------------------------------------------------------------===//
2331 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2332 /// type implied. For example, if we parse "4" we don't know what integer type
2333 /// it has. The value will later be combined with its type and checked for
2334 /// sanity. PFS is used to convert function-local operands of metadata (since
2335 /// metadata operands are not just parsed here but also converted to values).
2336 /// PFS can be null when we are not parsing metadata values inside a function.
2337 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2338 ID.Loc = Lex.getLoc();
2339 switch (Lex.getKind()) {
2340 default: return TokError("expected value token");
2341 case lltok::GlobalID: // @42
2342 ID.UIntVal = Lex.getUIntVal();
2343 ID.Kind = ValID::t_GlobalID;
2345 case lltok::GlobalVar: // @foo
2346 ID.StrVal = Lex.getStrVal();
2347 ID.Kind = ValID::t_GlobalName;
2349 case lltok::LocalVarID: // %42
2350 ID.UIntVal = Lex.getUIntVal();
2351 ID.Kind = ValID::t_LocalID;
2353 case lltok::LocalVar: // %foo
2354 ID.StrVal = Lex.getStrVal();
2355 ID.Kind = ValID::t_LocalName;
2358 ID.APSIntVal = Lex.getAPSIntVal();
2359 ID.Kind = ValID::t_APSInt;
2361 case lltok::APFloat:
2362 ID.APFloatVal = Lex.getAPFloatVal();
2363 ID.Kind = ValID::t_APFloat;
2365 case lltok::kw_true:
2366 ID.ConstantVal = ConstantInt::getTrue(Context);
2367 ID.Kind = ValID::t_Constant;
2369 case lltok::kw_false:
2370 ID.ConstantVal = ConstantInt::getFalse(Context);
2371 ID.Kind = ValID::t_Constant;
2373 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2374 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2375 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2377 case lltok::lbrace: {
2378 // ValID ::= '{' ConstVector '}'
2380 SmallVector<Constant*, 16> Elts;
2381 if (ParseGlobalValueVector(Elts) ||
2382 ParseToken(lltok::rbrace, "expected end of struct constant"))
2385 ID.ConstantStructElts = new Constant*[Elts.size()];
2386 ID.UIntVal = Elts.size();
2387 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2388 ID.Kind = ValID::t_ConstantStruct;
2392 // ValID ::= '<' ConstVector '>' --> Vector.
2393 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2395 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2397 SmallVector<Constant*, 16> Elts;
2398 LocTy FirstEltLoc = Lex.getLoc();
2399 if (ParseGlobalValueVector(Elts) ||
2401 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2402 ParseToken(lltok::greater, "expected end of constant"))
2405 if (isPackedStruct) {
2406 ID.ConstantStructElts = new Constant*[Elts.size()];
2407 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2408 ID.UIntVal = Elts.size();
2409 ID.Kind = ValID::t_PackedConstantStruct;
2414 return Error(ID.Loc, "constant vector must not be empty");
2416 if (!Elts[0]->getType()->isIntegerTy() &&
2417 !Elts[0]->getType()->isFloatingPointTy() &&
2418 !Elts[0]->getType()->isPointerTy())
2419 return Error(FirstEltLoc,
2420 "vector elements must have integer, pointer or floating point type");
2422 // Verify that all the vector elements have the same type.
2423 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2424 if (Elts[i]->getType() != Elts[0]->getType())
2425 return Error(FirstEltLoc,
2426 "vector element #" + Twine(i) +
2427 " is not of type '" + getTypeString(Elts[0]->getType()));
2429 ID.ConstantVal = ConstantVector::get(Elts);
2430 ID.Kind = ValID::t_Constant;
2433 case lltok::lsquare: { // Array Constant
2435 SmallVector<Constant*, 16> Elts;
2436 LocTy FirstEltLoc = Lex.getLoc();
2437 if (ParseGlobalValueVector(Elts) ||
2438 ParseToken(lltok::rsquare, "expected end of array constant"))
2441 // Handle empty element.
2443 // Use undef instead of an array because it's inconvenient to determine
2444 // the element type at this point, there being no elements to examine.
2445 ID.Kind = ValID::t_EmptyArray;
2449 if (!Elts[0]->getType()->isFirstClassType())
2450 return Error(FirstEltLoc, "invalid array element type: " +
2451 getTypeString(Elts[0]->getType()));
2453 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2455 // Verify all elements are correct type!
2456 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2457 if (Elts[i]->getType() != Elts[0]->getType())
2458 return Error(FirstEltLoc,
2459 "array element #" + Twine(i) +
2460 " is not of type '" + getTypeString(Elts[0]->getType()));
2463 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2464 ID.Kind = ValID::t_Constant;
2467 case lltok::kw_c: // c "foo"
2469 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2471 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2472 ID.Kind = ValID::t_Constant;
2475 case lltok::kw_asm: {
2476 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2478 bool HasSideEffect, AlignStack, AsmDialect;
2480 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2481 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2482 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2483 ParseStringConstant(ID.StrVal) ||
2484 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2485 ParseToken(lltok::StringConstant, "expected constraint string"))
2487 ID.StrVal2 = Lex.getStrVal();
2488 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2489 (unsigned(AsmDialect)<<2);
2490 ID.Kind = ValID::t_InlineAsm;
2494 case lltok::kw_blockaddress: {
2495 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2500 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2502 ParseToken(lltok::comma, "expected comma in block address expression")||
2503 ParseValID(Label) ||
2504 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2507 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2508 return Error(Fn.Loc, "expected function name in blockaddress");
2509 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2510 return Error(Label.Loc, "expected basic block name in blockaddress");
2512 // Try to find the function (but skip it if it's forward-referenced).
2513 GlobalValue *GV = nullptr;
2514 if (Fn.Kind == ValID::t_GlobalID) {
2515 if (Fn.UIntVal < NumberedVals.size())
2516 GV = NumberedVals[Fn.UIntVal];
2517 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2518 GV = M->getNamedValue(Fn.StrVal);
2520 Function *F = nullptr;
2522 // Confirm that it's actually a function with a definition.
2523 if (!isa<Function>(GV))
2524 return Error(Fn.Loc, "expected function name in blockaddress");
2525 F = cast<Function>(GV);
2526 if (F->isDeclaration())
2527 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2531 // Make a global variable as a placeholder for this reference.
2532 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2534 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2535 GlobalValue::InternalLinkage, nullptr, "");
2536 ID.ConstantVal = FwdRef;
2537 ID.Kind = ValID::t_Constant;
2541 // We found the function; now find the basic block. Don't use PFS, since we
2542 // might be inside a constant expression.
2544 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2545 if (Label.Kind == ValID::t_LocalID)
2546 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2548 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2550 return Error(Label.Loc, "referenced value is not a basic block");
2552 if (Label.Kind == ValID::t_LocalID)
2553 return Error(Label.Loc, "cannot take address of numeric label after "
2554 "the function is defined");
2555 BB = dyn_cast_or_null<BasicBlock>(
2556 F->getValueSymbolTable().lookup(Label.StrVal));
2558 return Error(Label.Loc, "referenced value is not a basic block");
2561 ID.ConstantVal = BlockAddress::get(F, BB);
2562 ID.Kind = ValID::t_Constant;
2566 case lltok::kw_trunc:
2567 case lltok::kw_zext:
2568 case lltok::kw_sext:
2569 case lltok::kw_fptrunc:
2570 case lltok::kw_fpext:
2571 case lltok::kw_bitcast:
2572 case lltok::kw_addrspacecast:
2573 case lltok::kw_uitofp:
2574 case lltok::kw_sitofp:
2575 case lltok::kw_fptoui:
2576 case lltok::kw_fptosi:
2577 case lltok::kw_inttoptr:
2578 case lltok::kw_ptrtoint: {
2579 unsigned Opc = Lex.getUIntVal();
2580 Type *DestTy = nullptr;
2583 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2584 ParseGlobalTypeAndValue(SrcVal) ||
2585 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2586 ParseType(DestTy) ||
2587 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2589 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2590 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2591 getTypeString(SrcVal->getType()) + "' to '" +
2592 getTypeString(DestTy) + "'");
2593 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2595 ID.Kind = ValID::t_Constant;
2598 case lltok::kw_extractvalue: {
2601 SmallVector<unsigned, 4> Indices;
2602 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2603 ParseGlobalTypeAndValue(Val) ||
2604 ParseIndexList(Indices) ||
2605 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2608 if (!Val->getType()->isAggregateType())
2609 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2610 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2611 return Error(ID.Loc, "invalid indices for extractvalue");
2612 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2613 ID.Kind = ValID::t_Constant;
2616 case lltok::kw_insertvalue: {
2618 Constant *Val0, *Val1;
2619 SmallVector<unsigned, 4> Indices;
2620 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2621 ParseGlobalTypeAndValue(Val0) ||
2622 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2623 ParseGlobalTypeAndValue(Val1) ||
2624 ParseIndexList(Indices) ||
2625 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2627 if (!Val0->getType()->isAggregateType())
2628 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2629 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2630 return Error(ID.Loc, "invalid indices for insertvalue");
2631 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2632 ID.Kind = ValID::t_Constant;
2635 case lltok::kw_icmp:
2636 case lltok::kw_fcmp: {
2637 unsigned PredVal, Opc = Lex.getUIntVal();
2638 Constant *Val0, *Val1;
2640 if (ParseCmpPredicate(PredVal, Opc) ||
2641 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2642 ParseGlobalTypeAndValue(Val0) ||
2643 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2644 ParseGlobalTypeAndValue(Val1) ||
2645 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2648 if (Val0->getType() != Val1->getType())
2649 return Error(ID.Loc, "compare operands must have the same type");
2651 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2653 if (Opc == Instruction::FCmp) {
2654 if (!Val0->getType()->isFPOrFPVectorTy())
2655 return Error(ID.Loc, "fcmp requires floating point operands");
2656 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2658 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2659 if (!Val0->getType()->isIntOrIntVectorTy() &&
2660 !Val0->getType()->getScalarType()->isPointerTy())
2661 return Error(ID.Loc, "icmp requires pointer or integer operands");
2662 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2664 ID.Kind = ValID::t_Constant;
2668 // Binary Operators.
2670 case lltok::kw_fadd:
2672 case lltok::kw_fsub:
2674 case lltok::kw_fmul:
2675 case lltok::kw_udiv:
2676 case lltok::kw_sdiv:
2677 case lltok::kw_fdiv:
2678 case lltok::kw_urem:
2679 case lltok::kw_srem:
2680 case lltok::kw_frem:
2682 case lltok::kw_lshr:
2683 case lltok::kw_ashr: {
2687 unsigned Opc = Lex.getUIntVal();
2688 Constant *Val0, *Val1;
2690 LocTy ModifierLoc = Lex.getLoc();
2691 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2692 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2693 if (EatIfPresent(lltok::kw_nuw))
2695 if (EatIfPresent(lltok::kw_nsw)) {
2697 if (EatIfPresent(lltok::kw_nuw))
2700 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2701 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2702 if (EatIfPresent(lltok::kw_exact))
2705 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2706 ParseGlobalTypeAndValue(Val0) ||
2707 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2708 ParseGlobalTypeAndValue(Val1) ||
2709 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2711 if (Val0->getType() != Val1->getType())
2712 return Error(ID.Loc, "operands of constexpr must have same type");
2713 if (!Val0->getType()->isIntOrIntVectorTy()) {
2715 return Error(ModifierLoc, "nuw only applies to integer operations");
2717 return Error(ModifierLoc, "nsw only applies to integer operations");
2719 // Check that the type is valid for the operator.
2721 case Instruction::Add:
2722 case Instruction::Sub:
2723 case Instruction::Mul:
2724 case Instruction::UDiv:
2725 case Instruction::SDiv:
2726 case Instruction::URem:
2727 case Instruction::SRem:
2728 case Instruction::Shl:
2729 case Instruction::AShr:
2730 case Instruction::LShr:
2731 if (!Val0->getType()->isIntOrIntVectorTy())
2732 return Error(ID.Loc, "constexpr requires integer operands");
2734 case Instruction::FAdd:
2735 case Instruction::FSub:
2736 case Instruction::FMul:
2737 case Instruction::FDiv:
2738 case Instruction::FRem:
2739 if (!Val0->getType()->isFPOrFPVectorTy())
2740 return Error(ID.Loc, "constexpr requires fp operands");
2742 default: llvm_unreachable("Unknown binary operator!");
2745 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2746 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2747 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2748 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2750 ID.Kind = ValID::t_Constant;
2754 // Logical Operations
2757 case lltok::kw_xor: {
2758 unsigned Opc = Lex.getUIntVal();
2759 Constant *Val0, *Val1;
2761 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2762 ParseGlobalTypeAndValue(Val0) ||
2763 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2764 ParseGlobalTypeAndValue(Val1) ||
2765 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2767 if (Val0->getType() != Val1->getType())
2768 return Error(ID.Loc, "operands of constexpr must have same type");
2769 if (!Val0->getType()->isIntOrIntVectorTy())
2770 return Error(ID.Loc,
2771 "constexpr requires integer or integer vector operands");
2772 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2773 ID.Kind = ValID::t_Constant;
2777 case lltok::kw_getelementptr:
2778 case lltok::kw_shufflevector:
2779 case lltok::kw_insertelement:
2780 case lltok::kw_extractelement:
2781 case lltok::kw_select: {
2782 unsigned Opc = Lex.getUIntVal();
2783 SmallVector<Constant*, 16> Elts;
2784 bool InBounds = false;
2786 if (Opc == Instruction::GetElementPtr)
2787 InBounds = EatIfPresent(lltok::kw_inbounds);
2788 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2789 ParseGlobalValueVector(Elts) ||
2790 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2793 if (Opc == Instruction::GetElementPtr) {
2794 if (Elts.size() == 0 ||
2795 !Elts[0]->getType()->getScalarType()->isPointerTy())
2796 return Error(ID.Loc, "getelementptr requires pointer operand");
2798 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2799 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2800 return Error(ID.Loc, "invalid indices for getelementptr");
2801 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2803 } else if (Opc == Instruction::Select) {
2804 if (Elts.size() != 3)
2805 return Error(ID.Loc, "expected three operands to select");
2806 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2808 return Error(ID.Loc, Reason);
2809 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2810 } else if (Opc == Instruction::ShuffleVector) {
2811 if (Elts.size() != 3)
2812 return Error(ID.Loc, "expected three operands to shufflevector");
2813 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2814 return Error(ID.Loc, "invalid operands to shufflevector");
2816 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2817 } else if (Opc == Instruction::ExtractElement) {
2818 if (Elts.size() != 2)
2819 return Error(ID.Loc, "expected two operands to extractelement");
2820 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2821 return Error(ID.Loc, "invalid extractelement operands");
2822 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2824 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2825 if (Elts.size() != 3)
2826 return Error(ID.Loc, "expected three operands to insertelement");
2827 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2828 return Error(ID.Loc, "invalid insertelement operands");
2830 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2833 ID.Kind = ValID::t_Constant;
2842 /// ParseGlobalValue - Parse a global value with the specified type.
2843 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2847 bool Parsed = ParseValID(ID) ||
2848 ConvertValIDToValue(Ty, ID, V, nullptr);
2849 if (V && !(C = dyn_cast<Constant>(V)))
2850 return Error(ID.Loc, "global values must be constants");
2854 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2856 return ParseType(Ty) ||
2857 ParseGlobalValue(Ty, V);
2860 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2863 LocTy KwLoc = Lex.getLoc();
2864 if (!EatIfPresent(lltok::kw_comdat))
2867 if (EatIfPresent(lltok::lparen)) {
2868 if (Lex.getKind() != lltok::ComdatVar)
2869 return TokError("expected comdat variable");
2870 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2872 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2875 if (GlobalName.empty())
2876 return TokError("comdat cannot be unnamed");
2877 C = getComdat(GlobalName, KwLoc);
2883 /// ParseGlobalValueVector
2885 /// ::= TypeAndValue (',' TypeAndValue)*
2886 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2888 if (Lex.getKind() == lltok::rbrace ||
2889 Lex.getKind() == lltok::rsquare ||
2890 Lex.getKind() == lltok::greater ||
2891 Lex.getKind() == lltok::rparen)
2895 if (ParseGlobalTypeAndValue(C)) return true;
2898 while (EatIfPresent(lltok::comma)) {
2899 if (ParseGlobalTypeAndValue(C)) return true;
2906 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2907 SmallVector<Metadata *, 16> Elts;
2908 if (ParseMDNodeVector(Elts))
2911 MD = (IsDistinct ? MDNode::getDistinct : MDNode::get)(Context, Elts);
2915 /// ParseMetadataAsValue
2916 /// ::= metadata i32 %local
2917 /// ::= metadata i32 @global
2918 /// ::= metadata i32 7
2920 /// ::= metadata !{...}
2921 /// ::= metadata !"string"
2922 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
2923 // Note: the type 'metadata' has already been parsed.
2925 if (ParseMetadata(MD, &PFS))
2928 V = MetadataAsValue::get(Context, MD);
2932 /// ParseValueAsMetadata
2936 bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
2939 if (ParseType(Ty, "expected metadata operand", Loc))
2941 if (Ty->isMetadataTy())
2942 return Error(Loc, "invalid metadata-value-metadata roundtrip");
2945 if (ParseValue(Ty, V, PFS))
2948 MD = ValueAsMetadata::get(V);
2959 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
2962 if (Lex.getKind() != lltok::exclaim)
2963 return ParseValueAsMetadata(MD, PFS);
2966 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
2971 if (Lex.getKind() == lltok::lbrace) {
2973 if (ParseMDTuple(N))
2979 // Standalone metadata reference
2981 if (Lex.getKind() == lltok::APSInt) {
2983 if (ParseMDNodeID(N))
2990 // ::= '!' STRINGCONSTANT
2992 if (ParseMDString(S))
2999 //===----------------------------------------------------------------------===//
3000 // Function Parsing.
3001 //===----------------------------------------------------------------------===//
3003 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3004 PerFunctionState *PFS) {
3005 if (Ty->isFunctionTy())
3006 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3009 case ValID::t_LocalID:
3010 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3011 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3012 return V == nullptr;
3013 case ValID::t_LocalName:
3014 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3015 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3016 return V == nullptr;
3017 case ValID::t_InlineAsm: {
3018 PointerType *PTy = dyn_cast<PointerType>(Ty);
3020 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3021 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3022 return Error(ID.Loc, "invalid type for inline asm constraint string");
3023 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3024 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3027 case ValID::t_GlobalName:
3028 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3029 return V == nullptr;
3030 case ValID::t_GlobalID:
3031 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3032 return V == nullptr;
3033 case ValID::t_APSInt:
3034 if (!Ty->isIntegerTy())
3035 return Error(ID.Loc, "integer constant must have integer type");
3036 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3037 V = ConstantInt::get(Context, ID.APSIntVal);
3039 case ValID::t_APFloat:
3040 if (!Ty->isFloatingPointTy() ||
3041 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3042 return Error(ID.Loc, "floating point constant invalid for type");
3044 // The lexer has no type info, so builds all half, float, and double FP
3045 // constants as double. Fix this here. Long double does not need this.
3046 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3049 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3051 else if (Ty->isFloatTy())
3052 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3055 V = ConstantFP::get(Context, ID.APFloatVal);
3057 if (V->getType() != Ty)
3058 return Error(ID.Loc, "floating point constant does not have type '" +
3059 getTypeString(Ty) + "'");
3063 if (!Ty->isPointerTy())
3064 return Error(ID.Loc, "null must be a pointer type");
3065 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3067 case ValID::t_Undef:
3068 // FIXME: LabelTy should not be a first-class type.
3069 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3070 return Error(ID.Loc, "invalid type for undef constant");
3071 V = UndefValue::get(Ty);
3073 case ValID::t_EmptyArray:
3074 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3075 return Error(ID.Loc, "invalid empty array initializer");
3076 V = UndefValue::get(Ty);
3079 // FIXME: LabelTy should not be a first-class type.
3080 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3081 return Error(ID.Loc, "invalid type for null constant");
3082 V = Constant::getNullValue(Ty);
3084 case ValID::t_Constant:
3085 if (ID.ConstantVal->getType() != Ty)
3086 return Error(ID.Loc, "constant expression type mismatch");
3090 case ValID::t_ConstantStruct:
3091 case ValID::t_PackedConstantStruct:
3092 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3093 if (ST->getNumElements() != ID.UIntVal)
3094 return Error(ID.Loc,
3095 "initializer with struct type has wrong # elements");
3096 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3097 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3099 // Verify that the elements are compatible with the structtype.
3100 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3101 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3102 return Error(ID.Loc, "element " + Twine(i) +
3103 " of struct initializer doesn't match struct element type");
3105 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3108 return Error(ID.Loc, "constant expression type mismatch");
3111 llvm_unreachable("Invalid ValID");
3114 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3117 return ParseValID(ID, PFS) ||
3118 ConvertValIDToValue(Ty, ID, V, PFS);
3121 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3123 return ParseType(Ty) ||
3124 ParseValue(Ty, V, PFS);
3127 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3128 PerFunctionState &PFS) {
3131 if (ParseTypeAndValue(V, PFS)) return true;
3132 if (!isa<BasicBlock>(V))
3133 return Error(Loc, "expected a basic block");
3134 BB = cast<BasicBlock>(V);
3140 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3141 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3142 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3143 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3144 // Parse the linkage.
3145 LocTy LinkageLoc = Lex.getLoc();
3148 unsigned Visibility;
3149 unsigned DLLStorageClass;
3150 AttrBuilder RetAttrs;
3152 Type *RetType = nullptr;
3153 LocTy RetTypeLoc = Lex.getLoc();
3154 if (ParseOptionalLinkage(Linkage) ||
3155 ParseOptionalVisibility(Visibility) ||
3156 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3157 ParseOptionalCallingConv(CC) ||
3158 ParseOptionalReturnAttrs(RetAttrs) ||
3159 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3162 // Verify that the linkage is ok.
3163 switch ((GlobalValue::LinkageTypes)Linkage) {
3164 case GlobalValue::ExternalLinkage:
3165 break; // always ok.
3166 case GlobalValue::ExternalWeakLinkage:
3168 return Error(LinkageLoc, "invalid linkage for function definition");
3170 case GlobalValue::PrivateLinkage:
3171 case GlobalValue::InternalLinkage:
3172 case GlobalValue::AvailableExternallyLinkage:
3173 case GlobalValue::LinkOnceAnyLinkage:
3174 case GlobalValue::LinkOnceODRLinkage:
3175 case GlobalValue::WeakAnyLinkage:
3176 case GlobalValue::WeakODRLinkage:
3178 return Error(LinkageLoc, "invalid linkage for function declaration");
3180 case GlobalValue::AppendingLinkage:
3181 case GlobalValue::CommonLinkage:
3182 return Error(LinkageLoc, "invalid function linkage type");
3185 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3186 return Error(LinkageLoc,
3187 "symbol with local linkage must have default visibility");
3189 if (!FunctionType::isValidReturnType(RetType))
3190 return Error(RetTypeLoc, "invalid function return type");
3192 LocTy NameLoc = Lex.getLoc();
3194 std::string FunctionName;
3195 if (Lex.getKind() == lltok::GlobalVar) {
3196 FunctionName = Lex.getStrVal();
3197 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3198 unsigned NameID = Lex.getUIntVal();
3200 if (NameID != NumberedVals.size())
3201 return TokError("function expected to be numbered '%" +
3202 Twine(NumberedVals.size()) + "'");
3204 return TokError("expected function name");
3209 if (Lex.getKind() != lltok::lparen)
3210 return TokError("expected '(' in function argument list");
3212 SmallVector<ArgInfo, 8> ArgList;
3214 AttrBuilder FuncAttrs;
3215 std::vector<unsigned> FwdRefAttrGrps;
3217 std::string Section;
3221 LocTy UnnamedAddrLoc;
3222 Constant *Prefix = nullptr;
3223 Constant *Prologue = nullptr;
3226 if (ParseArgumentList(ArgList, isVarArg) ||
3227 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3229 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3231 (EatIfPresent(lltok::kw_section) &&
3232 ParseStringConstant(Section)) ||
3233 parseOptionalComdat(FunctionName, C) ||
3234 ParseOptionalAlignment(Alignment) ||
3235 (EatIfPresent(lltok::kw_gc) &&
3236 ParseStringConstant(GC)) ||
3237 (EatIfPresent(lltok::kw_prefix) &&
3238 ParseGlobalTypeAndValue(Prefix)) ||
3239 (EatIfPresent(lltok::kw_prologue) &&
3240 ParseGlobalTypeAndValue(Prologue)))
3243 if (FuncAttrs.contains(Attribute::Builtin))
3244 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3246 // If the alignment was parsed as an attribute, move to the alignment field.
3247 if (FuncAttrs.hasAlignmentAttr()) {
3248 Alignment = FuncAttrs.getAlignment();
3249 FuncAttrs.removeAttribute(Attribute::Alignment);
3252 // Okay, if we got here, the function is syntactically valid. Convert types
3253 // and do semantic checks.
3254 std::vector<Type*> ParamTypeList;
3255 SmallVector<AttributeSet, 8> Attrs;
3257 if (RetAttrs.hasAttributes())
3258 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3259 AttributeSet::ReturnIndex,
3262 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3263 ParamTypeList.push_back(ArgList[i].Ty);
3264 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3265 AttrBuilder B(ArgList[i].Attrs, i + 1);
3266 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3270 if (FuncAttrs.hasAttributes())
3271 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3272 AttributeSet::FunctionIndex,
3275 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3277 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3278 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3281 FunctionType::get(RetType, ParamTypeList, isVarArg);
3282 PointerType *PFT = PointerType::getUnqual(FT);
3285 if (!FunctionName.empty()) {
3286 // If this was a definition of a forward reference, remove the definition
3287 // from the forward reference table and fill in the forward ref.
3288 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3289 ForwardRefVals.find(FunctionName);
3290 if (FRVI != ForwardRefVals.end()) {
3291 Fn = M->getFunction(FunctionName);
3293 return Error(FRVI->second.second, "invalid forward reference to "
3294 "function as global value!");
3295 if (Fn->getType() != PFT)
3296 return Error(FRVI->second.second, "invalid forward reference to "
3297 "function '" + FunctionName + "' with wrong type!");
3299 ForwardRefVals.erase(FRVI);
3300 } else if ((Fn = M->getFunction(FunctionName))) {
3301 // Reject redefinitions.
3302 return Error(NameLoc, "invalid redefinition of function '" +
3303 FunctionName + "'");
3304 } else if (M->getNamedValue(FunctionName)) {
3305 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3309 // If this is a definition of a forward referenced function, make sure the
3311 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3312 = ForwardRefValIDs.find(NumberedVals.size());
3313 if (I != ForwardRefValIDs.end()) {
3314 Fn = cast<Function>(I->second.first);
3315 if (Fn->getType() != PFT)
3316 return Error(NameLoc, "type of definition and forward reference of '@" +
3317 Twine(NumberedVals.size()) + "' disagree");
3318 ForwardRefValIDs.erase(I);
3323 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3324 else // Move the forward-reference to the correct spot in the module.
3325 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3327 if (FunctionName.empty())
3328 NumberedVals.push_back(Fn);
3330 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3331 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3332 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3333 Fn->setCallingConv(CC);
3334 Fn->setAttributes(PAL);
3335 Fn->setUnnamedAddr(UnnamedAddr);
3336 Fn->setAlignment(Alignment);
3337 Fn->setSection(Section);
3339 if (!GC.empty()) Fn->setGC(GC.c_str());
3340 Fn->setPrefixData(Prefix);
3341 Fn->setPrologueData(Prologue);
3342 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3344 // Add all of the arguments we parsed to the function.
3345 Function::arg_iterator ArgIt = Fn->arg_begin();
3346 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3347 // If the argument has a name, insert it into the argument symbol table.
3348 if (ArgList[i].Name.empty()) continue;
3350 // Set the name, if it conflicted, it will be auto-renamed.
3351 ArgIt->setName(ArgList[i].Name);
3353 if (ArgIt->getName() != ArgList[i].Name)
3354 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3355 ArgList[i].Name + "'");
3361 // Check the declaration has no block address forward references.
3363 if (FunctionName.empty()) {
3364 ID.Kind = ValID::t_GlobalID;
3365 ID.UIntVal = NumberedVals.size() - 1;
3367 ID.Kind = ValID::t_GlobalName;
3368 ID.StrVal = FunctionName;
3370 auto Blocks = ForwardRefBlockAddresses.find(ID);
3371 if (Blocks != ForwardRefBlockAddresses.end())
3372 return Error(Blocks->first.Loc,
3373 "cannot take blockaddress inside a declaration");
3377 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3379 if (FunctionNumber == -1) {
3380 ID.Kind = ValID::t_GlobalName;
3381 ID.StrVal = F.getName();
3383 ID.Kind = ValID::t_GlobalID;
3384 ID.UIntVal = FunctionNumber;
3387 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3388 if (Blocks == P.ForwardRefBlockAddresses.end())
3391 for (const auto &I : Blocks->second) {
3392 const ValID &BBID = I.first;
3393 GlobalValue *GV = I.second;
3395 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3396 "Expected local id or name");
3398 if (BBID.Kind == ValID::t_LocalName)
3399 BB = GetBB(BBID.StrVal, BBID.Loc);
3401 BB = GetBB(BBID.UIntVal, BBID.Loc);
3403 return P.Error(BBID.Loc, "referenced value is not a basic block");
3405 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3406 GV->eraseFromParent();
3409 P.ForwardRefBlockAddresses.erase(Blocks);
3413 /// ParseFunctionBody
3414 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
3415 bool LLParser::ParseFunctionBody(Function &Fn) {
3416 if (Lex.getKind() != lltok::lbrace)
3417 return TokError("expected '{' in function body");
3418 Lex.Lex(); // eat the {.
3420 int FunctionNumber = -1;
3421 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3423 PerFunctionState PFS(*this, Fn, FunctionNumber);
3425 // Resolve block addresses and allow basic blocks to be forward-declared
3426 // within this function.
3427 if (PFS.resolveForwardRefBlockAddresses())
3429 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3431 // We need at least one basic block.
3432 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
3433 return TokError("function body requires at least one basic block");
3435 while (Lex.getKind() != lltok::rbrace &&
3436 Lex.getKind() != lltok::kw_uselistorder)
3437 if (ParseBasicBlock(PFS)) return true;
3439 while (Lex.getKind() != lltok::rbrace)
3440 if (ParseUseListOrder(&PFS))
3446 // Verify function is ok.
3447 return PFS.FinishFunction();
3451 /// ::= LabelStr? Instruction*
3452 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3453 // If this basic block starts out with a name, remember it.
3455 LocTy NameLoc = Lex.getLoc();
3456 if (Lex.getKind() == lltok::LabelStr) {
3457 Name = Lex.getStrVal();
3461 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3462 if (!BB) return true;
3464 std::string NameStr;
3466 // Parse the instructions in this block until we get a terminator.
3469 // This instruction may have three possibilities for a name: a) none
3470 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3471 LocTy NameLoc = Lex.getLoc();
3475 if (Lex.getKind() == lltok::LocalVarID) {
3476 NameID = Lex.getUIntVal();
3478 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3480 } else if (Lex.getKind() == lltok::LocalVar) {
3481 NameStr = Lex.getStrVal();
3483 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3487 switch (ParseInstruction(Inst, BB, PFS)) {
3488 default: llvm_unreachable("Unknown ParseInstruction result!");
3489 case InstError: return true;
3491 BB->getInstList().push_back(Inst);
3493 // With a normal result, we check to see if the instruction is followed by
3494 // a comma and metadata.
3495 if (EatIfPresent(lltok::comma))
3496 if (ParseInstructionMetadata(Inst, &PFS))
3499 case InstExtraComma:
3500 BB->getInstList().push_back(Inst);
3502 // If the instruction parser ate an extra comma at the end of it, it
3503 // *must* be followed by metadata.
3504 if (ParseInstructionMetadata(Inst, &PFS))
3509 // Set the name on the instruction.
3510 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3511 } while (!isa<TerminatorInst>(Inst));
3516 //===----------------------------------------------------------------------===//
3517 // Instruction Parsing.
3518 //===----------------------------------------------------------------------===//
3520 /// ParseInstruction - Parse one of the many different instructions.
3522 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3523 PerFunctionState &PFS) {
3524 lltok::Kind Token = Lex.getKind();
3525 if (Token == lltok::Eof)
3526 return TokError("found end of file when expecting more instructions");
3527 LocTy Loc = Lex.getLoc();
3528 unsigned KeywordVal = Lex.getUIntVal();
3529 Lex.Lex(); // Eat the keyword.
3532 default: return Error(Loc, "expected instruction opcode");
3533 // Terminator Instructions.
3534 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3535 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3536 case lltok::kw_br: return ParseBr(Inst, PFS);
3537 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3538 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3539 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3540 case lltok::kw_resume: return ParseResume(Inst, PFS);
3541 // Binary Operators.
3545 case lltok::kw_shl: {
3546 bool NUW = EatIfPresent(lltok::kw_nuw);
3547 bool NSW = EatIfPresent(lltok::kw_nsw);
3548 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3550 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3552 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3553 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3556 case lltok::kw_fadd:
3557 case lltok::kw_fsub:
3558 case lltok::kw_fmul:
3559 case lltok::kw_fdiv:
3560 case lltok::kw_frem: {
3561 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3562 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3566 Inst->setFastMathFlags(FMF);
3570 case lltok::kw_sdiv:
3571 case lltok::kw_udiv:
3572 case lltok::kw_lshr:
3573 case lltok::kw_ashr: {
3574 bool Exact = EatIfPresent(lltok::kw_exact);
3576 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3577 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3581 case lltok::kw_urem:
3582 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3585 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3586 case lltok::kw_icmp:
3587 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3589 case lltok::kw_trunc:
3590 case lltok::kw_zext:
3591 case lltok::kw_sext:
3592 case lltok::kw_fptrunc:
3593 case lltok::kw_fpext:
3594 case lltok::kw_bitcast:
3595 case lltok::kw_addrspacecast:
3596 case lltok::kw_uitofp:
3597 case lltok::kw_sitofp:
3598 case lltok::kw_fptoui:
3599 case lltok::kw_fptosi:
3600 case lltok::kw_inttoptr:
3601 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3603 case lltok::kw_select: return ParseSelect(Inst, PFS);
3604 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3605 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3606 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3607 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3608 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3609 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3611 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3612 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3613 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3615 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3616 case lltok::kw_load: return ParseLoad(Inst, PFS);
3617 case lltok::kw_store: return ParseStore(Inst, PFS);
3618 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3619 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3620 case lltok::kw_fence: return ParseFence(Inst, PFS);
3621 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3622 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3623 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3627 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3628 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3629 if (Opc == Instruction::FCmp) {
3630 switch (Lex.getKind()) {
3631 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3632 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3633 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3634 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3635 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3636 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3637 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3638 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3639 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3640 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3641 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3642 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3643 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3644 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3645 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3646 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3647 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3650 switch (Lex.getKind()) {
3651 default: return TokError("expected icmp predicate (e.g. 'eq')");
3652 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3653 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3654 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3655 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3656 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3657 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3658 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3659 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3660 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3661 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3668 //===----------------------------------------------------------------------===//
3669 // Terminator Instructions.
3670 //===----------------------------------------------------------------------===//
3672 /// ParseRet - Parse a return instruction.
3673 /// ::= 'ret' void (',' !dbg, !1)*
3674 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3675 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3676 PerFunctionState &PFS) {
3677 SMLoc TypeLoc = Lex.getLoc();
3679 if (ParseType(Ty, true /*void allowed*/)) return true;
3681 Type *ResType = PFS.getFunction().getReturnType();
3683 if (Ty->isVoidTy()) {
3684 if (!ResType->isVoidTy())
3685 return Error(TypeLoc, "value doesn't match function result type '" +
3686 getTypeString(ResType) + "'");
3688 Inst = ReturnInst::Create(Context);
3693 if (ParseValue(Ty, RV, PFS)) return true;
3695 if (ResType != RV->getType())
3696 return Error(TypeLoc, "value doesn't match function result type '" +
3697 getTypeString(ResType) + "'");
3699 Inst = ReturnInst::Create(Context, RV);
3705 /// ::= 'br' TypeAndValue
3706 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3707 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3710 BasicBlock *Op1, *Op2;
3711 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3713 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3714 Inst = BranchInst::Create(BB);
3718 if (Op0->getType() != Type::getInt1Ty(Context))
3719 return Error(Loc, "branch condition must have 'i1' type");
3721 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3722 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3723 ParseToken(lltok::comma, "expected ',' after true destination") ||
3724 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3727 Inst = BranchInst::Create(Op1, Op2, Op0);
3733 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3735 /// ::= (TypeAndValue ',' TypeAndValue)*
3736 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3737 LocTy CondLoc, BBLoc;
3739 BasicBlock *DefaultBB;
3740 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3741 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3742 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3743 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3746 if (!Cond->getType()->isIntegerTy())
3747 return Error(CondLoc, "switch condition must have integer type");
3749 // Parse the jump table pairs.
3750 SmallPtrSet<Value*, 32> SeenCases;
3751 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3752 while (Lex.getKind() != lltok::rsquare) {
3756 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3757 ParseToken(lltok::comma, "expected ',' after case value") ||
3758 ParseTypeAndBasicBlock(DestBB, PFS))
3761 if (!SeenCases.insert(Constant).second)
3762 return Error(CondLoc, "duplicate case value in switch");
3763 if (!isa<ConstantInt>(Constant))
3764 return Error(CondLoc, "case value is not a constant integer");
3766 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3769 Lex.Lex(); // Eat the ']'.
3771 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3772 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3773 SI->addCase(Table[i].first, Table[i].second);
3780 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3781 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3784 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3785 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3786 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3789 if (!Address->getType()->isPointerTy())
3790 return Error(AddrLoc, "indirectbr address must have pointer type");
3792 // Parse the destination list.
3793 SmallVector<BasicBlock*, 16> DestList;
3795 if (Lex.getKind() != lltok::rsquare) {
3797 if (ParseTypeAndBasicBlock(DestBB, PFS))
3799 DestList.push_back(DestBB);
3801 while (EatIfPresent(lltok::comma)) {
3802 if (ParseTypeAndBasicBlock(DestBB, PFS))
3804 DestList.push_back(DestBB);
3808 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3811 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3812 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3813 IBI->addDestination(DestList[i]);
3820 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3821 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3822 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3823 LocTy CallLoc = Lex.getLoc();
3824 AttrBuilder RetAttrs, FnAttrs;
3825 std::vector<unsigned> FwdRefAttrGrps;
3828 Type *RetType = nullptr;
3831 SmallVector<ParamInfo, 16> ArgList;
3833 BasicBlock *NormalBB, *UnwindBB;
3834 if (ParseOptionalCallingConv(CC) ||
3835 ParseOptionalReturnAttrs(RetAttrs) ||
3836 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3837 ParseValID(CalleeID) ||
3838 ParseParameterList(ArgList, PFS) ||
3839 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3841 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3842 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3843 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3844 ParseTypeAndBasicBlock(UnwindBB, PFS))
3847 // If RetType is a non-function pointer type, then this is the short syntax
3848 // for the call, which means that RetType is just the return type. Infer the
3849 // rest of the function argument types from the arguments that are present.
3850 PointerType *PFTy = nullptr;
3851 FunctionType *Ty = nullptr;
3852 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3853 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3854 // Pull out the types of all of the arguments...
3855 std::vector<Type*> ParamTypes;
3856 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3857 ParamTypes.push_back(ArgList[i].V->getType());
3859 if (!FunctionType::isValidReturnType(RetType))
3860 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3862 Ty = FunctionType::get(RetType, ParamTypes, false);
3863 PFTy = PointerType::getUnqual(Ty);
3866 // Look up the callee.
3868 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3870 // Set up the Attribute for the function.
3871 SmallVector<AttributeSet, 8> Attrs;
3872 if (RetAttrs.hasAttributes())
3873 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3874 AttributeSet::ReturnIndex,
3877 SmallVector<Value*, 8> Args;
3879 // Loop through FunctionType's arguments and ensure they are specified
3880 // correctly. Also, gather any parameter attributes.
3881 FunctionType::param_iterator I = Ty->param_begin();
3882 FunctionType::param_iterator E = Ty->param_end();
3883 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3884 Type *ExpectedTy = nullptr;
3887 } else if (!Ty->isVarArg()) {
3888 return Error(ArgList[i].Loc, "too many arguments specified");
3891 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3892 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3893 getTypeString(ExpectedTy) + "'");
3894 Args.push_back(ArgList[i].V);
3895 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3896 AttrBuilder B(ArgList[i].Attrs, i + 1);
3897 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3902 return Error(CallLoc, "not enough parameters specified for call");
3904 if (FnAttrs.hasAttributes())
3905 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3906 AttributeSet::FunctionIndex,
3909 // Finish off the Attribute and check them
3910 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3912 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3913 II->setCallingConv(CC);
3914 II->setAttributes(PAL);
3915 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3921 /// ::= 'resume' TypeAndValue
3922 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3923 Value *Exn; LocTy ExnLoc;
3924 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3927 ResumeInst *RI = ResumeInst::Create(Exn);
3932 //===----------------------------------------------------------------------===//
3933 // Binary Operators.
3934 //===----------------------------------------------------------------------===//
3937 /// ::= ArithmeticOps TypeAndValue ',' Value
3939 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3940 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3941 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3942 unsigned Opc, unsigned OperandType) {
3943 LocTy Loc; Value *LHS, *RHS;
3944 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3945 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3946 ParseValue(LHS->getType(), RHS, PFS))
3950 switch (OperandType) {
3951 default: llvm_unreachable("Unknown operand type!");
3952 case 0: // int or FP.
3953 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3954 LHS->getType()->isFPOrFPVectorTy();
3956 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3957 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3961 return Error(Loc, "invalid operand type for instruction");
3963 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3968 /// ::= ArithmeticOps TypeAndValue ',' Value {
3969 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3971 LocTy Loc; Value *LHS, *RHS;
3972 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3973 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3974 ParseValue(LHS->getType(), RHS, PFS))
3977 if (!LHS->getType()->isIntOrIntVectorTy())
3978 return Error(Loc,"instruction requires integer or integer vector operands");
3980 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3986 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3987 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3988 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3990 // Parse the integer/fp comparison predicate.
3994 if (ParseCmpPredicate(Pred, Opc) ||
3995 ParseTypeAndValue(LHS, Loc, PFS) ||
3996 ParseToken(lltok::comma, "expected ',' after compare value") ||
3997 ParseValue(LHS->getType(), RHS, PFS))
4000 if (Opc == Instruction::FCmp) {
4001 if (!LHS->getType()->isFPOrFPVectorTy())
4002 return Error(Loc, "fcmp requires floating point operands");
4003 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4005 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4006 if (!LHS->getType()->isIntOrIntVectorTy() &&
4007 !LHS->getType()->getScalarType()->isPointerTy())
4008 return Error(Loc, "icmp requires integer operands");
4009 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4014 //===----------------------------------------------------------------------===//
4015 // Other Instructions.
4016 //===----------------------------------------------------------------------===//
4020 /// ::= CastOpc TypeAndValue 'to' Type
4021 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4025 Type *DestTy = nullptr;
4026 if (ParseTypeAndValue(Op, Loc, PFS) ||
4027 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4031 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4032 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4033 return Error(Loc, "invalid cast opcode for cast from '" +
4034 getTypeString(Op->getType()) + "' to '" +
4035 getTypeString(DestTy) + "'");
4037 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4042 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4043 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4045 Value *Op0, *Op1, *Op2;
4046 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4047 ParseToken(lltok::comma, "expected ',' after select condition") ||
4048 ParseTypeAndValue(Op1, PFS) ||
4049 ParseToken(lltok::comma, "expected ',' after select value") ||
4050 ParseTypeAndValue(Op2, PFS))
4053 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4054 return Error(Loc, Reason);
4056 Inst = SelectInst::Create(Op0, Op1, Op2);
4061 /// ::= 'va_arg' TypeAndValue ',' Type
4062 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4064 Type *EltTy = nullptr;
4066 if (ParseTypeAndValue(Op, PFS) ||
4067 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4068 ParseType(EltTy, TypeLoc))
4071 if (!EltTy->isFirstClassType())
4072 return Error(TypeLoc, "va_arg requires operand with first class type");
4074 Inst = new VAArgInst(Op, EltTy);
4078 /// ParseExtractElement
4079 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4080 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4083 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4084 ParseToken(lltok::comma, "expected ',' after extract value") ||
4085 ParseTypeAndValue(Op1, PFS))
4088 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4089 return Error(Loc, "invalid extractelement operands");
4091 Inst = ExtractElementInst::Create(Op0, Op1);
4095 /// ParseInsertElement
4096 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4097 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4099 Value *Op0, *Op1, *Op2;
4100 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4101 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4102 ParseTypeAndValue(Op1, PFS) ||
4103 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4104 ParseTypeAndValue(Op2, PFS))
4107 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4108 return Error(Loc, "invalid insertelement operands");
4110 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4114 /// ParseShuffleVector
4115 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4116 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4118 Value *Op0, *Op1, *Op2;
4119 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4120 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4121 ParseTypeAndValue(Op1, PFS) ||
4122 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4123 ParseTypeAndValue(Op2, PFS))
4126 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4127 return Error(Loc, "invalid shufflevector operands");
4129 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4134 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4135 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4136 Type *Ty = nullptr; LocTy TypeLoc;
4139 if (ParseType(Ty, TypeLoc) ||
4140 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4141 ParseValue(Ty, Op0, PFS) ||
4142 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4143 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4144 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4147 bool AteExtraComma = false;
4148 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4150 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4152 if (!EatIfPresent(lltok::comma))
4155 if (Lex.getKind() == lltok::MetadataVar) {
4156 AteExtraComma = true;
4160 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4161 ParseValue(Ty, Op0, PFS) ||
4162 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4163 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4164 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4168 if (!Ty->isFirstClassType())
4169 return Error(TypeLoc, "phi node must have first class type");
4171 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4172 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4173 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4175 return AteExtraComma ? InstExtraComma : InstNormal;
4179 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4181 /// ::= 'catch' TypeAndValue
4183 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4184 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4185 Type *Ty = nullptr; LocTy TyLoc;
4186 Value *PersFn; LocTy PersFnLoc;
4188 if (ParseType(Ty, TyLoc) ||
4189 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4190 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4193 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4194 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4196 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4197 LandingPadInst::ClauseType CT;
4198 if (EatIfPresent(lltok::kw_catch))
4199 CT = LandingPadInst::Catch;
4200 else if (EatIfPresent(lltok::kw_filter))
4201 CT = LandingPadInst::Filter;
4203 return TokError("expected 'catch' or 'filter' clause type");
4207 if (ParseTypeAndValue(V, VLoc, PFS)) {
4212 // A 'catch' type expects a non-array constant. A filter clause expects an
4214 if (CT == LandingPadInst::Catch) {
4215 if (isa<ArrayType>(V->getType()))
4216 Error(VLoc, "'catch' clause has an invalid type");
4218 if (!isa<ArrayType>(V->getType()))
4219 Error(VLoc, "'filter' clause has an invalid type");
4222 LP->addClause(cast<Constant>(V));
4230 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4231 /// ParameterList OptionalAttrs
4232 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4233 /// ParameterList OptionalAttrs
4234 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4235 /// ParameterList OptionalAttrs
4236 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4237 CallInst::TailCallKind TCK) {
4238 AttrBuilder RetAttrs, FnAttrs;
4239 std::vector<unsigned> FwdRefAttrGrps;
4242 Type *RetType = nullptr;
4245 SmallVector<ParamInfo, 16> ArgList;
4246 LocTy CallLoc = Lex.getLoc();
4248 if ((TCK != CallInst::TCK_None &&
4249 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4250 ParseOptionalCallingConv(CC) ||
4251 ParseOptionalReturnAttrs(RetAttrs) ||
4252 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4253 ParseValID(CalleeID) ||
4254 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4255 PFS.getFunction().isVarArg()) ||
4256 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4260 // If RetType is a non-function pointer type, then this is the short syntax
4261 // for the call, which means that RetType is just the return type. Infer the
4262 // rest of the function argument types from the arguments that are present.
4263 PointerType *PFTy = nullptr;
4264 FunctionType *Ty = nullptr;
4265 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4266 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4267 // Pull out the types of all of the arguments...
4268 std::vector<Type*> ParamTypes;
4269 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4270 ParamTypes.push_back(ArgList[i].V->getType());
4272 if (!FunctionType::isValidReturnType(RetType))
4273 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4275 Ty = FunctionType::get(RetType, ParamTypes, false);
4276 PFTy = PointerType::getUnqual(Ty);
4279 // Look up the callee.
4281 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4283 // Set up the Attribute for the function.
4284 SmallVector<AttributeSet, 8> Attrs;
4285 if (RetAttrs.hasAttributes())
4286 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4287 AttributeSet::ReturnIndex,
4290 SmallVector<Value*, 8> Args;
4292 // Loop through FunctionType's arguments and ensure they are specified
4293 // correctly. Also, gather any parameter attributes.
4294 FunctionType::param_iterator I = Ty->param_begin();
4295 FunctionType::param_iterator E = Ty->param_end();
4296 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4297 Type *ExpectedTy = nullptr;
4300 } else if (!Ty->isVarArg()) {
4301 return Error(ArgList[i].Loc, "too many arguments specified");
4304 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4305 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4306 getTypeString(ExpectedTy) + "'");
4307 Args.push_back(ArgList[i].V);
4308 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4309 AttrBuilder B(ArgList[i].Attrs, i + 1);
4310 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4315 return Error(CallLoc, "not enough parameters specified for call");
4317 if (FnAttrs.hasAttributes())
4318 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4319 AttributeSet::FunctionIndex,
4322 // Finish off the Attribute and check them
4323 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4325 CallInst *CI = CallInst::Create(Callee, Args);
4326 CI->setTailCallKind(TCK);
4327 CI->setCallingConv(CC);
4328 CI->setAttributes(PAL);
4329 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4334 //===----------------------------------------------------------------------===//
4335 // Memory Instructions.
4336 //===----------------------------------------------------------------------===//
4339 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4340 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4341 Value *Size = nullptr;
4343 unsigned Alignment = 0;
4346 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4348 if (ParseType(Ty)) return true;
4350 bool AteExtraComma = false;
4351 if (EatIfPresent(lltok::comma)) {
4352 if (Lex.getKind() == lltok::kw_align) {
4353 if (ParseOptionalAlignment(Alignment)) return true;
4354 } else if (Lex.getKind() == lltok::MetadataVar) {
4355 AteExtraComma = true;
4357 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4358 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4363 if (Size && !Size->getType()->isIntegerTy())
4364 return Error(SizeLoc, "element count must have integer type");
4366 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4367 AI->setUsedWithInAlloca(IsInAlloca);
4369 return AteExtraComma ? InstExtraComma : InstNormal;
4373 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4374 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4375 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4376 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4377 Value *Val; LocTy Loc;
4378 unsigned Alignment = 0;
4379 bool AteExtraComma = false;
4380 bool isAtomic = false;
4381 AtomicOrdering Ordering = NotAtomic;
4382 SynchronizationScope Scope = CrossThread;
4384 if (Lex.getKind() == lltok::kw_atomic) {
4389 bool isVolatile = false;
4390 if (Lex.getKind() == lltok::kw_volatile) {
4395 if (ParseTypeAndValue(Val, Loc, PFS) ||
4396 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4397 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4400 if (!Val->getType()->isPointerTy() ||
4401 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4402 return Error(Loc, "load operand must be a pointer to a first class type");
4403 if (isAtomic && !Alignment)
4404 return Error(Loc, "atomic load must have explicit non-zero alignment");
4405 if (Ordering == Release || Ordering == AcquireRelease)
4406 return Error(Loc, "atomic load cannot use Release ordering");
4408 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4409 return AteExtraComma ? InstExtraComma : InstNormal;
4414 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4415 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4416 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4417 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4418 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4419 unsigned Alignment = 0;
4420 bool AteExtraComma = false;
4421 bool isAtomic = false;
4422 AtomicOrdering Ordering = NotAtomic;
4423 SynchronizationScope Scope = CrossThread;
4425 if (Lex.getKind() == lltok::kw_atomic) {
4430 bool isVolatile = false;
4431 if (Lex.getKind() == lltok::kw_volatile) {
4436 if (ParseTypeAndValue(Val, Loc, PFS) ||
4437 ParseToken(lltok::comma, "expected ',' after store operand") ||
4438 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4439 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4440 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4443 if (!Ptr->getType()->isPointerTy())
4444 return Error(PtrLoc, "store operand must be a pointer");
4445 if (!Val->getType()->isFirstClassType())
4446 return Error(Loc, "store operand must be a first class value");
4447 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4448 return Error(Loc, "stored value and pointer type do not match");
4449 if (isAtomic && !Alignment)
4450 return Error(Loc, "atomic store must have explicit non-zero alignment");
4451 if (Ordering == Acquire || Ordering == AcquireRelease)
4452 return Error(Loc, "atomic store cannot use Acquire ordering");
4454 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4455 return AteExtraComma ? InstExtraComma : InstNormal;
4459 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4460 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4461 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4462 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4463 bool AteExtraComma = false;
4464 AtomicOrdering SuccessOrdering = NotAtomic;
4465 AtomicOrdering FailureOrdering = NotAtomic;
4466 SynchronizationScope Scope = CrossThread;
4467 bool isVolatile = false;
4468 bool isWeak = false;
4470 if (EatIfPresent(lltok::kw_weak))
4473 if (EatIfPresent(lltok::kw_volatile))
4476 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4477 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4478 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4479 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4480 ParseTypeAndValue(New, NewLoc, PFS) ||
4481 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4482 ParseOrdering(FailureOrdering))
4485 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4486 return TokError("cmpxchg cannot be unordered");
4487 if (SuccessOrdering < FailureOrdering)
4488 return TokError("cmpxchg must be at least as ordered on success as failure");
4489 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4490 return TokError("cmpxchg failure ordering cannot include release semantics");
4491 if (!Ptr->getType()->isPointerTy())
4492 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4493 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4494 return Error(CmpLoc, "compare value and pointer type do not match");
4495 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4496 return Error(NewLoc, "new value and pointer type do not match");
4497 if (!New->getType()->isIntegerTy())
4498 return Error(NewLoc, "cmpxchg operand must be an integer");
4499 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4500 if (Size < 8 || (Size & (Size - 1)))
4501 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4504 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4505 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4506 CXI->setVolatile(isVolatile);
4507 CXI->setWeak(isWeak);
4509 return AteExtraComma ? InstExtraComma : InstNormal;
4513 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4514 /// 'singlethread'? AtomicOrdering
4515 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4516 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4517 bool AteExtraComma = false;
4518 AtomicOrdering Ordering = NotAtomic;
4519 SynchronizationScope Scope = CrossThread;
4520 bool isVolatile = false;
4521 AtomicRMWInst::BinOp Operation;
4523 if (EatIfPresent(lltok::kw_volatile))
4526 switch (Lex.getKind()) {
4527 default: return TokError("expected binary operation in atomicrmw");
4528 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4529 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4530 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4531 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4532 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4533 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4534 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4535 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4536 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4537 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4538 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4540 Lex.Lex(); // Eat the operation.
4542 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4543 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4544 ParseTypeAndValue(Val, ValLoc, PFS) ||
4545 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4548 if (Ordering == Unordered)
4549 return TokError("atomicrmw cannot be unordered");
4550 if (!Ptr->getType()->isPointerTy())
4551 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4552 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4553 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4554 if (!Val->getType()->isIntegerTy())
4555 return Error(ValLoc, "atomicrmw operand must be an integer");
4556 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4557 if (Size < 8 || (Size & (Size - 1)))
4558 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4561 AtomicRMWInst *RMWI =
4562 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4563 RMWI->setVolatile(isVolatile);
4565 return AteExtraComma ? InstExtraComma : InstNormal;
4569 /// ::= 'fence' 'singlethread'? AtomicOrdering
4570 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4571 AtomicOrdering Ordering = NotAtomic;
4572 SynchronizationScope Scope = CrossThread;
4573 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4576 if (Ordering == Unordered)
4577 return TokError("fence cannot be unordered");
4578 if (Ordering == Monotonic)
4579 return TokError("fence cannot be monotonic");
4581 Inst = new FenceInst(Context, Ordering, Scope);
4585 /// ParseGetElementPtr
4586 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4587 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4588 Value *Ptr = nullptr;
4589 Value *Val = nullptr;
4592 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4594 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4596 Type *BaseType = Ptr->getType();
4597 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4598 if (!BasePointerType)
4599 return Error(Loc, "base of getelementptr must be a pointer");
4601 SmallVector<Value*, 16> Indices;
4602 bool AteExtraComma = false;
4603 while (EatIfPresent(lltok::comma)) {
4604 if (Lex.getKind() == lltok::MetadataVar) {
4605 AteExtraComma = true;
4608 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4609 if (!Val->getType()->getScalarType()->isIntegerTy())
4610 return Error(EltLoc, "getelementptr index must be an integer");
4611 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4612 return Error(EltLoc, "getelementptr index type missmatch");
4613 if (Val->getType()->isVectorTy()) {
4614 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4615 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4616 if (ValNumEl != PtrNumEl)
4617 return Error(EltLoc,
4618 "getelementptr vector index has a wrong number of elements");
4620 Indices.push_back(Val);
4623 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4624 return Error(Loc, "base element of getelementptr must be sized");
4626 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4627 return Error(Loc, "invalid getelementptr indices");
4628 Inst = GetElementPtrInst::Create(Ptr, Indices);
4630 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4631 return AteExtraComma ? InstExtraComma : InstNormal;
4634 /// ParseExtractValue
4635 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4636 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4637 Value *Val; LocTy Loc;
4638 SmallVector<unsigned, 4> Indices;
4640 if (ParseTypeAndValue(Val, Loc, PFS) ||
4641 ParseIndexList(Indices, AteExtraComma))
4644 if (!Val->getType()->isAggregateType())
4645 return Error(Loc, "extractvalue operand must be aggregate type");
4647 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4648 return Error(Loc, "invalid indices for extractvalue");
4649 Inst = ExtractValueInst::Create(Val, Indices);
4650 return AteExtraComma ? InstExtraComma : InstNormal;
4653 /// ParseInsertValue
4654 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4655 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4656 Value *Val0, *Val1; LocTy Loc0, Loc1;
4657 SmallVector<unsigned, 4> Indices;
4659 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4660 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4661 ParseTypeAndValue(Val1, Loc1, PFS) ||
4662 ParseIndexList(Indices, AteExtraComma))
4665 if (!Val0->getType()->isAggregateType())
4666 return Error(Loc0, "insertvalue operand must be aggregate type");
4668 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4669 return Error(Loc0, "invalid indices for insertvalue");
4670 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4671 return AteExtraComma ? InstExtraComma : InstNormal;
4674 //===----------------------------------------------------------------------===//
4675 // Embedded metadata.
4676 //===----------------------------------------------------------------------===//
4678 /// ParseMDNodeVector
4679 /// ::= { Element (',' Element)* }
4681 /// ::= 'null' | TypeAndValue
4682 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
4683 if (ParseToken(lltok::lbrace, "expected '{' here"))
4686 // Check for an empty list.
4687 if (EatIfPresent(lltok::rbrace))
4691 // Null is a special case since it is typeless.
4692 if (EatIfPresent(lltok::kw_null)) {
4693 Elts.push_back(nullptr);
4698 if (ParseMetadata(MD, nullptr))
4701 } while (EatIfPresent(lltok::comma));
4703 return ParseToken(lltok::rbrace, "expected end of metadata node");
4706 //===----------------------------------------------------------------------===//
4707 // Use-list order directives.
4708 //===----------------------------------------------------------------------===//
4709 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4712 return Error(Loc, "value has no uses");
4714 unsigned NumUses = 0;
4715 SmallDenseMap<const Use *, unsigned, 16> Order;
4716 for (const Use &U : V->uses()) {
4717 if (++NumUses > Indexes.size())
4719 Order[&U] = Indexes[NumUses - 1];
4722 return Error(Loc, "value only has one use");
4723 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4724 return Error(Loc, "wrong number of indexes, expected " +
4725 Twine(std::distance(V->use_begin(), V->use_end())));
4727 V->sortUseList([&](const Use &L, const Use &R) {
4728 return Order.lookup(&L) < Order.lookup(&R);
4733 /// ParseUseListOrderIndexes
4734 /// ::= '{' uint32 (',' uint32)+ '}'
4735 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4736 SMLoc Loc = Lex.getLoc();
4737 if (ParseToken(lltok::lbrace, "expected '{' here"))
4739 if (Lex.getKind() == lltok::rbrace)
4740 return Lex.Error("expected non-empty list of uselistorder indexes");
4742 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4743 // indexes should be distinct numbers in the range [0, size-1], and should
4745 unsigned Offset = 0;
4747 bool IsOrdered = true;
4748 assert(Indexes.empty() && "Expected empty order vector");
4751 if (ParseUInt32(Index))
4754 // Update consistency checks.
4755 Offset += Index - Indexes.size();
4756 Max = std::max(Max, Index);
4757 IsOrdered &= Index == Indexes.size();
4759 Indexes.push_back(Index);
4760 } while (EatIfPresent(lltok::comma));
4762 if (ParseToken(lltok::rbrace, "expected '}' here"))
4765 if (Indexes.size() < 2)
4766 return Error(Loc, "expected >= 2 uselistorder indexes");
4767 if (Offset != 0 || Max >= Indexes.size())
4768 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4770 return Error(Loc, "expected uselistorder indexes to change the order");
4775 /// ParseUseListOrder
4776 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4777 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4778 SMLoc Loc = Lex.getLoc();
4779 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4783 SmallVector<unsigned, 16> Indexes;
4784 if (ParseTypeAndValue(V, PFS) ||
4785 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4786 ParseUseListOrderIndexes(Indexes))
4789 return sortUseListOrder(V, Indexes, Loc);
4792 /// ParseUseListOrderBB
4793 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4794 bool LLParser::ParseUseListOrderBB() {
4795 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4796 SMLoc Loc = Lex.getLoc();
4800 SmallVector<unsigned, 16> Indexes;
4801 if (ParseValID(Fn) ||
4802 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4803 ParseValID(Label) ||
4804 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4805 ParseUseListOrderIndexes(Indexes))
4808 // Check the function.
4810 if (Fn.Kind == ValID::t_GlobalName)
4811 GV = M->getNamedValue(Fn.StrVal);
4812 else if (Fn.Kind == ValID::t_GlobalID)
4813 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4815 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4817 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4818 auto *F = dyn_cast<Function>(GV);
4820 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4821 if (F->isDeclaration())
4822 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4824 // Check the basic block.
4825 if (Label.Kind == ValID::t_LocalID)
4826 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4827 if (Label.Kind != ValID::t_LocalName)
4828 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4829 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4831 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4832 if (!isa<BasicBlock>(V))
4833 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4835 return sortUseListOrder(V, Indexes, Loc);