1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/ValueSymbolTable.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 #include "llvm/Support/raw_ostream.h"
32 static std::string getTypeString(Type *T) {
34 raw_string_ostream Tmp(Result);
39 /// Run: module ::= toplevelentity*
40 bool LLParser::Run() {
44 return ParseTopLevelEntities() ||
45 ValidateEndOfModule();
48 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
50 bool LLParser::ValidateEndOfModule() {
51 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
52 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
54 // Handle any function attribute group forward references.
55 for (std::map<Value*, std::vector<unsigned> >::iterator
56 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
59 std::vector<unsigned> &Vec = I->second;
62 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
64 B.merge(NumberedAttrBuilders[*VI]);
66 if (Function *Fn = dyn_cast<Function>(V)) {
67 AttributeSet AS = Fn->getAttributes();
68 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
69 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
70 AS.getFnAttributes());
74 // If the alignment was parsed as an attribute, move to the alignment
76 if (FnAttrs.hasAlignmentAttr()) {
77 Fn->setAlignment(FnAttrs.getAlignment());
78 FnAttrs.removeAttribute(Attribute::Alignment);
81 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
82 AttributeSet::get(Context,
83 AttributeSet::FunctionIndex,
85 Fn->setAttributes(AS);
86 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
87 AttributeSet AS = CI->getAttributes();
88 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
89 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
90 AS.getFnAttributes());
92 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
93 AttributeSet::get(Context,
94 AttributeSet::FunctionIndex,
96 CI->setAttributes(AS);
97 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
98 AttributeSet AS = II->getAttributes();
99 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
100 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
101 AS.getFnAttributes());
103 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
104 AttributeSet::get(Context,
105 AttributeSet::FunctionIndex,
107 II->setAttributes(AS);
109 llvm_unreachable("invalid object with forward attribute group reference");
113 // If there are entries in ForwardRefBlockAddresses at this point, the
114 // function was never defined.
115 if (!ForwardRefBlockAddresses.empty())
116 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
117 "expected function name in blockaddress");
119 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
120 if (NumberedTypes[i].second.isValid())
121 return Error(NumberedTypes[i].second,
122 "use of undefined type '%" + Twine(i) + "'");
124 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
125 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
126 if (I->second.second.isValid())
127 return Error(I->second.second,
128 "use of undefined type named '" + I->getKey() + "'");
130 if (!ForwardRefComdats.empty())
131 return Error(ForwardRefComdats.begin()->second,
132 "use of undefined comdat '$" +
133 ForwardRefComdats.begin()->first + "'");
135 if (!ForwardRefVals.empty())
136 return Error(ForwardRefVals.begin()->second.second,
137 "use of undefined value '@" + ForwardRefVals.begin()->first +
140 if (!ForwardRefValIDs.empty())
141 return Error(ForwardRefValIDs.begin()->second.second,
142 "use of undefined value '@" +
143 Twine(ForwardRefValIDs.begin()->first) + "'");
145 if (!ForwardRefMDNodes.empty())
146 return Error(ForwardRefMDNodes.begin()->second.second,
147 "use of undefined metadata '!" +
148 Twine(ForwardRefMDNodes.begin()->first) + "'");
150 // Resolve metadata cycles.
151 for (auto &N : NumberedMetadata)
152 if (N && !N->isResolved())
155 // Look for intrinsic functions and CallInst that need to be upgraded
156 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
157 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
159 UpgradeDebugInfo(*M);
164 //===----------------------------------------------------------------------===//
165 // Top-Level Entities
166 //===----------------------------------------------------------------------===//
168 bool LLParser::ParseTopLevelEntities() {
170 switch (Lex.getKind()) {
171 default: return TokError("expected top-level entity");
172 case lltok::Eof: return false;
173 case lltok::kw_declare: if (ParseDeclare()) return true; break;
174 case lltok::kw_define: if (ParseDefine()) return true; break;
175 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
176 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
177 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
178 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
179 case lltok::LocalVar: if (ParseNamedType()) return true; break;
180 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
181 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
182 case lltok::ComdatVar: if (parseComdat()) return true; break;
183 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
184 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
186 // The Global variable production with no name can have many different
187 // optional leading prefixes, the production is:
188 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
189 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
190 // ('constant'|'global') ...
191 case lltok::kw_private: // OptionalLinkage
192 case lltok::kw_internal: // OptionalLinkage
193 case lltok::kw_weak: // OptionalLinkage
194 case lltok::kw_weak_odr: // OptionalLinkage
195 case lltok::kw_linkonce: // OptionalLinkage
196 case lltok::kw_linkonce_odr: // OptionalLinkage
197 case lltok::kw_appending: // OptionalLinkage
198 case lltok::kw_common: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: // OptionalLinkage
201 case lltok::kw_default: // OptionalVisibility
202 case lltok::kw_hidden: // OptionalVisibility
203 case lltok::kw_protected: // OptionalVisibility
204 case lltok::kw_dllimport: // OptionalDLLStorageClass
205 case lltok::kw_dllexport: // OptionalDLLStorageClass
206 case lltok::kw_thread_local: // OptionalThreadLocal
207 case lltok::kw_addrspace: // OptionalAddrSpace
208 case lltok::kw_constant: // GlobalType
209 case lltok::kw_global: { // GlobalType
210 unsigned Linkage, Visibility, DLLStorageClass;
212 GlobalVariable::ThreadLocalMode TLM;
214 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
215 ParseOptionalVisibility(Visibility) ||
216 ParseOptionalDLLStorageClass(DLLStorageClass) ||
217 ParseOptionalThreadLocal(TLM) ||
218 parseOptionalUnnamedAddr(UnnamedAddr) ||
219 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
220 DLLStorageClass, TLM, UnnamedAddr))
225 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
226 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
227 case lltok::kw_uselistorder_bb:
228 if (ParseUseListOrderBB()) return true; break;
235 /// ::= 'module' 'asm' STRINGCONSTANT
236 bool LLParser::ParseModuleAsm() {
237 assert(Lex.getKind() == lltok::kw_module);
241 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
242 ParseStringConstant(AsmStr)) return true;
244 M->appendModuleInlineAsm(AsmStr);
249 /// ::= 'target' 'triple' '=' STRINGCONSTANT
250 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
251 bool LLParser::ParseTargetDefinition() {
252 assert(Lex.getKind() == lltok::kw_target);
255 default: return TokError("unknown target property");
256 case lltok::kw_triple:
258 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
259 ParseStringConstant(Str))
261 M->setTargetTriple(Str);
263 case lltok::kw_datalayout:
265 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
266 ParseStringConstant(Str))
268 M->setDataLayout(Str);
274 /// ::= 'deplibs' '=' '[' ']'
275 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
276 /// FIXME: Remove in 4.0. Currently parse, but ignore.
277 bool LLParser::ParseDepLibs() {
278 assert(Lex.getKind() == lltok::kw_deplibs);
280 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
281 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
284 if (EatIfPresent(lltok::rsquare))
289 if (ParseStringConstant(Str)) return true;
290 } while (EatIfPresent(lltok::comma));
292 return ParseToken(lltok::rsquare, "expected ']' at end of list");
295 /// ParseUnnamedType:
296 /// ::= LocalVarID '=' 'type' type
297 bool LLParser::ParseUnnamedType() {
298 LocTy TypeLoc = Lex.getLoc();
299 unsigned TypeID = Lex.getUIntVal();
300 Lex.Lex(); // eat LocalVarID;
302 if (ParseToken(lltok::equal, "expected '=' after name") ||
303 ParseToken(lltok::kw_type, "expected 'type' after '='"))
306 if (TypeID >= NumberedTypes.size())
307 NumberedTypes.resize(TypeID+1);
309 Type *Result = nullptr;
310 if (ParseStructDefinition(TypeLoc, "",
311 NumberedTypes[TypeID], Result)) return true;
313 if (!isa<StructType>(Result)) {
314 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
316 return Error(TypeLoc, "non-struct types may not be recursive");
317 Entry.first = Result;
318 Entry.second = SMLoc();
326 /// ::= LocalVar '=' 'type' type
327 bool LLParser::ParseNamedType() {
328 std::string Name = Lex.getStrVal();
329 LocTy NameLoc = Lex.getLoc();
330 Lex.Lex(); // eat LocalVar.
332 if (ParseToken(lltok::equal, "expected '=' after name") ||
333 ParseToken(lltok::kw_type, "expected 'type' after name"))
336 Type *Result = nullptr;
337 if (ParseStructDefinition(NameLoc, Name,
338 NamedTypes[Name], Result)) return true;
340 if (!isa<StructType>(Result)) {
341 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
343 return Error(NameLoc, "non-struct types may not be recursive");
344 Entry.first = Result;
345 Entry.second = SMLoc();
353 /// ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
359 return ParseFunctionHeader(F, false);
363 /// ::= 'define' FunctionHeader '{' ...
364 bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
376 bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
379 else if (Lex.getKind() == lltok::kw_global)
383 return TokError("expected 'global' or 'constant'");
389 /// ParseUnnamedGlobal:
390 /// OptionalVisibility ALIAS ...
391 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392 /// ... -> global variable
393 /// GlobalID '=' OptionalVisibility ALIAS ...
394 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395 /// ... -> global variable
396 bool LLParser::ParseUnnamedGlobal() {
397 unsigned VarID = NumberedVals.size();
399 LocTy NameLoc = Lex.getLoc();
401 // Handle the GlobalID form.
402 if (Lex.getKind() == lltok::GlobalID) {
403 if (Lex.getUIntVal() != VarID)
404 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
406 Lex.Lex(); // eat GlobalID;
408 if (ParseToken(lltok::equal, "expected '=' after name"))
413 unsigned Linkage, Visibility, DLLStorageClass;
414 GlobalVariable::ThreadLocalMode TLM;
416 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
417 ParseOptionalVisibility(Visibility) ||
418 ParseOptionalDLLStorageClass(DLLStorageClass) ||
419 ParseOptionalThreadLocal(TLM) ||
420 parseOptionalUnnamedAddr(UnnamedAddr))
423 if (Lex.getKind() != lltok::kw_alias)
424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
425 DLLStorageClass, TLM, UnnamedAddr);
426 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
430 /// ParseNamedGlobal:
431 /// GlobalVar '=' OptionalVisibility ALIAS ...
432 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433 /// ... -> global variable
434 bool LLParser::ParseNamedGlobal() {
435 assert(Lex.getKind() == lltok::GlobalVar);
436 LocTy NameLoc = Lex.getLoc();
437 std::string Name = Lex.getStrVal();
441 unsigned Linkage, Visibility, DLLStorageClass;
442 GlobalVariable::ThreadLocalMode TLM;
444 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445 ParseOptionalLinkage(Linkage, HasLinkage) ||
446 ParseOptionalVisibility(Visibility) ||
447 ParseOptionalDLLStorageClass(DLLStorageClass) ||
448 ParseOptionalThreadLocal(TLM) ||
449 parseOptionalUnnamedAddr(UnnamedAddr))
452 if (Lex.getKind() != lltok::kw_alias)
453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
454 DLLStorageClass, TLM, UnnamedAddr);
456 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
460 bool LLParser::parseComdat() {
461 assert(Lex.getKind() == lltok::ComdatVar);
462 std::string Name = Lex.getStrVal();
463 LocTy NameLoc = Lex.getLoc();
466 if (ParseToken(lltok::equal, "expected '=' here"))
469 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470 return TokError("expected comdat type");
472 Comdat::SelectionKind SK;
473 switch (Lex.getKind()) {
475 return TokError("unknown selection kind");
479 case lltok::kw_exactmatch:
480 SK = Comdat::ExactMatch;
482 case lltok::kw_largest:
483 SK = Comdat::Largest;
485 case lltok::kw_noduplicates:
486 SK = Comdat::NoDuplicates;
488 case lltok::kw_samesize:
489 SK = Comdat::SameSize;
494 // See if the comdat was forward referenced, if so, use the comdat.
495 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
501 if (I != ComdatSymTab.end())
504 C = M->getOrInsertComdat(Name);
505 C->setSelectionKind(SK);
511 // ::= '!' STRINGCONSTANT
512 bool LLParser::ParseMDString(MDString *&Result) {
514 if (ParseStringConstant(Str)) return true;
515 llvm::UpgradeMDStringConstant(Str);
516 Result = MDString::get(Context, Str);
521 // ::= '!' MDNodeNumber
522 bool LLParser::ParseMDNodeID(MDNode *&Result) {
523 // !{ ..., !42, ... }
525 if (ParseUInt32(MID))
528 // If not a forward reference, just return it now.
529 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
530 Result = NumberedMetadata[MID];
534 // Otherwise, create MDNode forward reference.
535 auto &FwdRef = ForwardRefMDNodes[MID];
536 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
538 if (NumberedMetadata.size() <= MID)
539 NumberedMetadata.resize(MID+1);
540 Result = FwdRef.first.get();
541 NumberedMetadata[MID].reset(Result);
545 /// ParseNamedMetadata:
546 /// !foo = !{ !1, !2 }
547 bool LLParser::ParseNamedMetadata() {
548 assert(Lex.getKind() == lltok::MetadataVar);
549 std::string Name = Lex.getStrVal();
552 if (ParseToken(lltok::equal, "expected '=' here") ||
553 ParseToken(lltok::exclaim, "Expected '!' here") ||
554 ParseToken(lltok::lbrace, "Expected '{' here"))
557 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
558 if (Lex.getKind() != lltok::rbrace)
560 if (ParseToken(lltok::exclaim, "Expected '!' here"))
564 if (ParseMDNodeID(N)) return true;
566 } while (EatIfPresent(lltok::comma));
568 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
574 /// ParseStandaloneMetadata:
576 bool LLParser::ParseStandaloneMetadata() {
577 assert(Lex.getKind() == lltok::exclaim);
579 unsigned MetadataID = 0;
582 if (ParseUInt32(MetadataID) ||
583 ParseToken(lltok::equal, "expected '=' here"))
586 // Detect common error, from old metadata syntax.
587 if (Lex.getKind() == lltok::Type)
588 return TokError("unexpected type in metadata definition");
590 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
591 if (Lex.getKind() == lltok::MetadataVar) {
592 if (ParseSpecializedMDNode(Init, IsDistinct))
594 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
595 ParseMDTuple(Init, IsDistinct))
598 // See if this was forward referenced, if so, handle it.
599 auto FI = ForwardRefMDNodes.find(MetadataID);
600 if (FI != ForwardRefMDNodes.end()) {
601 FI->second.first->replaceAllUsesWith(Init);
602 ForwardRefMDNodes.erase(FI);
604 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
606 if (MetadataID >= NumberedMetadata.size())
607 NumberedMetadata.resize(MetadataID+1);
609 if (NumberedMetadata[MetadataID] != nullptr)
610 return TokError("Metadata id is already used");
611 NumberedMetadata[MetadataID].reset(Init);
617 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
618 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
619 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
623 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
624 /// OptionalDLLStorageClass OptionalThreadLocal
625 /// OptionalUnNammedAddr 'alias' Aliasee
630 /// Everything through OptionalUnNammedAddr has already been parsed.
632 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
633 unsigned Visibility, unsigned DLLStorageClass,
634 GlobalVariable::ThreadLocalMode TLM,
636 assert(Lex.getKind() == lltok::kw_alias);
639 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
641 if(!GlobalAlias::isValidLinkage(Linkage))
642 return Error(NameLoc, "invalid linkage type for alias");
644 if (!isValidVisibilityForLinkage(Visibility, L))
645 return Error(NameLoc,
646 "symbol with local linkage must have default visibility");
649 LocTy AliaseeLoc = Lex.getLoc();
650 if (Lex.getKind() != lltok::kw_bitcast &&
651 Lex.getKind() != lltok::kw_getelementptr &&
652 Lex.getKind() != lltok::kw_addrspacecast &&
653 Lex.getKind() != lltok::kw_inttoptr) {
654 if (ParseGlobalTypeAndValue(Aliasee))
657 // The bitcast dest type is not present, it is implied by the dest type.
661 if (ID.Kind != ValID::t_Constant)
662 return Error(AliaseeLoc, "invalid aliasee");
663 Aliasee = ID.ConstantVal;
666 Type *AliaseeType = Aliasee->getType();
667 auto *PTy = dyn_cast<PointerType>(AliaseeType);
669 return Error(AliaseeLoc, "An alias must have pointer type");
670 Type *Ty = PTy->getElementType();
671 unsigned AddrSpace = PTy->getAddressSpace();
673 // Okay, create the alias but do not insert it into the module yet.
674 std::unique_ptr<GlobalAlias> GA(
675 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
676 Name, Aliasee, /*Parent*/ nullptr));
677 GA->setThreadLocalMode(TLM);
678 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
679 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
680 GA->setUnnamedAddr(UnnamedAddr);
682 // See if this value already exists in the symbol table. If so, it is either
683 // a redefinition or a definition of a forward reference.
684 if (GlobalValue *Val = M->getNamedValue(Name)) {
685 // See if this was a redefinition. If so, there is no entry in
687 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
688 I = ForwardRefVals.find(Name);
689 if (I == ForwardRefVals.end())
690 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
692 // Otherwise, this was a definition of forward ref. Verify that types
694 if (Val->getType() != GA->getType())
695 return Error(NameLoc,
696 "forward reference and definition of alias have different types");
698 // If they agree, just RAUW the old value with the alias and remove the
700 Val->replaceAllUsesWith(GA.get());
701 Val->eraseFromParent();
702 ForwardRefVals.erase(I);
705 // Insert into the module, we know its name won't collide now.
706 M->getAliasList().push_back(GA.get());
707 assert(GA->getName() == Name && "Should not be a name conflict!");
709 // The module owns this now
716 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
717 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
718 /// OptionalExternallyInitialized GlobalType Type Const
719 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
720 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
721 /// OptionalExternallyInitialized GlobalType Type Const
723 /// Everything up to and including OptionalUnNammedAddr has been parsed
726 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
727 unsigned Linkage, bool HasLinkage,
728 unsigned Visibility, unsigned DLLStorageClass,
729 GlobalVariable::ThreadLocalMode TLM,
731 if (!isValidVisibilityForLinkage(Visibility, Linkage))
732 return Error(NameLoc,
733 "symbol with local linkage must have default visibility");
736 bool IsConstant, IsExternallyInitialized;
737 LocTy IsExternallyInitializedLoc;
741 if (ParseOptionalAddrSpace(AddrSpace) ||
742 ParseOptionalToken(lltok::kw_externally_initialized,
743 IsExternallyInitialized,
744 &IsExternallyInitializedLoc) ||
745 ParseGlobalType(IsConstant) ||
746 ParseType(Ty, TyLoc))
749 // If the linkage is specified and is external, then no initializer is
751 Constant *Init = nullptr;
752 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
753 Linkage != GlobalValue::ExternalLinkage)) {
754 if (ParseGlobalValue(Ty, Init))
758 if (Ty->isFunctionTy() || Ty->isLabelTy())
759 return Error(TyLoc, "invalid type for global variable");
761 GlobalValue *GVal = nullptr;
763 // See if the global was forward referenced, if so, use the global.
765 GVal = M->getNamedValue(Name);
767 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
768 return Error(NameLoc, "redefinition of global '@" + Name + "'");
771 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
772 I = ForwardRefValIDs.find(NumberedVals.size());
773 if (I != ForwardRefValIDs.end()) {
774 GVal = I->second.first;
775 ForwardRefValIDs.erase(I);
781 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
782 Name, nullptr, GlobalVariable::NotThreadLocal,
785 if (GVal->getType()->getElementType() != Ty)
787 "forward reference and definition of global have different types");
789 GV = cast<GlobalVariable>(GVal);
791 // Move the forward-reference to the correct spot in the module.
792 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
796 NumberedVals.push_back(GV);
798 // Set the parsed properties on the global.
800 GV->setInitializer(Init);
801 GV->setConstant(IsConstant);
802 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
803 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
804 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
805 GV->setExternallyInitialized(IsExternallyInitialized);
806 GV->setThreadLocalMode(TLM);
807 GV->setUnnamedAddr(UnnamedAddr);
809 // Parse attributes on the global.
810 while (Lex.getKind() == lltok::comma) {
813 if (Lex.getKind() == lltok::kw_section) {
815 GV->setSection(Lex.getStrVal());
816 if (ParseToken(lltok::StringConstant, "expected global section string"))
818 } else if (Lex.getKind() == lltok::kw_align) {
820 if (ParseOptionalAlignment(Alignment)) return true;
821 GV->setAlignment(Alignment);
824 if (parseOptionalComdat(Name, C))
829 return TokError("unknown global variable property!");
836 /// ParseUnnamedAttrGrp
837 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
838 bool LLParser::ParseUnnamedAttrGrp() {
839 assert(Lex.getKind() == lltok::kw_attributes);
840 LocTy AttrGrpLoc = Lex.getLoc();
843 if (Lex.getKind() != lltok::AttrGrpID)
844 return TokError("expected attribute group id");
846 unsigned VarID = Lex.getUIntVal();
847 std::vector<unsigned> unused;
851 if (ParseToken(lltok::equal, "expected '=' here") ||
852 ParseToken(lltok::lbrace, "expected '{' here") ||
853 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
855 ParseToken(lltok::rbrace, "expected end of attribute group"))
858 if (!NumberedAttrBuilders[VarID].hasAttributes())
859 return Error(AttrGrpLoc, "attribute group has no attributes");
864 /// ParseFnAttributeValuePairs
865 /// ::= <attr> | <attr> '=' <value>
866 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
867 std::vector<unsigned> &FwdRefAttrGrps,
868 bool inAttrGrp, LocTy &BuiltinLoc) {
869 bool HaveError = false;
874 lltok::Kind Token = Lex.getKind();
875 if (Token == lltok::kw_builtin)
876 BuiltinLoc = Lex.getLoc();
879 if (!inAttrGrp) return HaveError;
880 return Error(Lex.getLoc(), "unterminated attribute group");
885 case lltok::AttrGrpID: {
886 // Allow a function to reference an attribute group:
888 // define void @foo() #1 { ... }
892 "cannot have an attribute group reference in an attribute group");
894 unsigned AttrGrpNum = Lex.getUIntVal();
895 if (inAttrGrp) break;
897 // Save the reference to the attribute group. We'll fill it in later.
898 FwdRefAttrGrps.push_back(AttrGrpNum);
901 // Target-dependent attributes:
902 case lltok::StringConstant: {
903 std::string Attr = Lex.getStrVal();
906 if (EatIfPresent(lltok::equal) &&
907 ParseStringConstant(Val))
910 B.addAttribute(Attr, Val);
914 // Target-independent attributes:
915 case lltok::kw_align: {
916 // As a hack, we allow function alignment to be initially parsed as an
917 // attribute on a function declaration/definition or added to an attribute
918 // group and later moved to the alignment field.
922 if (ParseToken(lltok::equal, "expected '=' here") ||
923 ParseUInt32(Alignment))
926 if (ParseOptionalAlignment(Alignment))
929 B.addAlignmentAttr(Alignment);
932 case lltok::kw_alignstack: {
936 if (ParseToken(lltok::equal, "expected '=' here") ||
937 ParseUInt32(Alignment))
940 if (ParseOptionalStackAlignment(Alignment))
943 B.addStackAlignmentAttr(Alignment);
946 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
947 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
948 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
949 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
950 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
951 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
952 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
953 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
954 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
955 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
956 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
957 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
958 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
959 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
960 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
961 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
962 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
963 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
964 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
965 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
966 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
967 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
968 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
969 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
970 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
971 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
972 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
975 case lltok::kw_inreg:
976 case lltok::kw_signext:
977 case lltok::kw_zeroext:
980 "invalid use of attribute on a function");
982 case lltok::kw_byval:
983 case lltok::kw_dereferenceable:
984 case lltok::kw_inalloca:
986 case lltok::kw_noalias:
987 case lltok::kw_nocapture:
988 case lltok::kw_nonnull:
989 case lltok::kw_returned:
993 "invalid use of parameter-only attribute on a function");
1001 //===----------------------------------------------------------------------===//
1002 // GlobalValue Reference/Resolution Routines.
1003 //===----------------------------------------------------------------------===//
1005 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1006 /// forward reference record if needed. This can return null if the value
1007 /// exists but does not have the right type.
1008 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1010 PointerType *PTy = dyn_cast<PointerType>(Ty);
1012 Error(Loc, "global variable reference must have pointer type");
1016 // Look this name up in the normal function symbol table.
1018 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1020 // If this is a forward reference for the value, see if we already created a
1021 // forward ref record.
1023 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1024 I = ForwardRefVals.find(Name);
1025 if (I != ForwardRefVals.end())
1026 Val = I->second.first;
1029 // If we have the value in the symbol table or fwd-ref table, return it.
1031 if (Val->getType() == Ty) return Val;
1032 Error(Loc, "'@" + Name + "' defined with type '" +
1033 getTypeString(Val->getType()) + "'");
1037 // Otherwise, create a new forward reference for this value and remember it.
1038 GlobalValue *FwdVal;
1039 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1040 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1042 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1043 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1044 nullptr, GlobalVariable::NotThreadLocal,
1045 PTy->getAddressSpace());
1047 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1051 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1052 PointerType *PTy = dyn_cast<PointerType>(Ty);
1054 Error(Loc, "global variable reference must have pointer type");
1058 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1060 // If this is a forward reference for the value, see if we already created a
1061 // forward ref record.
1063 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1064 I = ForwardRefValIDs.find(ID);
1065 if (I != ForwardRefValIDs.end())
1066 Val = I->second.first;
1069 // If we have the value in the symbol table or fwd-ref table, return it.
1071 if (Val->getType() == Ty) return Val;
1072 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1073 getTypeString(Val->getType()) + "'");
1077 // Otherwise, create a new forward reference for this value and remember it.
1078 GlobalValue *FwdVal;
1079 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1080 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1082 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1083 GlobalValue::ExternalWeakLinkage, nullptr, "");
1085 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1090 //===----------------------------------------------------------------------===//
1091 // Comdat Reference/Resolution Routines.
1092 //===----------------------------------------------------------------------===//
1094 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1095 // Look this name up in the comdat symbol table.
1096 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1097 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1098 if (I != ComdatSymTab.end())
1101 // Otherwise, create a new forward reference for this value and remember it.
1102 Comdat *C = M->getOrInsertComdat(Name);
1103 ForwardRefComdats[Name] = Loc;
1108 //===----------------------------------------------------------------------===//
1110 //===----------------------------------------------------------------------===//
1112 /// ParseToken - If the current token has the specified kind, eat it and return
1113 /// success. Otherwise, emit the specified error and return failure.
1114 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1115 if (Lex.getKind() != T)
1116 return TokError(ErrMsg);
1121 /// ParseStringConstant
1122 /// ::= StringConstant
1123 bool LLParser::ParseStringConstant(std::string &Result) {
1124 if (Lex.getKind() != lltok::StringConstant)
1125 return TokError("expected string constant");
1126 Result = Lex.getStrVal();
1133 bool LLParser::ParseUInt32(unsigned &Val) {
1134 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1135 return TokError("expected integer");
1136 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1137 if (Val64 != unsigned(Val64))
1138 return TokError("expected 32-bit integer (too large)");
1146 bool LLParser::ParseUInt64(uint64_t &Val) {
1147 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1148 return TokError("expected integer");
1149 Val = Lex.getAPSIntVal().getLimitedValue();
1155 /// := 'localdynamic'
1156 /// := 'initialexec'
1158 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1159 switch (Lex.getKind()) {
1161 return TokError("expected localdynamic, initialexec or localexec");
1162 case lltok::kw_localdynamic:
1163 TLM = GlobalVariable::LocalDynamicTLSModel;
1165 case lltok::kw_initialexec:
1166 TLM = GlobalVariable::InitialExecTLSModel;
1168 case lltok::kw_localexec:
1169 TLM = GlobalVariable::LocalExecTLSModel;
1177 /// ParseOptionalThreadLocal
1179 /// := 'thread_local'
1180 /// := 'thread_local' '(' tlsmodel ')'
1181 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1182 TLM = GlobalVariable::NotThreadLocal;
1183 if (!EatIfPresent(lltok::kw_thread_local))
1186 TLM = GlobalVariable::GeneralDynamicTLSModel;
1187 if (Lex.getKind() == lltok::lparen) {
1189 return ParseTLSModel(TLM) ||
1190 ParseToken(lltok::rparen, "expected ')' after thread local model");
1195 /// ParseOptionalAddrSpace
1197 /// := 'addrspace' '(' uint32 ')'
1198 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1200 if (!EatIfPresent(lltok::kw_addrspace))
1202 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1203 ParseUInt32(AddrSpace) ||
1204 ParseToken(lltok::rparen, "expected ')' in address space");
1207 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1208 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1209 bool HaveError = false;
1214 lltok::Kind Token = Lex.getKind();
1216 default: // End of attributes.
1218 case lltok::kw_align: {
1220 if (ParseOptionalAlignment(Alignment))
1222 B.addAlignmentAttr(Alignment);
1225 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1226 case lltok::kw_dereferenceable: {
1228 if (ParseOptionalDereferenceableBytes(Bytes))
1230 B.addDereferenceableAttr(Bytes);
1233 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1234 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1235 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1236 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1237 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1238 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1239 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1240 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1241 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1242 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1243 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1244 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1246 case lltok::kw_alignstack:
1247 case lltok::kw_alwaysinline:
1248 case lltok::kw_builtin:
1249 case lltok::kw_inlinehint:
1250 case lltok::kw_jumptable:
1251 case lltok::kw_minsize:
1252 case lltok::kw_naked:
1253 case lltok::kw_nobuiltin:
1254 case lltok::kw_noduplicate:
1255 case lltok::kw_noimplicitfloat:
1256 case lltok::kw_noinline:
1257 case lltok::kw_nonlazybind:
1258 case lltok::kw_noredzone:
1259 case lltok::kw_noreturn:
1260 case lltok::kw_nounwind:
1261 case lltok::kw_optnone:
1262 case lltok::kw_optsize:
1263 case lltok::kw_returns_twice:
1264 case lltok::kw_sanitize_address:
1265 case lltok::kw_sanitize_memory:
1266 case lltok::kw_sanitize_thread:
1268 case lltok::kw_sspreq:
1269 case lltok::kw_sspstrong:
1270 case lltok::kw_uwtable:
1271 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1279 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1280 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1281 bool HaveError = false;
1286 lltok::Kind Token = Lex.getKind();
1288 default: // End of attributes.
1290 case lltok::kw_dereferenceable: {
1292 if (ParseOptionalDereferenceableBytes(Bytes))
1294 B.addDereferenceableAttr(Bytes);
1297 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1298 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1299 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1300 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1301 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1304 case lltok::kw_align:
1305 case lltok::kw_byval:
1306 case lltok::kw_inalloca:
1307 case lltok::kw_nest:
1308 case lltok::kw_nocapture:
1309 case lltok::kw_returned:
1310 case lltok::kw_sret:
1311 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1314 case lltok::kw_alignstack:
1315 case lltok::kw_alwaysinline:
1316 case lltok::kw_builtin:
1317 case lltok::kw_cold:
1318 case lltok::kw_inlinehint:
1319 case lltok::kw_jumptable:
1320 case lltok::kw_minsize:
1321 case lltok::kw_naked:
1322 case lltok::kw_nobuiltin:
1323 case lltok::kw_noduplicate:
1324 case lltok::kw_noimplicitfloat:
1325 case lltok::kw_noinline:
1326 case lltok::kw_nonlazybind:
1327 case lltok::kw_noredzone:
1328 case lltok::kw_noreturn:
1329 case lltok::kw_nounwind:
1330 case lltok::kw_optnone:
1331 case lltok::kw_optsize:
1332 case lltok::kw_returns_twice:
1333 case lltok::kw_sanitize_address:
1334 case lltok::kw_sanitize_memory:
1335 case lltok::kw_sanitize_thread:
1337 case lltok::kw_sspreq:
1338 case lltok::kw_sspstrong:
1339 case lltok::kw_uwtable:
1340 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1343 case lltok::kw_readnone:
1344 case lltok::kw_readonly:
1345 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1352 /// ParseOptionalLinkage
1359 /// ::= 'linkonce_odr'
1360 /// ::= 'available_externally'
1363 /// ::= 'extern_weak'
1365 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1367 switch (Lex.getKind()) {
1368 default: Res=GlobalValue::ExternalLinkage; return false;
1369 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1370 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1371 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1372 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1373 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1374 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1375 case lltok::kw_available_externally:
1376 Res = GlobalValue::AvailableExternallyLinkage;
1378 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1379 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1380 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1381 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1388 /// ParseOptionalVisibility
1394 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1395 switch (Lex.getKind()) {
1396 default: Res = GlobalValue::DefaultVisibility; return false;
1397 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1398 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1399 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1405 /// ParseOptionalDLLStorageClass
1410 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1411 switch (Lex.getKind()) {
1412 default: Res = GlobalValue::DefaultStorageClass; return false;
1413 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1414 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1420 /// ParseOptionalCallingConv
1424 /// ::= 'intel_ocl_bicc'
1426 /// ::= 'x86_stdcallcc'
1427 /// ::= 'x86_fastcallcc'
1428 /// ::= 'x86_thiscallcc'
1429 /// ::= 'x86_vectorcallcc'
1430 /// ::= 'arm_apcscc'
1431 /// ::= 'arm_aapcscc'
1432 /// ::= 'arm_aapcs_vfpcc'
1433 /// ::= 'msp430_intrcc'
1434 /// ::= 'ptx_kernel'
1435 /// ::= 'ptx_device'
1437 /// ::= 'spir_kernel'
1438 /// ::= 'x86_64_sysvcc'
1439 /// ::= 'x86_64_win64cc'
1440 /// ::= 'webkit_jscc'
1442 /// ::= 'preserve_mostcc'
1443 /// ::= 'preserve_allcc'
1447 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1448 switch (Lex.getKind()) {
1449 default: CC = CallingConv::C; return false;
1450 case lltok::kw_ccc: CC = CallingConv::C; break;
1451 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1452 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1453 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1454 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1455 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1456 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1457 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1458 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1459 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1460 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1461 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1462 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1463 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1464 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1465 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1466 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1467 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1468 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1469 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1470 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1471 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1472 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1473 case lltok::kw_cc: {
1475 return ParseUInt32(CC);
1483 /// ParseInstructionMetadata
1484 /// ::= !dbg !42 (',' !dbg !57)*
1485 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1486 PerFunctionState *PFS) {
1488 if (Lex.getKind() != lltok::MetadataVar)
1489 return TokError("expected metadata after comma");
1491 std::string Name = Lex.getStrVal();
1492 unsigned MDK = M->getMDKindID(Name);
1499 Inst->setMetadata(MDK, N);
1500 if (MDK == LLVMContext::MD_tbaa)
1501 InstsWithTBAATag.push_back(Inst);
1503 // If this is the end of the list, we're done.
1504 } while (EatIfPresent(lltok::comma));
1508 /// ParseOptionalAlignment
1511 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1513 if (!EatIfPresent(lltok::kw_align))
1515 LocTy AlignLoc = Lex.getLoc();
1516 if (ParseUInt32(Alignment)) return true;
1517 if (!isPowerOf2_32(Alignment))
1518 return Error(AlignLoc, "alignment is not a power of two");
1519 if (Alignment > Value::MaximumAlignment)
1520 return Error(AlignLoc, "huge alignments are not supported yet");
1524 /// ParseOptionalDereferenceableBytes
1526 /// ::= 'dereferenceable' '(' 4 ')'
1527 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1529 if (!EatIfPresent(lltok::kw_dereferenceable))
1531 LocTy ParenLoc = Lex.getLoc();
1532 if (!EatIfPresent(lltok::lparen))
1533 return Error(ParenLoc, "expected '('");
1534 LocTy DerefLoc = Lex.getLoc();
1535 if (ParseUInt64(Bytes)) return true;
1536 ParenLoc = Lex.getLoc();
1537 if (!EatIfPresent(lltok::rparen))
1538 return Error(ParenLoc, "expected ')'");
1540 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1544 /// ParseOptionalCommaAlign
1548 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1550 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1551 bool &AteExtraComma) {
1552 AteExtraComma = false;
1553 while (EatIfPresent(lltok::comma)) {
1554 // Metadata at the end is an early exit.
1555 if (Lex.getKind() == lltok::MetadataVar) {
1556 AteExtraComma = true;
1560 if (Lex.getKind() != lltok::kw_align)
1561 return Error(Lex.getLoc(), "expected metadata or 'align'");
1563 if (ParseOptionalAlignment(Alignment)) return true;
1569 /// ParseScopeAndOrdering
1570 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1573 /// This sets Scope and Ordering to the parsed values.
1574 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1575 AtomicOrdering &Ordering) {
1579 Scope = CrossThread;
1580 if (EatIfPresent(lltok::kw_singlethread))
1581 Scope = SingleThread;
1583 return ParseOrdering(Ordering);
1587 /// ::= AtomicOrdering
1589 /// This sets Ordering to the parsed value.
1590 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1591 switch (Lex.getKind()) {
1592 default: return TokError("Expected ordering on atomic instruction");
1593 case lltok::kw_unordered: Ordering = Unordered; break;
1594 case lltok::kw_monotonic: Ordering = Monotonic; break;
1595 case lltok::kw_acquire: Ordering = Acquire; break;
1596 case lltok::kw_release: Ordering = Release; break;
1597 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1598 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1604 /// ParseOptionalStackAlignment
1606 /// ::= 'alignstack' '(' 4 ')'
1607 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1609 if (!EatIfPresent(lltok::kw_alignstack))
1611 LocTy ParenLoc = Lex.getLoc();
1612 if (!EatIfPresent(lltok::lparen))
1613 return Error(ParenLoc, "expected '('");
1614 LocTy AlignLoc = Lex.getLoc();
1615 if (ParseUInt32(Alignment)) return true;
1616 ParenLoc = Lex.getLoc();
1617 if (!EatIfPresent(lltok::rparen))
1618 return Error(ParenLoc, "expected ')'");
1619 if (!isPowerOf2_32(Alignment))
1620 return Error(AlignLoc, "stack alignment is not a power of two");
1624 /// ParseIndexList - This parses the index list for an insert/extractvalue
1625 /// instruction. This sets AteExtraComma in the case where we eat an extra
1626 /// comma at the end of the line and find that it is followed by metadata.
1627 /// Clients that don't allow metadata can call the version of this function that
1628 /// only takes one argument.
1631 /// ::= (',' uint32)+
1633 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1634 bool &AteExtraComma) {
1635 AteExtraComma = false;
1637 if (Lex.getKind() != lltok::comma)
1638 return TokError("expected ',' as start of index list");
1640 while (EatIfPresent(lltok::comma)) {
1641 if (Lex.getKind() == lltok::MetadataVar) {
1642 AteExtraComma = true;
1646 if (ParseUInt32(Idx)) return true;
1647 Indices.push_back(Idx);
1653 //===----------------------------------------------------------------------===//
1655 //===----------------------------------------------------------------------===//
1657 /// ParseType - Parse a type.
1658 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1659 SMLoc TypeLoc = Lex.getLoc();
1660 switch (Lex.getKind()) {
1662 return TokError(Msg);
1664 // Type ::= 'float' | 'void' (etc)
1665 Result = Lex.getTyVal();
1669 // Type ::= StructType
1670 if (ParseAnonStructType(Result, false))
1673 case lltok::lsquare:
1674 // Type ::= '[' ... ']'
1675 Lex.Lex(); // eat the lsquare.
1676 if (ParseArrayVectorType(Result, false))
1679 case lltok::less: // Either vector or packed struct.
1680 // Type ::= '<' ... '>'
1682 if (Lex.getKind() == lltok::lbrace) {
1683 if (ParseAnonStructType(Result, true) ||
1684 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1686 } else if (ParseArrayVectorType(Result, true))
1689 case lltok::LocalVar: {
1691 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1693 // If the type hasn't been defined yet, create a forward definition and
1694 // remember where that forward def'n was seen (in case it never is defined).
1696 Entry.first = StructType::create(Context, Lex.getStrVal());
1697 Entry.second = Lex.getLoc();
1699 Result = Entry.first;
1704 case lltok::LocalVarID: {
1706 if (Lex.getUIntVal() >= NumberedTypes.size())
1707 NumberedTypes.resize(Lex.getUIntVal()+1);
1708 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1710 // If the type hasn't been defined yet, create a forward definition and
1711 // remember where that forward def'n was seen (in case it never is defined).
1713 Entry.first = StructType::create(Context);
1714 Entry.second = Lex.getLoc();
1716 Result = Entry.first;
1722 // Parse the type suffixes.
1724 switch (Lex.getKind()) {
1727 if (!AllowVoid && Result->isVoidTy())
1728 return Error(TypeLoc, "void type only allowed for function results");
1731 // Type ::= Type '*'
1733 if (Result->isLabelTy())
1734 return TokError("basic block pointers are invalid");
1735 if (Result->isVoidTy())
1736 return TokError("pointers to void are invalid - use i8* instead");
1737 if (!PointerType::isValidElementType(Result))
1738 return TokError("pointer to this type is invalid");
1739 Result = PointerType::getUnqual(Result);
1743 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1744 case lltok::kw_addrspace: {
1745 if (Result->isLabelTy())
1746 return TokError("basic block pointers are invalid");
1747 if (Result->isVoidTy())
1748 return TokError("pointers to void are invalid; use i8* instead");
1749 if (!PointerType::isValidElementType(Result))
1750 return TokError("pointer to this type is invalid");
1752 if (ParseOptionalAddrSpace(AddrSpace) ||
1753 ParseToken(lltok::star, "expected '*' in address space"))
1756 Result = PointerType::get(Result, AddrSpace);
1760 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1762 if (ParseFunctionType(Result))
1769 /// ParseParameterList
1771 /// ::= '(' Arg (',' Arg)* ')'
1773 /// ::= Type OptionalAttributes Value OptionalAttributes
1774 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1775 PerFunctionState &PFS, bool IsMustTailCall,
1776 bool InVarArgsFunc) {
1777 if (ParseToken(lltok::lparen, "expected '(' in call"))
1780 unsigned AttrIndex = 1;
1781 while (Lex.getKind() != lltok::rparen) {
1782 // If this isn't the first argument, we need a comma.
1783 if (!ArgList.empty() &&
1784 ParseToken(lltok::comma, "expected ',' in argument list"))
1787 // Parse an ellipsis if this is a musttail call in a variadic function.
1788 if (Lex.getKind() == lltok::dotdotdot) {
1789 const char *Msg = "unexpected ellipsis in argument list for ";
1790 if (!IsMustTailCall)
1791 return TokError(Twine(Msg) + "non-musttail call");
1793 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1794 Lex.Lex(); // Lex the '...', it is purely for readability.
1795 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1798 // Parse the argument.
1800 Type *ArgTy = nullptr;
1801 AttrBuilder ArgAttrs;
1803 if (ParseType(ArgTy, ArgLoc))
1806 if (ArgTy->isMetadataTy()) {
1807 if (ParseMetadataAsValue(V, PFS))
1810 // Otherwise, handle normal operands.
1811 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1814 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1819 if (IsMustTailCall && InVarArgsFunc)
1820 return TokError("expected '...' at end of argument list for musttail call "
1821 "in varargs function");
1823 Lex.Lex(); // Lex the ')'.
1829 /// ParseArgumentList - Parse the argument list for a function type or function
1831 /// ::= '(' ArgTypeListI ')'
1835 /// ::= ArgTypeList ',' '...'
1836 /// ::= ArgType (',' ArgType)*
1838 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1841 assert(Lex.getKind() == lltok::lparen);
1842 Lex.Lex(); // eat the (.
1844 if (Lex.getKind() == lltok::rparen) {
1846 } else if (Lex.getKind() == lltok::dotdotdot) {
1850 LocTy TypeLoc = Lex.getLoc();
1851 Type *ArgTy = nullptr;
1855 if (ParseType(ArgTy) ||
1856 ParseOptionalParamAttrs(Attrs)) return true;
1858 if (ArgTy->isVoidTy())
1859 return Error(TypeLoc, "argument can not have void type");
1861 if (Lex.getKind() == lltok::LocalVar) {
1862 Name = Lex.getStrVal();
1866 if (!FunctionType::isValidArgumentType(ArgTy))
1867 return Error(TypeLoc, "invalid type for function argument");
1869 unsigned AttrIndex = 1;
1870 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1871 AttributeSet::get(ArgTy->getContext(),
1872 AttrIndex++, Attrs), Name));
1874 while (EatIfPresent(lltok::comma)) {
1875 // Handle ... at end of arg list.
1876 if (EatIfPresent(lltok::dotdotdot)) {
1881 // Otherwise must be an argument type.
1882 TypeLoc = Lex.getLoc();
1883 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1885 if (ArgTy->isVoidTy())
1886 return Error(TypeLoc, "argument can not have void type");
1888 if (Lex.getKind() == lltok::LocalVar) {
1889 Name = Lex.getStrVal();
1895 if (!ArgTy->isFirstClassType())
1896 return Error(TypeLoc, "invalid type for function argument");
1898 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1899 AttributeSet::get(ArgTy->getContext(),
1900 AttrIndex++, Attrs),
1905 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1908 /// ParseFunctionType
1909 /// ::= Type ArgumentList OptionalAttrs
1910 bool LLParser::ParseFunctionType(Type *&Result) {
1911 assert(Lex.getKind() == lltok::lparen);
1913 if (!FunctionType::isValidReturnType(Result))
1914 return TokError("invalid function return type");
1916 SmallVector<ArgInfo, 8> ArgList;
1918 if (ParseArgumentList(ArgList, isVarArg))
1921 // Reject names on the arguments lists.
1922 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1923 if (!ArgList[i].Name.empty())
1924 return Error(ArgList[i].Loc, "argument name invalid in function type");
1925 if (ArgList[i].Attrs.hasAttributes(i + 1))
1926 return Error(ArgList[i].Loc,
1927 "argument attributes invalid in function type");
1930 SmallVector<Type*, 16> ArgListTy;
1931 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1932 ArgListTy.push_back(ArgList[i].Ty);
1934 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1938 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1940 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1941 SmallVector<Type*, 8> Elts;
1942 if (ParseStructBody(Elts)) return true;
1944 Result = StructType::get(Context, Elts, Packed);
1948 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1949 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1950 std::pair<Type*, LocTy> &Entry,
1952 // If the type was already defined, diagnose the redefinition.
1953 if (Entry.first && !Entry.second.isValid())
1954 return Error(TypeLoc, "redefinition of type");
1956 // If we have opaque, just return without filling in the definition for the
1957 // struct. This counts as a definition as far as the .ll file goes.
1958 if (EatIfPresent(lltok::kw_opaque)) {
1959 // This type is being defined, so clear the location to indicate this.
1960 Entry.second = SMLoc();
1962 // If this type number has never been uttered, create it.
1964 Entry.first = StructType::create(Context, Name);
1965 ResultTy = Entry.first;
1969 // If the type starts with '<', then it is either a packed struct or a vector.
1970 bool isPacked = EatIfPresent(lltok::less);
1972 // If we don't have a struct, then we have a random type alias, which we
1973 // accept for compatibility with old files. These types are not allowed to be
1974 // forward referenced and not allowed to be recursive.
1975 if (Lex.getKind() != lltok::lbrace) {
1977 return Error(TypeLoc, "forward references to non-struct type");
1981 return ParseArrayVectorType(ResultTy, true);
1982 return ParseType(ResultTy);
1985 // This type is being defined, so clear the location to indicate this.
1986 Entry.second = SMLoc();
1988 // If this type number has never been uttered, create it.
1990 Entry.first = StructType::create(Context, Name);
1992 StructType *STy = cast<StructType>(Entry.first);
1994 SmallVector<Type*, 8> Body;
1995 if (ParseStructBody(Body) ||
1996 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1999 STy->setBody(Body, isPacked);
2005 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2008 /// ::= '{' Type (',' Type)* '}'
2009 /// ::= '<' '{' '}' '>'
2010 /// ::= '<' '{' Type (',' Type)* '}' '>'
2011 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2012 assert(Lex.getKind() == lltok::lbrace);
2013 Lex.Lex(); // Consume the '{'
2015 // Handle the empty struct.
2016 if (EatIfPresent(lltok::rbrace))
2019 LocTy EltTyLoc = Lex.getLoc();
2021 if (ParseType(Ty)) return true;
2024 if (!StructType::isValidElementType(Ty))
2025 return Error(EltTyLoc, "invalid element type for struct");
2027 while (EatIfPresent(lltok::comma)) {
2028 EltTyLoc = Lex.getLoc();
2029 if (ParseType(Ty)) return true;
2031 if (!StructType::isValidElementType(Ty))
2032 return Error(EltTyLoc, "invalid element type for struct");
2037 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2040 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2041 /// token has already been consumed.
2043 /// ::= '[' APSINTVAL 'x' Types ']'
2044 /// ::= '<' APSINTVAL 'x' Types '>'
2045 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2046 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2047 Lex.getAPSIntVal().getBitWidth() > 64)
2048 return TokError("expected number in address space");
2050 LocTy SizeLoc = Lex.getLoc();
2051 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2054 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2057 LocTy TypeLoc = Lex.getLoc();
2058 Type *EltTy = nullptr;
2059 if (ParseType(EltTy)) return true;
2061 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2062 "expected end of sequential type"))
2067 return Error(SizeLoc, "zero element vector is illegal");
2068 if ((unsigned)Size != Size)
2069 return Error(SizeLoc, "size too large for vector");
2070 if (!VectorType::isValidElementType(EltTy))
2071 return Error(TypeLoc, "invalid vector element type");
2072 Result = VectorType::get(EltTy, unsigned(Size));
2074 if (!ArrayType::isValidElementType(EltTy))
2075 return Error(TypeLoc, "invalid array element type");
2076 Result = ArrayType::get(EltTy, Size);
2081 //===----------------------------------------------------------------------===//
2082 // Function Semantic Analysis.
2083 //===----------------------------------------------------------------------===//
2085 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2087 : P(p), F(f), FunctionNumber(functionNumber) {
2089 // Insert unnamed arguments into the NumberedVals list.
2090 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2093 NumberedVals.push_back(AI);
2096 LLParser::PerFunctionState::~PerFunctionState() {
2097 // If there were any forward referenced non-basicblock values, delete them.
2098 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2099 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2100 if (!isa<BasicBlock>(I->second.first)) {
2101 I->second.first->replaceAllUsesWith(
2102 UndefValue::get(I->second.first->getType()));
2103 delete I->second.first;
2104 I->second.first = nullptr;
2107 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2108 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2109 if (!isa<BasicBlock>(I->second.first)) {
2110 I->second.first->replaceAllUsesWith(
2111 UndefValue::get(I->second.first->getType()));
2112 delete I->second.first;
2113 I->second.first = nullptr;
2117 bool LLParser::PerFunctionState::FinishFunction() {
2118 if (!ForwardRefVals.empty())
2119 return P.Error(ForwardRefVals.begin()->second.second,
2120 "use of undefined value '%" + ForwardRefVals.begin()->first +
2122 if (!ForwardRefValIDs.empty())
2123 return P.Error(ForwardRefValIDs.begin()->second.second,
2124 "use of undefined value '%" +
2125 Twine(ForwardRefValIDs.begin()->first) + "'");
2130 /// GetVal - Get a value with the specified name or ID, creating a
2131 /// forward reference record if needed. This can return null if the value
2132 /// exists but does not have the right type.
2133 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2134 Type *Ty, LocTy Loc) {
2135 // Look this name up in the normal function symbol table.
2136 Value *Val = F.getValueSymbolTable().lookup(Name);
2138 // If this is a forward reference for the value, see if we already created a
2139 // forward ref record.
2141 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2142 I = ForwardRefVals.find(Name);
2143 if (I != ForwardRefVals.end())
2144 Val = I->second.first;
2147 // If we have the value in the symbol table or fwd-ref table, return it.
2149 if (Val->getType() == Ty) return Val;
2150 if (Ty->isLabelTy())
2151 P.Error(Loc, "'%" + Name + "' is not a basic block");
2153 P.Error(Loc, "'%" + Name + "' defined with type '" +
2154 getTypeString(Val->getType()) + "'");
2158 // Don't make placeholders with invalid type.
2159 if (!Ty->isFirstClassType()) {
2160 P.Error(Loc, "invalid use of a non-first-class type");
2164 // Otherwise, create a new forward reference for this value and remember it.
2166 if (Ty->isLabelTy())
2167 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2169 FwdVal = new Argument(Ty, Name);
2171 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2175 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2177 // Look this name up in the normal function symbol table.
2178 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2180 // If this is a forward reference for the value, see if we already created a
2181 // forward ref record.
2183 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2184 I = ForwardRefValIDs.find(ID);
2185 if (I != ForwardRefValIDs.end())
2186 Val = I->second.first;
2189 // If we have the value in the symbol table or fwd-ref table, return it.
2191 if (Val->getType() == Ty) return Val;
2192 if (Ty->isLabelTy())
2193 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2195 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2196 getTypeString(Val->getType()) + "'");
2200 if (!Ty->isFirstClassType()) {
2201 P.Error(Loc, "invalid use of a non-first-class type");
2205 // Otherwise, create a new forward reference for this value and remember it.
2207 if (Ty->isLabelTy())
2208 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2210 FwdVal = new Argument(Ty);
2212 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2216 /// SetInstName - After an instruction is parsed and inserted into its
2217 /// basic block, this installs its name.
2218 bool LLParser::PerFunctionState::SetInstName(int NameID,
2219 const std::string &NameStr,
2220 LocTy NameLoc, Instruction *Inst) {
2221 // If this instruction has void type, it cannot have a name or ID specified.
2222 if (Inst->getType()->isVoidTy()) {
2223 if (NameID != -1 || !NameStr.empty())
2224 return P.Error(NameLoc, "instructions returning void cannot have a name");
2228 // If this was a numbered instruction, verify that the instruction is the
2229 // expected value and resolve any forward references.
2230 if (NameStr.empty()) {
2231 // If neither a name nor an ID was specified, just use the next ID.
2233 NameID = NumberedVals.size();
2235 if (unsigned(NameID) != NumberedVals.size())
2236 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2237 Twine(NumberedVals.size()) + "'");
2239 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2240 ForwardRefValIDs.find(NameID);
2241 if (FI != ForwardRefValIDs.end()) {
2242 if (FI->second.first->getType() != Inst->getType())
2243 return P.Error(NameLoc, "instruction forward referenced with type '" +
2244 getTypeString(FI->second.first->getType()) + "'");
2245 FI->second.first->replaceAllUsesWith(Inst);
2246 delete FI->second.first;
2247 ForwardRefValIDs.erase(FI);
2250 NumberedVals.push_back(Inst);
2254 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2255 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2256 FI = ForwardRefVals.find(NameStr);
2257 if (FI != ForwardRefVals.end()) {
2258 if (FI->second.first->getType() != Inst->getType())
2259 return P.Error(NameLoc, "instruction forward referenced with type '" +
2260 getTypeString(FI->second.first->getType()) + "'");
2261 FI->second.first->replaceAllUsesWith(Inst);
2262 delete FI->second.first;
2263 ForwardRefVals.erase(FI);
2266 // Set the name on the instruction.
2267 Inst->setName(NameStr);
2269 if (Inst->getName() != NameStr)
2270 return P.Error(NameLoc, "multiple definition of local value named '" +
2275 /// GetBB - Get a basic block with the specified name or ID, creating a
2276 /// forward reference record if needed.
2277 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2279 return cast_or_null<BasicBlock>(GetVal(Name,
2280 Type::getLabelTy(F.getContext()), Loc));
2283 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2284 return cast_or_null<BasicBlock>(GetVal(ID,
2285 Type::getLabelTy(F.getContext()), Loc));
2288 /// DefineBB - Define the specified basic block, which is either named or
2289 /// unnamed. If there is an error, this returns null otherwise it returns
2290 /// the block being defined.
2291 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2295 BB = GetBB(NumberedVals.size(), Loc);
2297 BB = GetBB(Name, Loc);
2298 if (!BB) return nullptr; // Already diagnosed error.
2300 // Move the block to the end of the function. Forward ref'd blocks are
2301 // inserted wherever they happen to be referenced.
2302 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2304 // Remove the block from forward ref sets.
2306 ForwardRefValIDs.erase(NumberedVals.size());
2307 NumberedVals.push_back(BB);
2309 // BB forward references are already in the function symbol table.
2310 ForwardRefVals.erase(Name);
2316 //===----------------------------------------------------------------------===//
2318 //===----------------------------------------------------------------------===//
2320 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2321 /// type implied. For example, if we parse "4" we don't know what integer type
2322 /// it has. The value will later be combined with its type and checked for
2323 /// sanity. PFS is used to convert function-local operands of metadata (since
2324 /// metadata operands are not just parsed here but also converted to values).
2325 /// PFS can be null when we are not parsing metadata values inside a function.
2326 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2327 ID.Loc = Lex.getLoc();
2328 switch (Lex.getKind()) {
2329 default: return TokError("expected value token");
2330 case lltok::GlobalID: // @42
2331 ID.UIntVal = Lex.getUIntVal();
2332 ID.Kind = ValID::t_GlobalID;
2334 case lltok::GlobalVar: // @foo
2335 ID.StrVal = Lex.getStrVal();
2336 ID.Kind = ValID::t_GlobalName;
2338 case lltok::LocalVarID: // %42
2339 ID.UIntVal = Lex.getUIntVal();
2340 ID.Kind = ValID::t_LocalID;
2342 case lltok::LocalVar: // %foo
2343 ID.StrVal = Lex.getStrVal();
2344 ID.Kind = ValID::t_LocalName;
2347 ID.APSIntVal = Lex.getAPSIntVal();
2348 ID.Kind = ValID::t_APSInt;
2350 case lltok::APFloat:
2351 ID.APFloatVal = Lex.getAPFloatVal();
2352 ID.Kind = ValID::t_APFloat;
2354 case lltok::kw_true:
2355 ID.ConstantVal = ConstantInt::getTrue(Context);
2356 ID.Kind = ValID::t_Constant;
2358 case lltok::kw_false:
2359 ID.ConstantVal = ConstantInt::getFalse(Context);
2360 ID.Kind = ValID::t_Constant;
2362 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2363 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2364 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2366 case lltok::lbrace: {
2367 // ValID ::= '{' ConstVector '}'
2369 SmallVector<Constant*, 16> Elts;
2370 if (ParseGlobalValueVector(Elts) ||
2371 ParseToken(lltok::rbrace, "expected end of struct constant"))
2374 ID.ConstantStructElts = new Constant*[Elts.size()];
2375 ID.UIntVal = Elts.size();
2376 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2377 ID.Kind = ValID::t_ConstantStruct;
2381 // ValID ::= '<' ConstVector '>' --> Vector.
2382 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2384 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2386 SmallVector<Constant*, 16> Elts;
2387 LocTy FirstEltLoc = Lex.getLoc();
2388 if (ParseGlobalValueVector(Elts) ||
2390 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2391 ParseToken(lltok::greater, "expected end of constant"))
2394 if (isPackedStruct) {
2395 ID.ConstantStructElts = new Constant*[Elts.size()];
2396 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2397 ID.UIntVal = Elts.size();
2398 ID.Kind = ValID::t_PackedConstantStruct;
2403 return Error(ID.Loc, "constant vector must not be empty");
2405 if (!Elts[0]->getType()->isIntegerTy() &&
2406 !Elts[0]->getType()->isFloatingPointTy() &&
2407 !Elts[0]->getType()->isPointerTy())
2408 return Error(FirstEltLoc,
2409 "vector elements must have integer, pointer or floating point type");
2411 // Verify that all the vector elements have the same type.
2412 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2413 if (Elts[i]->getType() != Elts[0]->getType())
2414 return Error(FirstEltLoc,
2415 "vector element #" + Twine(i) +
2416 " is not of type '" + getTypeString(Elts[0]->getType()));
2418 ID.ConstantVal = ConstantVector::get(Elts);
2419 ID.Kind = ValID::t_Constant;
2422 case lltok::lsquare: { // Array Constant
2424 SmallVector<Constant*, 16> Elts;
2425 LocTy FirstEltLoc = Lex.getLoc();
2426 if (ParseGlobalValueVector(Elts) ||
2427 ParseToken(lltok::rsquare, "expected end of array constant"))
2430 // Handle empty element.
2432 // Use undef instead of an array because it's inconvenient to determine
2433 // the element type at this point, there being no elements to examine.
2434 ID.Kind = ValID::t_EmptyArray;
2438 if (!Elts[0]->getType()->isFirstClassType())
2439 return Error(FirstEltLoc, "invalid array element type: " +
2440 getTypeString(Elts[0]->getType()));
2442 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2444 // Verify all elements are correct type!
2445 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2446 if (Elts[i]->getType() != Elts[0]->getType())
2447 return Error(FirstEltLoc,
2448 "array element #" + Twine(i) +
2449 " is not of type '" + getTypeString(Elts[0]->getType()));
2452 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2453 ID.Kind = ValID::t_Constant;
2456 case lltok::kw_c: // c "foo"
2458 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2460 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2461 ID.Kind = ValID::t_Constant;
2464 case lltok::kw_asm: {
2465 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2467 bool HasSideEffect, AlignStack, AsmDialect;
2469 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2470 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2471 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2472 ParseStringConstant(ID.StrVal) ||
2473 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2474 ParseToken(lltok::StringConstant, "expected constraint string"))
2476 ID.StrVal2 = Lex.getStrVal();
2477 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2478 (unsigned(AsmDialect)<<2);
2479 ID.Kind = ValID::t_InlineAsm;
2483 case lltok::kw_blockaddress: {
2484 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2489 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2491 ParseToken(lltok::comma, "expected comma in block address expression")||
2492 ParseValID(Label) ||
2493 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2496 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2497 return Error(Fn.Loc, "expected function name in blockaddress");
2498 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2499 return Error(Label.Loc, "expected basic block name in blockaddress");
2501 // Try to find the function (but skip it if it's forward-referenced).
2502 GlobalValue *GV = nullptr;
2503 if (Fn.Kind == ValID::t_GlobalID) {
2504 if (Fn.UIntVal < NumberedVals.size())
2505 GV = NumberedVals[Fn.UIntVal];
2506 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2507 GV = M->getNamedValue(Fn.StrVal);
2509 Function *F = nullptr;
2511 // Confirm that it's actually a function with a definition.
2512 if (!isa<Function>(GV))
2513 return Error(Fn.Loc, "expected function name in blockaddress");
2514 F = cast<Function>(GV);
2515 if (F->isDeclaration())
2516 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2520 // Make a global variable as a placeholder for this reference.
2521 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2523 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2524 GlobalValue::InternalLinkage, nullptr, "");
2525 ID.ConstantVal = FwdRef;
2526 ID.Kind = ValID::t_Constant;
2530 // We found the function; now find the basic block. Don't use PFS, since we
2531 // might be inside a constant expression.
2533 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2534 if (Label.Kind == ValID::t_LocalID)
2535 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2537 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2539 return Error(Label.Loc, "referenced value is not a basic block");
2541 if (Label.Kind == ValID::t_LocalID)
2542 return Error(Label.Loc, "cannot take address of numeric label after "
2543 "the function is defined");
2544 BB = dyn_cast_or_null<BasicBlock>(
2545 F->getValueSymbolTable().lookup(Label.StrVal));
2547 return Error(Label.Loc, "referenced value is not a basic block");
2550 ID.ConstantVal = BlockAddress::get(F, BB);
2551 ID.Kind = ValID::t_Constant;
2555 case lltok::kw_trunc:
2556 case lltok::kw_zext:
2557 case lltok::kw_sext:
2558 case lltok::kw_fptrunc:
2559 case lltok::kw_fpext:
2560 case lltok::kw_bitcast:
2561 case lltok::kw_addrspacecast:
2562 case lltok::kw_uitofp:
2563 case lltok::kw_sitofp:
2564 case lltok::kw_fptoui:
2565 case lltok::kw_fptosi:
2566 case lltok::kw_inttoptr:
2567 case lltok::kw_ptrtoint: {
2568 unsigned Opc = Lex.getUIntVal();
2569 Type *DestTy = nullptr;
2572 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2573 ParseGlobalTypeAndValue(SrcVal) ||
2574 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2575 ParseType(DestTy) ||
2576 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2578 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2579 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2580 getTypeString(SrcVal->getType()) + "' to '" +
2581 getTypeString(DestTy) + "'");
2582 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2584 ID.Kind = ValID::t_Constant;
2587 case lltok::kw_extractvalue: {
2590 SmallVector<unsigned, 4> Indices;
2591 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2592 ParseGlobalTypeAndValue(Val) ||
2593 ParseIndexList(Indices) ||
2594 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2597 if (!Val->getType()->isAggregateType())
2598 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2599 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2600 return Error(ID.Loc, "invalid indices for extractvalue");
2601 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2602 ID.Kind = ValID::t_Constant;
2605 case lltok::kw_insertvalue: {
2607 Constant *Val0, *Val1;
2608 SmallVector<unsigned, 4> Indices;
2609 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2610 ParseGlobalTypeAndValue(Val0) ||
2611 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2612 ParseGlobalTypeAndValue(Val1) ||
2613 ParseIndexList(Indices) ||
2614 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2616 if (!Val0->getType()->isAggregateType())
2617 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2618 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2619 return Error(ID.Loc, "invalid indices for insertvalue");
2620 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2621 ID.Kind = ValID::t_Constant;
2624 case lltok::kw_icmp:
2625 case lltok::kw_fcmp: {
2626 unsigned PredVal, Opc = Lex.getUIntVal();
2627 Constant *Val0, *Val1;
2629 if (ParseCmpPredicate(PredVal, Opc) ||
2630 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2631 ParseGlobalTypeAndValue(Val0) ||
2632 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2633 ParseGlobalTypeAndValue(Val1) ||
2634 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2637 if (Val0->getType() != Val1->getType())
2638 return Error(ID.Loc, "compare operands must have the same type");
2640 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2642 if (Opc == Instruction::FCmp) {
2643 if (!Val0->getType()->isFPOrFPVectorTy())
2644 return Error(ID.Loc, "fcmp requires floating point operands");
2645 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2647 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2648 if (!Val0->getType()->isIntOrIntVectorTy() &&
2649 !Val0->getType()->getScalarType()->isPointerTy())
2650 return Error(ID.Loc, "icmp requires pointer or integer operands");
2651 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2653 ID.Kind = ValID::t_Constant;
2657 // Binary Operators.
2659 case lltok::kw_fadd:
2661 case lltok::kw_fsub:
2663 case lltok::kw_fmul:
2664 case lltok::kw_udiv:
2665 case lltok::kw_sdiv:
2666 case lltok::kw_fdiv:
2667 case lltok::kw_urem:
2668 case lltok::kw_srem:
2669 case lltok::kw_frem:
2671 case lltok::kw_lshr:
2672 case lltok::kw_ashr: {
2676 unsigned Opc = Lex.getUIntVal();
2677 Constant *Val0, *Val1;
2679 LocTy ModifierLoc = Lex.getLoc();
2680 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2681 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2682 if (EatIfPresent(lltok::kw_nuw))
2684 if (EatIfPresent(lltok::kw_nsw)) {
2686 if (EatIfPresent(lltok::kw_nuw))
2689 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2690 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2691 if (EatIfPresent(lltok::kw_exact))
2694 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2695 ParseGlobalTypeAndValue(Val0) ||
2696 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2697 ParseGlobalTypeAndValue(Val1) ||
2698 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2700 if (Val0->getType() != Val1->getType())
2701 return Error(ID.Loc, "operands of constexpr must have same type");
2702 if (!Val0->getType()->isIntOrIntVectorTy()) {
2704 return Error(ModifierLoc, "nuw only applies to integer operations");
2706 return Error(ModifierLoc, "nsw only applies to integer operations");
2708 // Check that the type is valid for the operator.
2710 case Instruction::Add:
2711 case Instruction::Sub:
2712 case Instruction::Mul:
2713 case Instruction::UDiv:
2714 case Instruction::SDiv:
2715 case Instruction::URem:
2716 case Instruction::SRem:
2717 case Instruction::Shl:
2718 case Instruction::AShr:
2719 case Instruction::LShr:
2720 if (!Val0->getType()->isIntOrIntVectorTy())
2721 return Error(ID.Loc, "constexpr requires integer operands");
2723 case Instruction::FAdd:
2724 case Instruction::FSub:
2725 case Instruction::FMul:
2726 case Instruction::FDiv:
2727 case Instruction::FRem:
2728 if (!Val0->getType()->isFPOrFPVectorTy())
2729 return Error(ID.Loc, "constexpr requires fp operands");
2731 default: llvm_unreachable("Unknown binary operator!");
2734 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2735 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2736 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2737 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2739 ID.Kind = ValID::t_Constant;
2743 // Logical Operations
2746 case lltok::kw_xor: {
2747 unsigned Opc = Lex.getUIntVal();
2748 Constant *Val0, *Val1;
2750 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2751 ParseGlobalTypeAndValue(Val0) ||
2752 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2753 ParseGlobalTypeAndValue(Val1) ||
2754 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2756 if (Val0->getType() != Val1->getType())
2757 return Error(ID.Loc, "operands of constexpr must have same type");
2758 if (!Val0->getType()->isIntOrIntVectorTy())
2759 return Error(ID.Loc,
2760 "constexpr requires integer or integer vector operands");
2761 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2762 ID.Kind = ValID::t_Constant;
2766 case lltok::kw_getelementptr:
2767 case lltok::kw_shufflevector:
2768 case lltok::kw_insertelement:
2769 case lltok::kw_extractelement:
2770 case lltok::kw_select: {
2771 unsigned Opc = Lex.getUIntVal();
2772 SmallVector<Constant*, 16> Elts;
2773 bool InBounds = false;
2775 if (Opc == Instruction::GetElementPtr)
2776 InBounds = EatIfPresent(lltok::kw_inbounds);
2777 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2778 ParseGlobalValueVector(Elts) ||
2779 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2782 if (Opc == Instruction::GetElementPtr) {
2783 if (Elts.size() == 0 ||
2784 !Elts[0]->getType()->getScalarType()->isPointerTy())
2785 return Error(ID.Loc, "getelementptr requires pointer operand");
2787 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2788 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2789 return Error(ID.Loc, "invalid indices for getelementptr");
2790 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2792 } else if (Opc == Instruction::Select) {
2793 if (Elts.size() != 3)
2794 return Error(ID.Loc, "expected three operands to select");
2795 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2797 return Error(ID.Loc, Reason);
2798 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2799 } else if (Opc == Instruction::ShuffleVector) {
2800 if (Elts.size() != 3)
2801 return Error(ID.Loc, "expected three operands to shufflevector");
2802 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2803 return Error(ID.Loc, "invalid operands to shufflevector");
2805 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2806 } else if (Opc == Instruction::ExtractElement) {
2807 if (Elts.size() != 2)
2808 return Error(ID.Loc, "expected two operands to extractelement");
2809 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2810 return Error(ID.Loc, "invalid extractelement operands");
2811 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2813 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2814 if (Elts.size() != 3)
2815 return Error(ID.Loc, "expected three operands to insertelement");
2816 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2817 return Error(ID.Loc, "invalid insertelement operands");
2819 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2822 ID.Kind = ValID::t_Constant;
2831 /// ParseGlobalValue - Parse a global value with the specified type.
2832 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2836 bool Parsed = ParseValID(ID) ||
2837 ConvertValIDToValue(Ty, ID, V, nullptr);
2838 if (V && !(C = dyn_cast<Constant>(V)))
2839 return Error(ID.Loc, "global values must be constants");
2843 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2845 return ParseType(Ty) ||
2846 ParseGlobalValue(Ty, V);
2849 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2852 LocTy KwLoc = Lex.getLoc();
2853 if (!EatIfPresent(lltok::kw_comdat))
2856 if (EatIfPresent(lltok::lparen)) {
2857 if (Lex.getKind() != lltok::ComdatVar)
2858 return TokError("expected comdat variable");
2859 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2861 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2864 if (GlobalName.empty())
2865 return TokError("comdat cannot be unnamed");
2866 C = getComdat(GlobalName, KwLoc);
2872 /// ParseGlobalValueVector
2874 /// ::= TypeAndValue (',' TypeAndValue)*
2875 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2877 if (Lex.getKind() == lltok::rbrace ||
2878 Lex.getKind() == lltok::rsquare ||
2879 Lex.getKind() == lltok::greater ||
2880 Lex.getKind() == lltok::rparen)
2884 if (ParseGlobalTypeAndValue(C)) return true;
2887 while (EatIfPresent(lltok::comma)) {
2888 if (ParseGlobalTypeAndValue(C)) return true;
2895 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2896 SmallVector<Metadata *, 16> Elts;
2897 if (ParseMDNodeVector(Elts))
2900 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2907 /// ::= !MDLocation(...)
2908 bool LLParser::ParseMDNode(MDNode *&N) {
2909 if (Lex.getKind() == lltok::MetadataVar)
2910 return ParseSpecializedMDNode(N);
2912 return ParseToken(lltok::exclaim, "expected '!' here") ||
2916 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2918 if (Lex.getKind() == lltok::lbrace)
2919 return ParseMDTuple(N);
2922 return ParseMDNodeID(N);
2925 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
2926 MDUnsignedField<uint32_t> &Result) {
2927 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2928 return TokError("expected unsigned integer");
2929 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(Result.Max + 1ull);
2931 if (Val64 > Result.Max)
2932 return TokError("value for '" + Name + "' too large, limit is " +
2934 Result.assign(Val64);
2939 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
2941 if (ParseMetadata(MD, nullptr))
2948 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
2950 if (ParseStringConstant(S))
2953 Result.assign(std::move(S));
2957 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
2958 SmallVector<Metadata *, 4> MDs;
2959 if (ParseMDNodeVector(MDs))
2962 Result.assign(std::move(MDs));
2966 template <class ParserTy>
2967 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
2969 if (Lex.getKind() != lltok::LabelStr)
2970 return TokError("expected field label here");
2974 } while (EatIfPresent(lltok::comma));
2979 template <class ParserTy>
2980 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
2981 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
2984 if (ParseToken(lltok::lparen, "expected '(' here"))
2986 if (Lex.getKind() != lltok::rparen)
2987 if (ParseMDFieldsImplBody(parseField))
2990 ClosingLoc = Lex.getLoc();
2991 return ParseToken(lltok::rparen, "expected ')' here");
2994 template <class FieldTy>
2995 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
2997 return TokError("field '" + Name + "' cannot be specified more than once");
2999 LocTy Loc = Lex.getLoc();
3001 return ParseMDField(Loc, Name, Result);
3004 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3005 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3006 #define DISPATCH_TO_PARSER(CLASS) \
3007 if (Lex.getStrVal() == #CLASS) \
3008 return Parse##CLASS(N, IsDistinct);
3010 DISPATCH_TO_PARSER(MDLocation);
3011 DISPATCH_TO_PARSER(GenericDebugNode);
3012 #undef DISPATCH_TO_PARSER
3014 return TokError("expected metadata type");
3017 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3018 #define NOP_FIELD(NAME, TYPE, INIT)
3019 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3021 return Error(ClosingLoc, "missing required field '" #NAME "'");
3022 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3023 if (Lex.getStrVal() == #NAME) \
3024 return ParseMDField(#NAME, NAME);
3025 #define PARSE_MD_FIELDS() \
3026 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3029 if (ParseMDFieldsImpl([&]() -> bool { \
3030 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3031 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3034 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3036 #define GET_OR_DISTINCT(CLASS, ARGS) \
3037 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3039 /// ParseMDLocationFields:
3040 /// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3041 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3042 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3043 OPTIONAL(line, MDUnsignedField<uint32_t>, (0, ~0u >> 8)); \
3044 OPTIONAL(column, MDUnsignedField<uint32_t>, (0, ~0u >> 16)); \
3045 REQUIRED(scope, MDField, ); \
3046 OPTIONAL(inlinedAt, MDField, );
3048 #undef VISIT_MD_FIELDS
3050 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3051 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3055 /// ParseGenericDebugNode:
3056 /// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3057 bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3058 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3059 REQUIRED(tag, MDUnsignedField<uint32_t>, (0, ~0u >> 16)); \
3060 OPTIONAL(header, MDStringField, ); \
3061 OPTIONAL(operands, MDFieldList, );
3063 #undef VISIT_MD_FIELDS
3065 Result = GET_OR_DISTINCT(GenericDebugNode,
3066 (Context, tag.Val, header.Val, operands.Val));
3069 #undef PARSE_MD_FIELD
3071 #undef REQUIRE_FIELD
3072 #undef DECLARE_FIELD
3074 /// ParseMetadataAsValue
3075 /// ::= metadata i32 %local
3076 /// ::= metadata i32 @global
3077 /// ::= metadata i32 7
3079 /// ::= metadata !{...}
3080 /// ::= metadata !"string"
3081 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3082 // Note: the type 'metadata' has already been parsed.
3084 if (ParseMetadata(MD, &PFS))
3087 V = MetadataAsValue::get(Context, MD);
3091 /// ParseValueAsMetadata
3095 bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
3098 if (ParseType(Ty, "expected metadata operand", Loc))
3100 if (Ty->isMetadataTy())
3101 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3104 if (ParseValue(Ty, V, PFS))
3107 MD = ValueAsMetadata::get(V);
3118 /// ::= !MDLocation(...)
3119 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3120 if (Lex.getKind() == lltok::MetadataVar) {
3122 if (ParseSpecializedMDNode(N))
3130 if (Lex.getKind() != lltok::exclaim)
3131 return ParseValueAsMetadata(MD, PFS);
3134 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3138 // ::= '!' STRINGCONSTANT
3139 if (Lex.getKind() == lltok::StringConstant) {
3141 if (ParseMDString(S))
3151 if (ParseMDNodeTail(N))
3158 //===----------------------------------------------------------------------===//
3159 // Function Parsing.
3160 //===----------------------------------------------------------------------===//
3162 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3163 PerFunctionState *PFS) {
3164 if (Ty->isFunctionTy())
3165 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3168 case ValID::t_LocalID:
3169 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3170 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3171 return V == nullptr;
3172 case ValID::t_LocalName:
3173 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3174 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3175 return V == nullptr;
3176 case ValID::t_InlineAsm: {
3177 PointerType *PTy = dyn_cast<PointerType>(Ty);
3179 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3180 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3181 return Error(ID.Loc, "invalid type for inline asm constraint string");
3182 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3183 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3186 case ValID::t_GlobalName:
3187 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3188 return V == nullptr;
3189 case ValID::t_GlobalID:
3190 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3191 return V == nullptr;
3192 case ValID::t_APSInt:
3193 if (!Ty->isIntegerTy())
3194 return Error(ID.Loc, "integer constant must have integer type");
3195 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3196 V = ConstantInt::get(Context, ID.APSIntVal);
3198 case ValID::t_APFloat:
3199 if (!Ty->isFloatingPointTy() ||
3200 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3201 return Error(ID.Loc, "floating point constant invalid for type");
3203 // The lexer has no type info, so builds all half, float, and double FP
3204 // constants as double. Fix this here. Long double does not need this.
3205 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3208 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3210 else if (Ty->isFloatTy())
3211 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3214 V = ConstantFP::get(Context, ID.APFloatVal);
3216 if (V->getType() != Ty)
3217 return Error(ID.Loc, "floating point constant does not have type '" +
3218 getTypeString(Ty) + "'");
3222 if (!Ty->isPointerTy())
3223 return Error(ID.Loc, "null must be a pointer type");
3224 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3226 case ValID::t_Undef:
3227 // FIXME: LabelTy should not be a first-class type.
3228 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3229 return Error(ID.Loc, "invalid type for undef constant");
3230 V = UndefValue::get(Ty);
3232 case ValID::t_EmptyArray:
3233 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3234 return Error(ID.Loc, "invalid empty array initializer");
3235 V = UndefValue::get(Ty);
3238 // FIXME: LabelTy should not be a first-class type.
3239 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3240 return Error(ID.Loc, "invalid type for null constant");
3241 V = Constant::getNullValue(Ty);
3243 case ValID::t_Constant:
3244 if (ID.ConstantVal->getType() != Ty)
3245 return Error(ID.Loc, "constant expression type mismatch");
3249 case ValID::t_ConstantStruct:
3250 case ValID::t_PackedConstantStruct:
3251 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3252 if (ST->getNumElements() != ID.UIntVal)
3253 return Error(ID.Loc,
3254 "initializer with struct type has wrong # elements");
3255 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3256 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3258 // Verify that the elements are compatible with the structtype.
3259 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3260 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3261 return Error(ID.Loc, "element " + Twine(i) +
3262 " of struct initializer doesn't match struct element type");
3264 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3267 return Error(ID.Loc, "constant expression type mismatch");
3270 llvm_unreachable("Invalid ValID");
3273 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3276 return ParseValID(ID, PFS) ||
3277 ConvertValIDToValue(Ty, ID, V, PFS);
3280 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3282 return ParseType(Ty) ||
3283 ParseValue(Ty, V, PFS);
3286 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3287 PerFunctionState &PFS) {
3290 if (ParseTypeAndValue(V, PFS)) return true;
3291 if (!isa<BasicBlock>(V))
3292 return Error(Loc, "expected a basic block");
3293 BB = cast<BasicBlock>(V);
3299 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3300 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3301 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3302 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3303 // Parse the linkage.
3304 LocTy LinkageLoc = Lex.getLoc();
3307 unsigned Visibility;
3308 unsigned DLLStorageClass;
3309 AttrBuilder RetAttrs;
3311 Type *RetType = nullptr;
3312 LocTy RetTypeLoc = Lex.getLoc();
3313 if (ParseOptionalLinkage(Linkage) ||
3314 ParseOptionalVisibility(Visibility) ||
3315 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3316 ParseOptionalCallingConv(CC) ||
3317 ParseOptionalReturnAttrs(RetAttrs) ||
3318 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3321 // Verify that the linkage is ok.
3322 switch ((GlobalValue::LinkageTypes)Linkage) {
3323 case GlobalValue::ExternalLinkage:
3324 break; // always ok.
3325 case GlobalValue::ExternalWeakLinkage:
3327 return Error(LinkageLoc, "invalid linkage for function definition");
3329 case GlobalValue::PrivateLinkage:
3330 case GlobalValue::InternalLinkage:
3331 case GlobalValue::AvailableExternallyLinkage:
3332 case GlobalValue::LinkOnceAnyLinkage:
3333 case GlobalValue::LinkOnceODRLinkage:
3334 case GlobalValue::WeakAnyLinkage:
3335 case GlobalValue::WeakODRLinkage:
3337 return Error(LinkageLoc, "invalid linkage for function declaration");
3339 case GlobalValue::AppendingLinkage:
3340 case GlobalValue::CommonLinkage:
3341 return Error(LinkageLoc, "invalid function linkage type");
3344 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3345 return Error(LinkageLoc,
3346 "symbol with local linkage must have default visibility");
3348 if (!FunctionType::isValidReturnType(RetType))
3349 return Error(RetTypeLoc, "invalid function return type");
3351 LocTy NameLoc = Lex.getLoc();
3353 std::string FunctionName;
3354 if (Lex.getKind() == lltok::GlobalVar) {
3355 FunctionName = Lex.getStrVal();
3356 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3357 unsigned NameID = Lex.getUIntVal();
3359 if (NameID != NumberedVals.size())
3360 return TokError("function expected to be numbered '%" +
3361 Twine(NumberedVals.size()) + "'");
3363 return TokError("expected function name");
3368 if (Lex.getKind() != lltok::lparen)
3369 return TokError("expected '(' in function argument list");
3371 SmallVector<ArgInfo, 8> ArgList;
3373 AttrBuilder FuncAttrs;
3374 std::vector<unsigned> FwdRefAttrGrps;
3376 std::string Section;
3380 LocTy UnnamedAddrLoc;
3381 Constant *Prefix = nullptr;
3382 Constant *Prologue = nullptr;
3385 if (ParseArgumentList(ArgList, isVarArg) ||
3386 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3388 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3390 (EatIfPresent(lltok::kw_section) &&
3391 ParseStringConstant(Section)) ||
3392 parseOptionalComdat(FunctionName, C) ||
3393 ParseOptionalAlignment(Alignment) ||
3394 (EatIfPresent(lltok::kw_gc) &&
3395 ParseStringConstant(GC)) ||
3396 (EatIfPresent(lltok::kw_prefix) &&
3397 ParseGlobalTypeAndValue(Prefix)) ||
3398 (EatIfPresent(lltok::kw_prologue) &&
3399 ParseGlobalTypeAndValue(Prologue)))
3402 if (FuncAttrs.contains(Attribute::Builtin))
3403 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3405 // If the alignment was parsed as an attribute, move to the alignment field.
3406 if (FuncAttrs.hasAlignmentAttr()) {
3407 Alignment = FuncAttrs.getAlignment();
3408 FuncAttrs.removeAttribute(Attribute::Alignment);
3411 // Okay, if we got here, the function is syntactically valid. Convert types
3412 // and do semantic checks.
3413 std::vector<Type*> ParamTypeList;
3414 SmallVector<AttributeSet, 8> Attrs;
3416 if (RetAttrs.hasAttributes())
3417 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3418 AttributeSet::ReturnIndex,
3421 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3422 ParamTypeList.push_back(ArgList[i].Ty);
3423 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3424 AttrBuilder B(ArgList[i].Attrs, i + 1);
3425 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3429 if (FuncAttrs.hasAttributes())
3430 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3431 AttributeSet::FunctionIndex,
3434 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3436 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3437 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3440 FunctionType::get(RetType, ParamTypeList, isVarArg);
3441 PointerType *PFT = PointerType::getUnqual(FT);
3444 if (!FunctionName.empty()) {
3445 // If this was a definition of a forward reference, remove the definition
3446 // from the forward reference table and fill in the forward ref.
3447 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3448 ForwardRefVals.find(FunctionName);
3449 if (FRVI != ForwardRefVals.end()) {
3450 Fn = M->getFunction(FunctionName);
3452 return Error(FRVI->second.second, "invalid forward reference to "
3453 "function as global value!");
3454 if (Fn->getType() != PFT)
3455 return Error(FRVI->second.second, "invalid forward reference to "
3456 "function '" + FunctionName + "' with wrong type!");
3458 ForwardRefVals.erase(FRVI);
3459 } else if ((Fn = M->getFunction(FunctionName))) {
3460 // Reject redefinitions.
3461 return Error(NameLoc, "invalid redefinition of function '" +
3462 FunctionName + "'");
3463 } else if (M->getNamedValue(FunctionName)) {
3464 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3468 // If this is a definition of a forward referenced function, make sure the
3470 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3471 = ForwardRefValIDs.find(NumberedVals.size());
3472 if (I != ForwardRefValIDs.end()) {
3473 Fn = cast<Function>(I->second.first);
3474 if (Fn->getType() != PFT)
3475 return Error(NameLoc, "type of definition and forward reference of '@" +
3476 Twine(NumberedVals.size()) + "' disagree");
3477 ForwardRefValIDs.erase(I);
3482 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3483 else // Move the forward-reference to the correct spot in the module.
3484 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3486 if (FunctionName.empty())
3487 NumberedVals.push_back(Fn);
3489 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3490 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3491 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3492 Fn->setCallingConv(CC);
3493 Fn->setAttributes(PAL);
3494 Fn->setUnnamedAddr(UnnamedAddr);
3495 Fn->setAlignment(Alignment);
3496 Fn->setSection(Section);
3498 if (!GC.empty()) Fn->setGC(GC.c_str());
3499 Fn->setPrefixData(Prefix);
3500 Fn->setPrologueData(Prologue);
3501 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3503 // Add all of the arguments we parsed to the function.
3504 Function::arg_iterator ArgIt = Fn->arg_begin();
3505 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3506 // If the argument has a name, insert it into the argument symbol table.
3507 if (ArgList[i].Name.empty()) continue;
3509 // Set the name, if it conflicted, it will be auto-renamed.
3510 ArgIt->setName(ArgList[i].Name);
3512 if (ArgIt->getName() != ArgList[i].Name)
3513 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3514 ArgList[i].Name + "'");
3520 // Check the declaration has no block address forward references.
3522 if (FunctionName.empty()) {
3523 ID.Kind = ValID::t_GlobalID;
3524 ID.UIntVal = NumberedVals.size() - 1;
3526 ID.Kind = ValID::t_GlobalName;
3527 ID.StrVal = FunctionName;
3529 auto Blocks = ForwardRefBlockAddresses.find(ID);
3530 if (Blocks != ForwardRefBlockAddresses.end())
3531 return Error(Blocks->first.Loc,
3532 "cannot take blockaddress inside a declaration");
3536 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3538 if (FunctionNumber == -1) {
3539 ID.Kind = ValID::t_GlobalName;
3540 ID.StrVal = F.getName();
3542 ID.Kind = ValID::t_GlobalID;
3543 ID.UIntVal = FunctionNumber;
3546 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3547 if (Blocks == P.ForwardRefBlockAddresses.end())
3550 for (const auto &I : Blocks->second) {
3551 const ValID &BBID = I.first;
3552 GlobalValue *GV = I.second;
3554 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3555 "Expected local id or name");
3557 if (BBID.Kind == ValID::t_LocalName)
3558 BB = GetBB(BBID.StrVal, BBID.Loc);
3560 BB = GetBB(BBID.UIntVal, BBID.Loc);
3562 return P.Error(BBID.Loc, "referenced value is not a basic block");
3564 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3565 GV->eraseFromParent();
3568 P.ForwardRefBlockAddresses.erase(Blocks);
3572 /// ParseFunctionBody
3573 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
3574 bool LLParser::ParseFunctionBody(Function &Fn) {
3575 if (Lex.getKind() != lltok::lbrace)
3576 return TokError("expected '{' in function body");
3577 Lex.Lex(); // eat the {.
3579 int FunctionNumber = -1;
3580 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3582 PerFunctionState PFS(*this, Fn, FunctionNumber);
3584 // Resolve block addresses and allow basic blocks to be forward-declared
3585 // within this function.
3586 if (PFS.resolveForwardRefBlockAddresses())
3588 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3590 // We need at least one basic block.
3591 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
3592 return TokError("function body requires at least one basic block");
3594 while (Lex.getKind() != lltok::rbrace &&
3595 Lex.getKind() != lltok::kw_uselistorder)
3596 if (ParseBasicBlock(PFS)) return true;
3598 while (Lex.getKind() != lltok::rbrace)
3599 if (ParseUseListOrder(&PFS))
3605 // Verify function is ok.
3606 return PFS.FinishFunction();
3610 /// ::= LabelStr? Instruction*
3611 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3612 // If this basic block starts out with a name, remember it.
3614 LocTy NameLoc = Lex.getLoc();
3615 if (Lex.getKind() == lltok::LabelStr) {
3616 Name = Lex.getStrVal();
3620 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3621 if (!BB) return true;
3623 std::string NameStr;
3625 // Parse the instructions in this block until we get a terminator.
3628 // This instruction may have three possibilities for a name: a) none
3629 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3630 LocTy NameLoc = Lex.getLoc();
3634 if (Lex.getKind() == lltok::LocalVarID) {
3635 NameID = Lex.getUIntVal();
3637 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3639 } else if (Lex.getKind() == lltok::LocalVar) {
3640 NameStr = Lex.getStrVal();
3642 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3646 switch (ParseInstruction(Inst, BB, PFS)) {
3647 default: llvm_unreachable("Unknown ParseInstruction result!");
3648 case InstError: return true;
3650 BB->getInstList().push_back(Inst);
3652 // With a normal result, we check to see if the instruction is followed by
3653 // a comma and metadata.
3654 if (EatIfPresent(lltok::comma))
3655 if (ParseInstructionMetadata(Inst, &PFS))
3658 case InstExtraComma:
3659 BB->getInstList().push_back(Inst);
3661 // If the instruction parser ate an extra comma at the end of it, it
3662 // *must* be followed by metadata.
3663 if (ParseInstructionMetadata(Inst, &PFS))
3668 // Set the name on the instruction.
3669 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3670 } while (!isa<TerminatorInst>(Inst));
3675 //===----------------------------------------------------------------------===//
3676 // Instruction Parsing.
3677 //===----------------------------------------------------------------------===//
3679 /// ParseInstruction - Parse one of the many different instructions.
3681 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3682 PerFunctionState &PFS) {
3683 lltok::Kind Token = Lex.getKind();
3684 if (Token == lltok::Eof)
3685 return TokError("found end of file when expecting more instructions");
3686 LocTy Loc = Lex.getLoc();
3687 unsigned KeywordVal = Lex.getUIntVal();
3688 Lex.Lex(); // Eat the keyword.
3691 default: return Error(Loc, "expected instruction opcode");
3692 // Terminator Instructions.
3693 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3694 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3695 case lltok::kw_br: return ParseBr(Inst, PFS);
3696 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3697 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3698 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3699 case lltok::kw_resume: return ParseResume(Inst, PFS);
3700 // Binary Operators.
3704 case lltok::kw_shl: {
3705 bool NUW = EatIfPresent(lltok::kw_nuw);
3706 bool NSW = EatIfPresent(lltok::kw_nsw);
3707 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3709 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3711 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3712 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3715 case lltok::kw_fadd:
3716 case lltok::kw_fsub:
3717 case lltok::kw_fmul:
3718 case lltok::kw_fdiv:
3719 case lltok::kw_frem: {
3720 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3721 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3725 Inst->setFastMathFlags(FMF);
3729 case lltok::kw_sdiv:
3730 case lltok::kw_udiv:
3731 case lltok::kw_lshr:
3732 case lltok::kw_ashr: {
3733 bool Exact = EatIfPresent(lltok::kw_exact);
3735 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3736 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3740 case lltok::kw_urem:
3741 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3744 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3745 case lltok::kw_icmp:
3746 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3748 case lltok::kw_trunc:
3749 case lltok::kw_zext:
3750 case lltok::kw_sext:
3751 case lltok::kw_fptrunc:
3752 case lltok::kw_fpext:
3753 case lltok::kw_bitcast:
3754 case lltok::kw_addrspacecast:
3755 case lltok::kw_uitofp:
3756 case lltok::kw_sitofp:
3757 case lltok::kw_fptoui:
3758 case lltok::kw_fptosi:
3759 case lltok::kw_inttoptr:
3760 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3762 case lltok::kw_select: return ParseSelect(Inst, PFS);
3763 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3764 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3765 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3766 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3767 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3768 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3770 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3771 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3772 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3774 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3775 case lltok::kw_load: return ParseLoad(Inst, PFS);
3776 case lltok::kw_store: return ParseStore(Inst, PFS);
3777 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3778 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3779 case lltok::kw_fence: return ParseFence(Inst, PFS);
3780 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3781 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3782 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3786 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3787 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3788 if (Opc == Instruction::FCmp) {
3789 switch (Lex.getKind()) {
3790 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3791 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3792 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3793 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3794 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3795 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3796 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3797 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3798 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3799 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3800 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3801 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3802 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3803 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3804 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3805 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3806 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3809 switch (Lex.getKind()) {
3810 default: return TokError("expected icmp predicate (e.g. 'eq')");
3811 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3812 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3813 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3814 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3815 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3816 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3817 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3818 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3819 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3820 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3827 //===----------------------------------------------------------------------===//
3828 // Terminator Instructions.
3829 //===----------------------------------------------------------------------===//
3831 /// ParseRet - Parse a return instruction.
3832 /// ::= 'ret' void (',' !dbg, !1)*
3833 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3834 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3835 PerFunctionState &PFS) {
3836 SMLoc TypeLoc = Lex.getLoc();
3838 if (ParseType(Ty, true /*void allowed*/)) return true;
3840 Type *ResType = PFS.getFunction().getReturnType();
3842 if (Ty->isVoidTy()) {
3843 if (!ResType->isVoidTy())
3844 return Error(TypeLoc, "value doesn't match function result type '" +
3845 getTypeString(ResType) + "'");
3847 Inst = ReturnInst::Create(Context);
3852 if (ParseValue(Ty, RV, PFS)) return true;
3854 if (ResType != RV->getType())
3855 return Error(TypeLoc, "value doesn't match function result type '" +
3856 getTypeString(ResType) + "'");
3858 Inst = ReturnInst::Create(Context, RV);
3864 /// ::= 'br' TypeAndValue
3865 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3866 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3869 BasicBlock *Op1, *Op2;
3870 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3872 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3873 Inst = BranchInst::Create(BB);
3877 if (Op0->getType() != Type::getInt1Ty(Context))
3878 return Error(Loc, "branch condition must have 'i1' type");
3880 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3881 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3882 ParseToken(lltok::comma, "expected ',' after true destination") ||
3883 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3886 Inst = BranchInst::Create(Op1, Op2, Op0);
3892 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3894 /// ::= (TypeAndValue ',' TypeAndValue)*
3895 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3896 LocTy CondLoc, BBLoc;
3898 BasicBlock *DefaultBB;
3899 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3900 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3901 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3902 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3905 if (!Cond->getType()->isIntegerTy())
3906 return Error(CondLoc, "switch condition must have integer type");
3908 // Parse the jump table pairs.
3909 SmallPtrSet<Value*, 32> SeenCases;
3910 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3911 while (Lex.getKind() != lltok::rsquare) {
3915 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3916 ParseToken(lltok::comma, "expected ',' after case value") ||
3917 ParseTypeAndBasicBlock(DestBB, PFS))
3920 if (!SeenCases.insert(Constant).second)
3921 return Error(CondLoc, "duplicate case value in switch");
3922 if (!isa<ConstantInt>(Constant))
3923 return Error(CondLoc, "case value is not a constant integer");
3925 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3928 Lex.Lex(); // Eat the ']'.
3930 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3931 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3932 SI->addCase(Table[i].first, Table[i].second);
3939 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3940 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3943 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3944 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3945 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3948 if (!Address->getType()->isPointerTy())
3949 return Error(AddrLoc, "indirectbr address must have pointer type");
3951 // Parse the destination list.
3952 SmallVector<BasicBlock*, 16> DestList;
3954 if (Lex.getKind() != lltok::rsquare) {
3956 if (ParseTypeAndBasicBlock(DestBB, PFS))
3958 DestList.push_back(DestBB);
3960 while (EatIfPresent(lltok::comma)) {
3961 if (ParseTypeAndBasicBlock(DestBB, PFS))
3963 DestList.push_back(DestBB);
3967 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3970 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3971 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3972 IBI->addDestination(DestList[i]);
3979 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3980 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3981 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3982 LocTy CallLoc = Lex.getLoc();
3983 AttrBuilder RetAttrs, FnAttrs;
3984 std::vector<unsigned> FwdRefAttrGrps;
3987 Type *RetType = nullptr;
3990 SmallVector<ParamInfo, 16> ArgList;
3992 BasicBlock *NormalBB, *UnwindBB;
3993 if (ParseOptionalCallingConv(CC) ||
3994 ParseOptionalReturnAttrs(RetAttrs) ||
3995 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3996 ParseValID(CalleeID) ||
3997 ParseParameterList(ArgList, PFS) ||
3998 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4000 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4001 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4002 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4003 ParseTypeAndBasicBlock(UnwindBB, PFS))
4006 // If RetType is a non-function pointer type, then this is the short syntax
4007 // for the call, which means that RetType is just the return type. Infer the
4008 // rest of the function argument types from the arguments that are present.
4009 PointerType *PFTy = nullptr;
4010 FunctionType *Ty = nullptr;
4011 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4012 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4013 // Pull out the types of all of the arguments...
4014 std::vector<Type*> ParamTypes;
4015 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4016 ParamTypes.push_back(ArgList[i].V->getType());
4018 if (!FunctionType::isValidReturnType(RetType))
4019 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4021 Ty = FunctionType::get(RetType, ParamTypes, false);
4022 PFTy = PointerType::getUnqual(Ty);
4025 // Look up the callee.
4027 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4029 // Set up the Attribute for the function.
4030 SmallVector<AttributeSet, 8> Attrs;
4031 if (RetAttrs.hasAttributes())
4032 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4033 AttributeSet::ReturnIndex,
4036 SmallVector<Value*, 8> Args;
4038 // Loop through FunctionType's arguments and ensure they are specified
4039 // correctly. Also, gather any parameter attributes.
4040 FunctionType::param_iterator I = Ty->param_begin();
4041 FunctionType::param_iterator E = Ty->param_end();
4042 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4043 Type *ExpectedTy = nullptr;
4046 } else if (!Ty->isVarArg()) {
4047 return Error(ArgList[i].Loc, "too many arguments specified");
4050 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4051 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4052 getTypeString(ExpectedTy) + "'");
4053 Args.push_back(ArgList[i].V);
4054 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4055 AttrBuilder B(ArgList[i].Attrs, i + 1);
4056 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4061 return Error(CallLoc, "not enough parameters specified for call");
4063 if (FnAttrs.hasAttributes())
4064 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4065 AttributeSet::FunctionIndex,
4068 // Finish off the Attribute and check them
4069 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4071 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4072 II->setCallingConv(CC);
4073 II->setAttributes(PAL);
4074 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4080 /// ::= 'resume' TypeAndValue
4081 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4082 Value *Exn; LocTy ExnLoc;
4083 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4086 ResumeInst *RI = ResumeInst::Create(Exn);
4091 //===----------------------------------------------------------------------===//
4092 // Binary Operators.
4093 //===----------------------------------------------------------------------===//
4096 /// ::= ArithmeticOps TypeAndValue ',' Value
4098 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4099 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4100 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4101 unsigned Opc, unsigned OperandType) {
4102 LocTy Loc; Value *LHS, *RHS;
4103 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4104 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4105 ParseValue(LHS->getType(), RHS, PFS))
4109 switch (OperandType) {
4110 default: llvm_unreachable("Unknown operand type!");
4111 case 0: // int or FP.
4112 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4113 LHS->getType()->isFPOrFPVectorTy();
4115 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4116 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4120 return Error(Loc, "invalid operand type for instruction");
4122 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4127 /// ::= ArithmeticOps TypeAndValue ',' Value {
4128 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4130 LocTy Loc; Value *LHS, *RHS;
4131 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4132 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4133 ParseValue(LHS->getType(), RHS, PFS))
4136 if (!LHS->getType()->isIntOrIntVectorTy())
4137 return Error(Loc,"instruction requires integer or integer vector operands");
4139 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4145 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4146 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4147 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4149 // Parse the integer/fp comparison predicate.
4153 if (ParseCmpPredicate(Pred, Opc) ||
4154 ParseTypeAndValue(LHS, Loc, PFS) ||
4155 ParseToken(lltok::comma, "expected ',' after compare value") ||
4156 ParseValue(LHS->getType(), RHS, PFS))
4159 if (Opc == Instruction::FCmp) {
4160 if (!LHS->getType()->isFPOrFPVectorTy())
4161 return Error(Loc, "fcmp requires floating point operands");
4162 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4164 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4165 if (!LHS->getType()->isIntOrIntVectorTy() &&
4166 !LHS->getType()->getScalarType()->isPointerTy())
4167 return Error(Loc, "icmp requires integer operands");
4168 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4173 //===----------------------------------------------------------------------===//
4174 // Other Instructions.
4175 //===----------------------------------------------------------------------===//
4179 /// ::= CastOpc TypeAndValue 'to' Type
4180 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4184 Type *DestTy = nullptr;
4185 if (ParseTypeAndValue(Op, Loc, PFS) ||
4186 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4190 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4191 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4192 return Error(Loc, "invalid cast opcode for cast from '" +
4193 getTypeString(Op->getType()) + "' to '" +
4194 getTypeString(DestTy) + "'");
4196 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4201 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4202 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4204 Value *Op0, *Op1, *Op2;
4205 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4206 ParseToken(lltok::comma, "expected ',' after select condition") ||
4207 ParseTypeAndValue(Op1, PFS) ||
4208 ParseToken(lltok::comma, "expected ',' after select value") ||
4209 ParseTypeAndValue(Op2, PFS))
4212 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4213 return Error(Loc, Reason);
4215 Inst = SelectInst::Create(Op0, Op1, Op2);
4220 /// ::= 'va_arg' TypeAndValue ',' Type
4221 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4223 Type *EltTy = nullptr;
4225 if (ParseTypeAndValue(Op, PFS) ||
4226 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4227 ParseType(EltTy, TypeLoc))
4230 if (!EltTy->isFirstClassType())
4231 return Error(TypeLoc, "va_arg requires operand with first class type");
4233 Inst = new VAArgInst(Op, EltTy);
4237 /// ParseExtractElement
4238 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4239 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4242 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4243 ParseToken(lltok::comma, "expected ',' after extract value") ||
4244 ParseTypeAndValue(Op1, PFS))
4247 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4248 return Error(Loc, "invalid extractelement operands");
4250 Inst = ExtractElementInst::Create(Op0, Op1);
4254 /// ParseInsertElement
4255 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4256 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4258 Value *Op0, *Op1, *Op2;
4259 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4260 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4261 ParseTypeAndValue(Op1, PFS) ||
4262 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4263 ParseTypeAndValue(Op2, PFS))
4266 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4267 return Error(Loc, "invalid insertelement operands");
4269 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4273 /// ParseShuffleVector
4274 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4275 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4277 Value *Op0, *Op1, *Op2;
4278 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4279 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4280 ParseTypeAndValue(Op1, PFS) ||
4281 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4282 ParseTypeAndValue(Op2, PFS))
4285 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4286 return Error(Loc, "invalid shufflevector operands");
4288 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4293 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4294 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4295 Type *Ty = nullptr; LocTy TypeLoc;
4298 if (ParseType(Ty, TypeLoc) ||
4299 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4300 ParseValue(Ty, Op0, PFS) ||
4301 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4302 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4303 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4306 bool AteExtraComma = false;
4307 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4309 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4311 if (!EatIfPresent(lltok::comma))
4314 if (Lex.getKind() == lltok::MetadataVar) {
4315 AteExtraComma = true;
4319 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4320 ParseValue(Ty, Op0, PFS) ||
4321 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4322 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4323 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4327 if (!Ty->isFirstClassType())
4328 return Error(TypeLoc, "phi node must have first class type");
4330 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4331 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4332 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4334 return AteExtraComma ? InstExtraComma : InstNormal;
4338 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4340 /// ::= 'catch' TypeAndValue
4342 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4343 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4344 Type *Ty = nullptr; LocTy TyLoc;
4345 Value *PersFn; LocTy PersFnLoc;
4347 if (ParseType(Ty, TyLoc) ||
4348 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4349 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4352 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4353 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4355 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4356 LandingPadInst::ClauseType CT;
4357 if (EatIfPresent(lltok::kw_catch))
4358 CT = LandingPadInst::Catch;
4359 else if (EatIfPresent(lltok::kw_filter))
4360 CT = LandingPadInst::Filter;
4362 return TokError("expected 'catch' or 'filter' clause type");
4366 if (ParseTypeAndValue(V, VLoc, PFS)) {
4371 // A 'catch' type expects a non-array constant. A filter clause expects an
4373 if (CT == LandingPadInst::Catch) {
4374 if (isa<ArrayType>(V->getType()))
4375 Error(VLoc, "'catch' clause has an invalid type");
4377 if (!isa<ArrayType>(V->getType()))
4378 Error(VLoc, "'filter' clause has an invalid type");
4381 LP->addClause(cast<Constant>(V));
4389 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4390 /// ParameterList OptionalAttrs
4391 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4392 /// ParameterList OptionalAttrs
4393 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4394 /// ParameterList OptionalAttrs
4395 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4396 CallInst::TailCallKind TCK) {
4397 AttrBuilder RetAttrs, FnAttrs;
4398 std::vector<unsigned> FwdRefAttrGrps;
4401 Type *RetType = nullptr;
4404 SmallVector<ParamInfo, 16> ArgList;
4405 LocTy CallLoc = Lex.getLoc();
4407 if ((TCK != CallInst::TCK_None &&
4408 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4409 ParseOptionalCallingConv(CC) ||
4410 ParseOptionalReturnAttrs(RetAttrs) ||
4411 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4412 ParseValID(CalleeID) ||
4413 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4414 PFS.getFunction().isVarArg()) ||
4415 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4419 // If RetType is a non-function pointer type, then this is the short syntax
4420 // for the call, which means that RetType is just the return type. Infer the
4421 // rest of the function argument types from the arguments that are present.
4422 PointerType *PFTy = nullptr;
4423 FunctionType *Ty = nullptr;
4424 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4425 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4426 // Pull out the types of all of the arguments...
4427 std::vector<Type*> ParamTypes;
4428 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4429 ParamTypes.push_back(ArgList[i].V->getType());
4431 if (!FunctionType::isValidReturnType(RetType))
4432 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4434 Ty = FunctionType::get(RetType, ParamTypes, false);
4435 PFTy = PointerType::getUnqual(Ty);
4438 // Look up the callee.
4440 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4442 // Set up the Attribute for the function.
4443 SmallVector<AttributeSet, 8> Attrs;
4444 if (RetAttrs.hasAttributes())
4445 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4446 AttributeSet::ReturnIndex,
4449 SmallVector<Value*, 8> Args;
4451 // Loop through FunctionType's arguments and ensure they are specified
4452 // correctly. Also, gather any parameter attributes.
4453 FunctionType::param_iterator I = Ty->param_begin();
4454 FunctionType::param_iterator E = Ty->param_end();
4455 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4456 Type *ExpectedTy = nullptr;
4459 } else if (!Ty->isVarArg()) {
4460 return Error(ArgList[i].Loc, "too many arguments specified");
4463 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4464 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4465 getTypeString(ExpectedTy) + "'");
4466 Args.push_back(ArgList[i].V);
4467 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4468 AttrBuilder B(ArgList[i].Attrs, i + 1);
4469 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4474 return Error(CallLoc, "not enough parameters specified for call");
4476 if (FnAttrs.hasAttributes())
4477 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4478 AttributeSet::FunctionIndex,
4481 // Finish off the Attribute and check them
4482 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4484 CallInst *CI = CallInst::Create(Callee, Args);
4485 CI->setTailCallKind(TCK);
4486 CI->setCallingConv(CC);
4487 CI->setAttributes(PAL);
4488 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4493 //===----------------------------------------------------------------------===//
4494 // Memory Instructions.
4495 //===----------------------------------------------------------------------===//
4498 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4499 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4500 Value *Size = nullptr;
4502 unsigned Alignment = 0;
4505 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4507 if (ParseType(Ty)) return true;
4509 bool AteExtraComma = false;
4510 if (EatIfPresent(lltok::comma)) {
4511 if (Lex.getKind() == lltok::kw_align) {
4512 if (ParseOptionalAlignment(Alignment)) return true;
4513 } else if (Lex.getKind() == lltok::MetadataVar) {
4514 AteExtraComma = true;
4516 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4517 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4522 if (Size && !Size->getType()->isIntegerTy())
4523 return Error(SizeLoc, "element count must have integer type");
4525 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4526 AI->setUsedWithInAlloca(IsInAlloca);
4528 return AteExtraComma ? InstExtraComma : InstNormal;
4532 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4533 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4534 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4535 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4536 Value *Val; LocTy Loc;
4537 unsigned Alignment = 0;
4538 bool AteExtraComma = false;
4539 bool isAtomic = false;
4540 AtomicOrdering Ordering = NotAtomic;
4541 SynchronizationScope Scope = CrossThread;
4543 if (Lex.getKind() == lltok::kw_atomic) {
4548 bool isVolatile = false;
4549 if (Lex.getKind() == lltok::kw_volatile) {
4554 if (ParseTypeAndValue(Val, Loc, PFS) ||
4555 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4556 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4559 if (!Val->getType()->isPointerTy() ||
4560 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4561 return Error(Loc, "load operand must be a pointer to a first class type");
4562 if (isAtomic && !Alignment)
4563 return Error(Loc, "atomic load must have explicit non-zero alignment");
4564 if (Ordering == Release || Ordering == AcquireRelease)
4565 return Error(Loc, "atomic load cannot use Release ordering");
4567 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4568 return AteExtraComma ? InstExtraComma : InstNormal;
4573 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4574 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4575 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4576 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4577 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4578 unsigned Alignment = 0;
4579 bool AteExtraComma = false;
4580 bool isAtomic = false;
4581 AtomicOrdering Ordering = NotAtomic;
4582 SynchronizationScope Scope = CrossThread;
4584 if (Lex.getKind() == lltok::kw_atomic) {
4589 bool isVolatile = false;
4590 if (Lex.getKind() == lltok::kw_volatile) {
4595 if (ParseTypeAndValue(Val, Loc, PFS) ||
4596 ParseToken(lltok::comma, "expected ',' after store operand") ||
4597 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4598 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4599 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4602 if (!Ptr->getType()->isPointerTy())
4603 return Error(PtrLoc, "store operand must be a pointer");
4604 if (!Val->getType()->isFirstClassType())
4605 return Error(Loc, "store operand must be a first class value");
4606 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4607 return Error(Loc, "stored value and pointer type do not match");
4608 if (isAtomic && !Alignment)
4609 return Error(Loc, "atomic store must have explicit non-zero alignment");
4610 if (Ordering == Acquire || Ordering == AcquireRelease)
4611 return Error(Loc, "atomic store cannot use Acquire ordering");
4613 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4614 return AteExtraComma ? InstExtraComma : InstNormal;
4618 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4619 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4620 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4621 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4622 bool AteExtraComma = false;
4623 AtomicOrdering SuccessOrdering = NotAtomic;
4624 AtomicOrdering FailureOrdering = NotAtomic;
4625 SynchronizationScope Scope = CrossThread;
4626 bool isVolatile = false;
4627 bool isWeak = false;
4629 if (EatIfPresent(lltok::kw_weak))
4632 if (EatIfPresent(lltok::kw_volatile))
4635 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4636 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4637 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4638 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4639 ParseTypeAndValue(New, NewLoc, PFS) ||
4640 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4641 ParseOrdering(FailureOrdering))
4644 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4645 return TokError("cmpxchg cannot be unordered");
4646 if (SuccessOrdering < FailureOrdering)
4647 return TokError("cmpxchg must be at least as ordered on success as failure");
4648 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4649 return TokError("cmpxchg failure ordering cannot include release semantics");
4650 if (!Ptr->getType()->isPointerTy())
4651 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4652 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4653 return Error(CmpLoc, "compare value and pointer type do not match");
4654 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4655 return Error(NewLoc, "new value and pointer type do not match");
4656 if (!New->getType()->isIntegerTy())
4657 return Error(NewLoc, "cmpxchg operand must be an integer");
4658 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4659 if (Size < 8 || (Size & (Size - 1)))
4660 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4663 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4664 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4665 CXI->setVolatile(isVolatile);
4666 CXI->setWeak(isWeak);
4668 return AteExtraComma ? InstExtraComma : InstNormal;
4672 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4673 /// 'singlethread'? AtomicOrdering
4674 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4675 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4676 bool AteExtraComma = false;
4677 AtomicOrdering Ordering = NotAtomic;
4678 SynchronizationScope Scope = CrossThread;
4679 bool isVolatile = false;
4680 AtomicRMWInst::BinOp Operation;
4682 if (EatIfPresent(lltok::kw_volatile))
4685 switch (Lex.getKind()) {
4686 default: return TokError("expected binary operation in atomicrmw");
4687 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4688 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4689 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4690 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4691 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4692 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4693 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4694 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4695 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4696 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4697 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4699 Lex.Lex(); // Eat the operation.
4701 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4702 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4703 ParseTypeAndValue(Val, ValLoc, PFS) ||
4704 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4707 if (Ordering == Unordered)
4708 return TokError("atomicrmw cannot be unordered");
4709 if (!Ptr->getType()->isPointerTy())
4710 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4711 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4712 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4713 if (!Val->getType()->isIntegerTy())
4714 return Error(ValLoc, "atomicrmw operand must be an integer");
4715 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4716 if (Size < 8 || (Size & (Size - 1)))
4717 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4720 AtomicRMWInst *RMWI =
4721 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4722 RMWI->setVolatile(isVolatile);
4724 return AteExtraComma ? InstExtraComma : InstNormal;
4728 /// ::= 'fence' 'singlethread'? AtomicOrdering
4729 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4730 AtomicOrdering Ordering = NotAtomic;
4731 SynchronizationScope Scope = CrossThread;
4732 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4735 if (Ordering == Unordered)
4736 return TokError("fence cannot be unordered");
4737 if (Ordering == Monotonic)
4738 return TokError("fence cannot be monotonic");
4740 Inst = new FenceInst(Context, Ordering, Scope);
4744 /// ParseGetElementPtr
4745 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4746 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4747 Value *Ptr = nullptr;
4748 Value *Val = nullptr;
4751 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4753 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4755 Type *BaseType = Ptr->getType();
4756 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4757 if (!BasePointerType)
4758 return Error(Loc, "base of getelementptr must be a pointer");
4760 SmallVector<Value*, 16> Indices;
4761 bool AteExtraComma = false;
4762 while (EatIfPresent(lltok::comma)) {
4763 if (Lex.getKind() == lltok::MetadataVar) {
4764 AteExtraComma = true;
4767 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4768 if (!Val->getType()->getScalarType()->isIntegerTy())
4769 return Error(EltLoc, "getelementptr index must be an integer");
4770 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4771 return Error(EltLoc, "getelementptr index type missmatch");
4772 if (Val->getType()->isVectorTy()) {
4773 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4774 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4775 if (ValNumEl != PtrNumEl)
4776 return Error(EltLoc,
4777 "getelementptr vector index has a wrong number of elements");
4779 Indices.push_back(Val);
4782 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4783 return Error(Loc, "base element of getelementptr must be sized");
4785 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4786 return Error(Loc, "invalid getelementptr indices");
4787 Inst = GetElementPtrInst::Create(Ptr, Indices);
4789 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4790 return AteExtraComma ? InstExtraComma : InstNormal;
4793 /// ParseExtractValue
4794 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4795 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4796 Value *Val; LocTy Loc;
4797 SmallVector<unsigned, 4> Indices;
4799 if (ParseTypeAndValue(Val, Loc, PFS) ||
4800 ParseIndexList(Indices, AteExtraComma))
4803 if (!Val->getType()->isAggregateType())
4804 return Error(Loc, "extractvalue operand must be aggregate type");
4806 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4807 return Error(Loc, "invalid indices for extractvalue");
4808 Inst = ExtractValueInst::Create(Val, Indices);
4809 return AteExtraComma ? InstExtraComma : InstNormal;
4812 /// ParseInsertValue
4813 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4814 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4815 Value *Val0, *Val1; LocTy Loc0, Loc1;
4816 SmallVector<unsigned, 4> Indices;
4818 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4819 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4820 ParseTypeAndValue(Val1, Loc1, PFS) ||
4821 ParseIndexList(Indices, AteExtraComma))
4824 if (!Val0->getType()->isAggregateType())
4825 return Error(Loc0, "insertvalue operand must be aggregate type");
4827 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4828 return Error(Loc0, "invalid indices for insertvalue");
4829 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4830 return AteExtraComma ? InstExtraComma : InstNormal;
4833 //===----------------------------------------------------------------------===//
4834 // Embedded metadata.
4835 //===----------------------------------------------------------------------===//
4837 /// ParseMDNodeVector
4838 /// ::= { Element (',' Element)* }
4840 /// ::= 'null' | TypeAndValue
4841 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
4842 if (ParseToken(lltok::lbrace, "expected '{' here"))
4845 // Check for an empty list.
4846 if (EatIfPresent(lltok::rbrace))
4850 // Null is a special case since it is typeless.
4851 if (EatIfPresent(lltok::kw_null)) {
4852 Elts.push_back(nullptr);
4857 if (ParseMetadata(MD, nullptr))
4860 } while (EatIfPresent(lltok::comma));
4862 return ParseToken(lltok::rbrace, "expected end of metadata node");
4865 //===----------------------------------------------------------------------===//
4866 // Use-list order directives.
4867 //===----------------------------------------------------------------------===//
4868 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4871 return Error(Loc, "value has no uses");
4873 unsigned NumUses = 0;
4874 SmallDenseMap<const Use *, unsigned, 16> Order;
4875 for (const Use &U : V->uses()) {
4876 if (++NumUses > Indexes.size())
4878 Order[&U] = Indexes[NumUses - 1];
4881 return Error(Loc, "value only has one use");
4882 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4883 return Error(Loc, "wrong number of indexes, expected " +
4884 Twine(std::distance(V->use_begin(), V->use_end())));
4886 V->sortUseList([&](const Use &L, const Use &R) {
4887 return Order.lookup(&L) < Order.lookup(&R);
4892 /// ParseUseListOrderIndexes
4893 /// ::= '{' uint32 (',' uint32)+ '}'
4894 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4895 SMLoc Loc = Lex.getLoc();
4896 if (ParseToken(lltok::lbrace, "expected '{' here"))
4898 if (Lex.getKind() == lltok::rbrace)
4899 return Lex.Error("expected non-empty list of uselistorder indexes");
4901 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4902 // indexes should be distinct numbers in the range [0, size-1], and should
4904 unsigned Offset = 0;
4906 bool IsOrdered = true;
4907 assert(Indexes.empty() && "Expected empty order vector");
4910 if (ParseUInt32(Index))
4913 // Update consistency checks.
4914 Offset += Index - Indexes.size();
4915 Max = std::max(Max, Index);
4916 IsOrdered &= Index == Indexes.size();
4918 Indexes.push_back(Index);
4919 } while (EatIfPresent(lltok::comma));
4921 if (ParseToken(lltok::rbrace, "expected '}' here"))
4924 if (Indexes.size() < 2)
4925 return Error(Loc, "expected >= 2 uselistorder indexes");
4926 if (Offset != 0 || Max >= Indexes.size())
4927 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4929 return Error(Loc, "expected uselistorder indexes to change the order");
4934 /// ParseUseListOrder
4935 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4936 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4937 SMLoc Loc = Lex.getLoc();
4938 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4942 SmallVector<unsigned, 16> Indexes;
4943 if (ParseTypeAndValue(V, PFS) ||
4944 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4945 ParseUseListOrderIndexes(Indexes))
4948 return sortUseListOrder(V, Indexes, Loc);
4951 /// ParseUseListOrderBB
4952 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4953 bool LLParser::ParseUseListOrderBB() {
4954 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4955 SMLoc Loc = Lex.getLoc();
4959 SmallVector<unsigned, 16> Indexes;
4960 if (ParseValID(Fn) ||
4961 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4962 ParseValID(Label) ||
4963 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4964 ParseUseListOrderIndexes(Indexes))
4967 // Check the function.
4969 if (Fn.Kind == ValID::t_GlobalName)
4970 GV = M->getNamedValue(Fn.StrVal);
4971 else if (Fn.Kind == ValID::t_GlobalID)
4972 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4974 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4976 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4977 auto *F = dyn_cast<Function>(GV);
4979 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4980 if (F->isDeclaration())
4981 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4983 // Check the basic block.
4984 if (Label.Kind == ValID::t_LocalID)
4985 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4986 if (Label.Kind != ValID::t_LocalName)
4987 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4988 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4990 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4991 if (!isa<BasicBlock>(V))
4992 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4994 return sortUseListOrder(V, Indexes, Loc);