1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SaveAndRestore.h"
28 #include "llvm/Support/raw_ostream.h"
31 static std::string getTypeString(Type *T) {
33 raw_string_ostream Tmp(Result);
38 /// Run: module ::= toplevelentity*
39 bool LLParser::Run() {
43 return ParseTopLevelEntities() ||
44 ValidateEndOfModule();
47 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
49 bool LLParser::ValidateEndOfModule() {
50 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
51 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
53 // Handle any function attribute group forward references.
54 for (std::map<Value*, std::vector<unsigned> >::iterator
55 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
58 std::vector<unsigned> &Vec = I->second;
61 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
63 B.merge(NumberedAttrBuilders[*VI]);
65 if (Function *Fn = dyn_cast<Function>(V)) {
66 AttributeSet AS = Fn->getAttributes();
67 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
68 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
69 AS.getFnAttributes());
73 // If the alignment was parsed as an attribute, move to the alignment
75 if (FnAttrs.hasAlignmentAttr()) {
76 Fn->setAlignment(FnAttrs.getAlignment());
77 FnAttrs.removeAttribute(Attribute::Alignment);
80 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
81 AttributeSet::get(Context,
82 AttributeSet::FunctionIndex,
84 Fn->setAttributes(AS);
85 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
86 AttributeSet AS = CI->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
91 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
92 AttributeSet::get(Context,
93 AttributeSet::FunctionIndex,
95 CI->setAttributes(AS);
96 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
97 AttributeSet AS = II->getAttributes();
98 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
99 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
100 AS.getFnAttributes());
102 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
103 AttributeSet::get(Context,
104 AttributeSet::FunctionIndex,
106 II->setAttributes(AS);
108 llvm_unreachable("invalid object with forward attribute group reference");
112 // If there are entries in ForwardRefBlockAddresses at this point, the
113 // function was never defined.
114 if (!ForwardRefBlockAddresses.empty())
115 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
116 "expected function name in blockaddress");
118 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
119 if (NumberedTypes[i].second.isValid())
120 return Error(NumberedTypes[i].second,
121 "use of undefined type '%" + Twine(i) + "'");
123 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
124 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
125 if (I->second.second.isValid())
126 return Error(I->second.second,
127 "use of undefined type named '" + I->getKey() + "'");
129 if (!ForwardRefComdats.empty())
130 return Error(ForwardRefComdats.begin()->second,
131 "use of undefined comdat '$" +
132 ForwardRefComdats.begin()->first + "'");
134 if (!ForwardRefVals.empty())
135 return Error(ForwardRefVals.begin()->second.second,
136 "use of undefined value '@" + ForwardRefVals.begin()->first +
139 if (!ForwardRefValIDs.empty())
140 return Error(ForwardRefValIDs.begin()->second.second,
141 "use of undefined value '@" +
142 Twine(ForwardRefValIDs.begin()->first) + "'");
144 if (!ForwardRefMDNodes.empty())
145 return Error(ForwardRefMDNodes.begin()->second.second,
146 "use of undefined metadata '!" +
147 Twine(ForwardRefMDNodes.begin()->first) + "'");
149 // Resolve metadata cycles.
150 for (auto &N : NumberedMetadata)
151 if (auto *U = cast_or_null<UniquableMDNode>(N))
154 // Look for intrinsic functions and CallInst that need to be upgraded
155 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
156 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
158 UpgradeDebugInfo(*M);
163 //===----------------------------------------------------------------------===//
164 // Top-Level Entities
165 //===----------------------------------------------------------------------===//
167 bool LLParser::ParseTopLevelEntities() {
169 switch (Lex.getKind()) {
170 default: return TokError("expected top-level entity");
171 case lltok::Eof: return false;
172 case lltok::kw_declare: if (ParseDeclare()) return true; break;
173 case lltok::kw_define: if (ParseDefine()) return true; break;
174 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
175 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
176 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
177 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
178 case lltok::LocalVar: if (ParseNamedType()) return true; break;
179 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
180 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
181 case lltok::ComdatVar: if (parseComdat()) return true; break;
182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
183 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
188 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
189 // ('constant'|'global') ...
190 case lltok::kw_private: // OptionalLinkage
191 case lltok::kw_internal: // OptionalLinkage
192 case lltok::kw_weak: // OptionalLinkage
193 case lltok::kw_weak_odr: // OptionalLinkage
194 case lltok::kw_linkonce: // OptionalLinkage
195 case lltok::kw_linkonce_odr: // OptionalLinkage
196 case lltok::kw_appending: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: // OptionalLinkage
200 case lltok::kw_default: // OptionalVisibility
201 case lltok::kw_hidden: // OptionalVisibility
202 case lltok::kw_protected: // OptionalVisibility
203 case lltok::kw_dllimport: // OptionalDLLStorageClass
204 case lltok::kw_dllexport: // OptionalDLLStorageClass
205 case lltok::kw_thread_local: // OptionalThreadLocal
206 case lltok::kw_addrspace: // OptionalAddrSpace
207 case lltok::kw_constant: // GlobalType
208 case lltok::kw_global: { // GlobalType
209 unsigned Linkage, Visibility, DLLStorageClass;
211 GlobalVariable::ThreadLocalMode TLM;
213 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
214 ParseOptionalVisibility(Visibility) ||
215 ParseOptionalDLLStorageClass(DLLStorageClass) ||
216 ParseOptionalThreadLocal(TLM) ||
217 parseOptionalUnnamedAddr(UnnamedAddr) ||
218 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
219 DLLStorageClass, TLM, UnnamedAddr))
224 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
225 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
226 case lltok::kw_uselistorder_bb:
227 if (ParseUseListOrderBB()) return true; break;
234 /// ::= 'module' 'asm' STRINGCONSTANT
235 bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
243 M->appendModuleInlineAsm(AsmStr);
248 /// ::= 'target' 'triple' '=' STRINGCONSTANT
249 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250 bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
260 M->setTargetTriple(Str);
262 case lltok::kw_datalayout:
264 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
265 ParseStringConstant(Str))
267 M->setDataLayout(Str);
273 /// ::= 'deplibs' '=' '[' ']'
274 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
275 /// FIXME: Remove in 4.0. Currently parse, but ignore.
276 bool LLParser::ParseDepLibs() {
277 assert(Lex.getKind() == lltok::kw_deplibs);
279 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
280 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
283 if (EatIfPresent(lltok::rsquare))
288 if (ParseStringConstant(Str)) return true;
289 } while (EatIfPresent(lltok::comma));
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
294 /// ParseUnnamedType:
295 /// ::= LocalVarID '=' 'type' type
296 bool LLParser::ParseUnnamedType() {
297 LocTy TypeLoc = Lex.getLoc();
298 unsigned TypeID = Lex.getUIntVal();
299 Lex.Lex(); // eat LocalVarID;
301 if (ParseToken(lltok::equal, "expected '=' after name") ||
302 ParseToken(lltok::kw_type, "expected 'type' after '='"))
305 if (TypeID >= NumberedTypes.size())
306 NumberedTypes.resize(TypeID+1);
308 Type *Result = nullptr;
309 if (ParseStructDefinition(TypeLoc, "",
310 NumberedTypes[TypeID], Result)) return true;
312 if (!isa<StructType>(Result)) {
313 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315 return Error(TypeLoc, "non-struct types may not be recursive");
316 Entry.first = Result;
317 Entry.second = SMLoc();
325 /// ::= LocalVar '=' 'type' type
326 bool LLParser::ParseNamedType() {
327 std::string Name = Lex.getStrVal();
328 LocTy NameLoc = Lex.getLoc();
329 Lex.Lex(); // eat LocalVar.
331 if (ParseToken(lltok::equal, "expected '=' after name") ||
332 ParseToken(lltok::kw_type, "expected 'type' after name"))
335 Type *Result = nullptr;
336 if (ParseStructDefinition(NameLoc, Name,
337 NamedTypes[Name], Result)) return true;
339 if (!isa<StructType>(Result)) {
340 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342 return Error(NameLoc, "non-struct types may not be recursive");
343 Entry.first = Result;
344 Entry.second = SMLoc();
352 /// ::= 'declare' FunctionHeader
353 bool LLParser::ParseDeclare() {
354 assert(Lex.getKind() == lltok::kw_declare);
358 return ParseFunctionHeader(F, false);
362 /// ::= 'define' FunctionHeader '{' ...
363 bool LLParser::ParseDefine() {
364 assert(Lex.getKind() == lltok::kw_define);
368 return ParseFunctionHeader(F, true) ||
369 ParseFunctionBody(*F);
375 bool LLParser::ParseGlobalType(bool &IsConstant) {
376 if (Lex.getKind() == lltok::kw_constant)
378 else if (Lex.getKind() == lltok::kw_global)
382 return TokError("expected 'global' or 'constant'");
388 /// ParseUnnamedGlobal:
389 /// OptionalVisibility ALIAS ...
390 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
391 /// ... -> global variable
392 /// GlobalID '=' OptionalVisibility ALIAS ...
393 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
394 /// ... -> global variable
395 bool LLParser::ParseUnnamedGlobal() {
396 unsigned VarID = NumberedVals.size();
398 LocTy NameLoc = Lex.getLoc();
400 // Handle the GlobalID form.
401 if (Lex.getKind() == lltok::GlobalID) {
402 if (Lex.getUIntVal() != VarID)
403 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
405 Lex.Lex(); // eat GlobalID;
407 if (ParseToken(lltok::equal, "expected '=' after name"))
412 unsigned Linkage, Visibility, DLLStorageClass;
413 GlobalVariable::ThreadLocalMode TLM;
415 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
416 ParseOptionalVisibility(Visibility) ||
417 ParseOptionalDLLStorageClass(DLLStorageClass) ||
418 ParseOptionalThreadLocal(TLM) ||
419 parseOptionalUnnamedAddr(UnnamedAddr))
422 if (Lex.getKind() != lltok::kw_alias)
423 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
424 DLLStorageClass, TLM, UnnamedAddr);
425 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
429 /// ParseNamedGlobal:
430 /// GlobalVar '=' OptionalVisibility ALIAS ...
431 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
432 /// ... -> global variable
433 bool LLParser::ParseNamedGlobal() {
434 assert(Lex.getKind() == lltok::GlobalVar);
435 LocTy NameLoc = Lex.getLoc();
436 std::string Name = Lex.getStrVal();
440 unsigned Linkage, Visibility, DLLStorageClass;
441 GlobalVariable::ThreadLocalMode TLM;
443 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
444 ParseOptionalLinkage(Linkage, HasLinkage) ||
445 ParseOptionalVisibility(Visibility) ||
446 ParseOptionalDLLStorageClass(DLLStorageClass) ||
447 ParseOptionalThreadLocal(TLM) ||
448 parseOptionalUnnamedAddr(UnnamedAddr))
451 if (Lex.getKind() != lltok::kw_alias)
452 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
453 DLLStorageClass, TLM, UnnamedAddr);
455 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
459 bool LLParser::parseComdat() {
460 assert(Lex.getKind() == lltok::ComdatVar);
461 std::string Name = Lex.getStrVal();
462 LocTy NameLoc = Lex.getLoc();
465 if (ParseToken(lltok::equal, "expected '=' here"))
468 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
469 return TokError("expected comdat type");
471 Comdat::SelectionKind SK;
472 switch (Lex.getKind()) {
474 return TokError("unknown selection kind");
478 case lltok::kw_exactmatch:
479 SK = Comdat::ExactMatch;
481 case lltok::kw_largest:
482 SK = Comdat::Largest;
484 case lltok::kw_noduplicates:
485 SK = Comdat::NoDuplicates;
487 case lltok::kw_samesize:
488 SK = Comdat::SameSize;
493 // See if the comdat was forward referenced, if so, use the comdat.
494 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
495 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
496 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
497 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
500 if (I != ComdatSymTab.end())
503 C = M->getOrInsertComdat(Name);
504 C->setSelectionKind(SK);
510 // ::= '!' STRINGCONSTANT
511 bool LLParser::ParseMDString(MDString *&Result) {
513 if (ParseStringConstant(Str)) return true;
514 llvm::UpgradeMDStringConstant(Str);
515 Result = MDString::get(Context, Str);
520 // ::= '!' MDNodeNumber
521 bool LLParser::ParseMDNodeID(MDNode *&Result) {
522 // !{ ..., !42, ... }
524 if (ParseUInt32(MID))
527 // If not a forward reference, just return it now.
528 if (MID < NumberedMetadata.size() && NumberedMetadata[MID] != nullptr) {
529 Result = NumberedMetadata[MID];
533 // Otherwise, create MDNode forward reference.
534 auto &FwdRef = ForwardRefMDNodes[MID];
535 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
537 if (NumberedMetadata.size() <= MID)
538 NumberedMetadata.resize(MID+1);
539 Result = FwdRef.first.get();
540 NumberedMetadata[MID].reset(Result);
544 /// ParseNamedMetadata:
545 /// !foo = !{ !1, !2 }
546 bool LLParser::ParseNamedMetadata() {
547 assert(Lex.getKind() == lltok::MetadataVar);
548 std::string Name = Lex.getStrVal();
551 if (ParseToken(lltok::equal, "expected '=' here") ||
552 ParseToken(lltok::exclaim, "Expected '!' here") ||
553 ParseToken(lltok::lbrace, "Expected '{' here"))
556 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
557 if (Lex.getKind() != lltok::rbrace)
559 if (ParseToken(lltok::exclaim, "Expected '!' here"))
563 if (ParseMDNodeID(N)) return true;
565 } while (EatIfPresent(lltok::comma));
567 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
573 /// ParseStandaloneMetadata:
575 bool LLParser::ParseStandaloneMetadata() {
576 assert(Lex.getKind() == lltok::exclaim);
578 unsigned MetadataID = 0;
581 if (ParseUInt32(MetadataID) ||
582 ParseToken(lltok::equal, "expected '=' here"))
585 // Detect common error, from old metadata syntax.
586 if (Lex.getKind() == lltok::Type)
587 return TokError("unexpected type in metadata definition");
589 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
590 if (Lex.getKind() == lltok::MetadataVar) {
591 if (ParseSpecializedMDNode(Init, IsDistinct))
593 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
594 ParseMDTuple(Init, IsDistinct))
597 // See if this was forward referenced, if so, handle it.
598 auto FI = ForwardRefMDNodes.find(MetadataID);
599 if (FI != ForwardRefMDNodes.end()) {
600 FI->second.first->replaceAllUsesWith(Init);
601 ForwardRefMDNodes.erase(FI);
603 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
605 if (MetadataID >= NumberedMetadata.size())
606 NumberedMetadata.resize(MetadataID+1);
608 if (NumberedMetadata[MetadataID] != nullptr)
609 return TokError("Metadata id is already used");
610 NumberedMetadata[MetadataID].reset(Init);
616 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
617 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
618 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
622 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
623 /// OptionalDLLStorageClass OptionalThreadLocal
624 /// OptionalUnNammedAddr 'alias' Aliasee
629 /// Everything through OptionalUnNammedAddr has already been parsed.
631 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
632 unsigned Visibility, unsigned DLLStorageClass,
633 GlobalVariable::ThreadLocalMode TLM,
635 assert(Lex.getKind() == lltok::kw_alias);
638 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
640 if(!GlobalAlias::isValidLinkage(Linkage))
641 return Error(NameLoc, "invalid linkage type for alias");
643 if (!isValidVisibilityForLinkage(Visibility, L))
644 return Error(NameLoc,
645 "symbol with local linkage must have default visibility");
648 LocTy AliaseeLoc = Lex.getLoc();
649 if (Lex.getKind() != lltok::kw_bitcast &&
650 Lex.getKind() != lltok::kw_getelementptr &&
651 Lex.getKind() != lltok::kw_addrspacecast &&
652 Lex.getKind() != lltok::kw_inttoptr) {
653 if (ParseGlobalTypeAndValue(Aliasee))
656 // The bitcast dest type is not present, it is implied by the dest type.
660 if (ID.Kind != ValID::t_Constant)
661 return Error(AliaseeLoc, "invalid aliasee");
662 Aliasee = ID.ConstantVal;
665 Type *AliaseeType = Aliasee->getType();
666 auto *PTy = dyn_cast<PointerType>(AliaseeType);
668 return Error(AliaseeLoc, "An alias must have pointer type");
669 Type *Ty = PTy->getElementType();
670 unsigned AddrSpace = PTy->getAddressSpace();
672 // Okay, create the alias but do not insert it into the module yet.
673 std::unique_ptr<GlobalAlias> GA(
674 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
675 Name, Aliasee, /*Parent*/ nullptr));
676 GA->setThreadLocalMode(TLM);
677 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
678 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
679 GA->setUnnamedAddr(UnnamedAddr);
681 // See if this value already exists in the symbol table. If so, it is either
682 // a redefinition or a definition of a forward reference.
683 if (GlobalValue *Val = M->getNamedValue(Name)) {
684 // See if this was a redefinition. If so, there is no entry in
686 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefVals.find(Name);
688 if (I == ForwardRefVals.end())
689 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
691 // Otherwise, this was a definition of forward ref. Verify that types
693 if (Val->getType() != GA->getType())
694 return Error(NameLoc,
695 "forward reference and definition of alias have different types");
697 // If they agree, just RAUW the old value with the alias and remove the
699 Val->replaceAllUsesWith(GA.get());
700 Val->eraseFromParent();
701 ForwardRefVals.erase(I);
704 // Insert into the module, we know its name won't collide now.
705 M->getAliasList().push_back(GA.get());
706 assert(GA->getName() == Name && "Should not be a name conflict!");
708 // The module owns this now
715 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
716 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
717 /// OptionalExternallyInitialized GlobalType Type Const
718 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
719 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
720 /// OptionalExternallyInitialized GlobalType Type Const
722 /// Everything up to and including OptionalUnNammedAddr has been parsed
725 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
726 unsigned Linkage, bool HasLinkage,
727 unsigned Visibility, unsigned DLLStorageClass,
728 GlobalVariable::ThreadLocalMode TLM,
730 if (!isValidVisibilityForLinkage(Visibility, Linkage))
731 return Error(NameLoc,
732 "symbol with local linkage must have default visibility");
735 bool IsConstant, IsExternallyInitialized;
736 LocTy IsExternallyInitializedLoc;
740 if (ParseOptionalAddrSpace(AddrSpace) ||
741 ParseOptionalToken(lltok::kw_externally_initialized,
742 IsExternallyInitialized,
743 &IsExternallyInitializedLoc) ||
744 ParseGlobalType(IsConstant) ||
745 ParseType(Ty, TyLoc))
748 // If the linkage is specified and is external, then no initializer is
750 Constant *Init = nullptr;
751 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
752 Linkage != GlobalValue::ExternalLinkage)) {
753 if (ParseGlobalValue(Ty, Init))
757 if (Ty->isFunctionTy() || Ty->isLabelTy())
758 return Error(TyLoc, "invalid type for global variable");
760 GlobalValue *GVal = nullptr;
762 // See if the global was forward referenced, if so, use the global.
764 GVal = M->getNamedValue(Name);
766 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
767 return Error(NameLoc, "redefinition of global '@" + Name + "'");
770 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
771 I = ForwardRefValIDs.find(NumberedVals.size());
772 if (I != ForwardRefValIDs.end()) {
773 GVal = I->second.first;
774 ForwardRefValIDs.erase(I);
780 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
781 Name, nullptr, GlobalVariable::NotThreadLocal,
784 if (GVal->getType()->getElementType() != Ty)
786 "forward reference and definition of global have different types");
788 GV = cast<GlobalVariable>(GVal);
790 // Move the forward-reference to the correct spot in the module.
791 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
795 NumberedVals.push_back(GV);
797 // Set the parsed properties on the global.
799 GV->setInitializer(Init);
800 GV->setConstant(IsConstant);
801 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
802 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
803 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
804 GV->setExternallyInitialized(IsExternallyInitialized);
805 GV->setThreadLocalMode(TLM);
806 GV->setUnnamedAddr(UnnamedAddr);
808 // Parse attributes on the global.
809 while (Lex.getKind() == lltok::comma) {
812 if (Lex.getKind() == lltok::kw_section) {
814 GV->setSection(Lex.getStrVal());
815 if (ParseToken(lltok::StringConstant, "expected global section string"))
817 } else if (Lex.getKind() == lltok::kw_align) {
819 if (ParseOptionalAlignment(Alignment)) return true;
820 GV->setAlignment(Alignment);
823 if (parseOptionalComdat(Name, C))
828 return TokError("unknown global variable property!");
835 /// ParseUnnamedAttrGrp
836 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
837 bool LLParser::ParseUnnamedAttrGrp() {
838 assert(Lex.getKind() == lltok::kw_attributes);
839 LocTy AttrGrpLoc = Lex.getLoc();
842 if (Lex.getKind() != lltok::AttrGrpID)
843 return TokError("expected attribute group id");
845 unsigned VarID = Lex.getUIntVal();
846 std::vector<unsigned> unused;
850 if (ParseToken(lltok::equal, "expected '=' here") ||
851 ParseToken(lltok::lbrace, "expected '{' here") ||
852 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
854 ParseToken(lltok::rbrace, "expected end of attribute group"))
857 if (!NumberedAttrBuilders[VarID].hasAttributes())
858 return Error(AttrGrpLoc, "attribute group has no attributes");
863 /// ParseFnAttributeValuePairs
864 /// ::= <attr> | <attr> '=' <value>
865 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
866 std::vector<unsigned> &FwdRefAttrGrps,
867 bool inAttrGrp, LocTy &BuiltinLoc) {
868 bool HaveError = false;
873 lltok::Kind Token = Lex.getKind();
874 if (Token == lltok::kw_builtin)
875 BuiltinLoc = Lex.getLoc();
878 if (!inAttrGrp) return HaveError;
879 return Error(Lex.getLoc(), "unterminated attribute group");
884 case lltok::AttrGrpID: {
885 // Allow a function to reference an attribute group:
887 // define void @foo() #1 { ... }
891 "cannot have an attribute group reference in an attribute group");
893 unsigned AttrGrpNum = Lex.getUIntVal();
894 if (inAttrGrp) break;
896 // Save the reference to the attribute group. We'll fill it in later.
897 FwdRefAttrGrps.push_back(AttrGrpNum);
900 // Target-dependent attributes:
901 case lltok::StringConstant: {
902 std::string Attr = Lex.getStrVal();
905 if (EatIfPresent(lltok::equal) &&
906 ParseStringConstant(Val))
909 B.addAttribute(Attr, Val);
913 // Target-independent attributes:
914 case lltok::kw_align: {
915 // As a hack, we allow function alignment to be initially parsed as an
916 // attribute on a function declaration/definition or added to an attribute
917 // group and later moved to the alignment field.
921 if (ParseToken(lltok::equal, "expected '=' here") ||
922 ParseUInt32(Alignment))
925 if (ParseOptionalAlignment(Alignment))
928 B.addAlignmentAttr(Alignment);
931 case lltok::kw_alignstack: {
935 if (ParseToken(lltok::equal, "expected '=' here") ||
936 ParseUInt32(Alignment))
939 if (ParseOptionalStackAlignment(Alignment))
942 B.addStackAlignmentAttr(Alignment);
945 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
946 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
947 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
948 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
949 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
950 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
951 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
952 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
953 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
954 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
955 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
956 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
957 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
958 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
959 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
960 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
961 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
962 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
963 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
964 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
965 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
966 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
967 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
968 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
969 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
970 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
971 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
974 case lltok::kw_inreg:
975 case lltok::kw_signext:
976 case lltok::kw_zeroext:
979 "invalid use of attribute on a function");
981 case lltok::kw_byval:
982 case lltok::kw_dereferenceable:
983 case lltok::kw_inalloca:
985 case lltok::kw_noalias:
986 case lltok::kw_nocapture:
987 case lltok::kw_nonnull:
988 case lltok::kw_returned:
992 "invalid use of parameter-only attribute on a function");
1000 //===----------------------------------------------------------------------===//
1001 // GlobalValue Reference/Resolution Routines.
1002 //===----------------------------------------------------------------------===//
1004 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1005 /// forward reference record if needed. This can return null if the value
1006 /// exists but does not have the right type.
1007 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1009 PointerType *PTy = dyn_cast<PointerType>(Ty);
1011 Error(Loc, "global variable reference must have pointer type");
1015 // Look this name up in the normal function symbol table.
1017 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1019 // If this is a forward reference for the value, see if we already created a
1020 // forward ref record.
1022 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1023 I = ForwardRefVals.find(Name);
1024 if (I != ForwardRefVals.end())
1025 Val = I->second.first;
1028 // If we have the value in the symbol table or fwd-ref table, return it.
1030 if (Val->getType() == Ty) return Val;
1031 Error(Loc, "'@" + Name + "' defined with type '" +
1032 getTypeString(Val->getType()) + "'");
1036 // Otherwise, create a new forward reference for this value and remember it.
1037 GlobalValue *FwdVal;
1038 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1039 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1041 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1042 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1043 nullptr, GlobalVariable::NotThreadLocal,
1044 PTy->getAddressSpace());
1046 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1050 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1051 PointerType *PTy = dyn_cast<PointerType>(Ty);
1053 Error(Loc, "global variable reference must have pointer type");
1057 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1059 // If this is a forward reference for the value, see if we already created a
1060 // forward ref record.
1062 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1063 I = ForwardRefValIDs.find(ID);
1064 if (I != ForwardRefValIDs.end())
1065 Val = I->second.first;
1068 // If we have the value in the symbol table or fwd-ref table, return it.
1070 if (Val->getType() == Ty) return Val;
1071 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1072 getTypeString(Val->getType()) + "'");
1076 // Otherwise, create a new forward reference for this value and remember it.
1077 GlobalValue *FwdVal;
1078 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1079 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1081 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1082 GlobalValue::ExternalWeakLinkage, nullptr, "");
1084 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1089 //===----------------------------------------------------------------------===//
1090 // Comdat Reference/Resolution Routines.
1091 //===----------------------------------------------------------------------===//
1093 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1094 // Look this name up in the comdat symbol table.
1095 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1096 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1097 if (I != ComdatSymTab.end())
1100 // Otherwise, create a new forward reference for this value and remember it.
1101 Comdat *C = M->getOrInsertComdat(Name);
1102 ForwardRefComdats[Name] = Loc;
1107 //===----------------------------------------------------------------------===//
1109 //===----------------------------------------------------------------------===//
1111 /// ParseToken - If the current token has the specified kind, eat it and return
1112 /// success. Otherwise, emit the specified error and return failure.
1113 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1114 if (Lex.getKind() != T)
1115 return TokError(ErrMsg);
1120 /// ParseStringConstant
1121 /// ::= StringConstant
1122 bool LLParser::ParseStringConstant(std::string &Result) {
1123 if (Lex.getKind() != lltok::StringConstant)
1124 return TokError("expected string constant");
1125 Result = Lex.getStrVal();
1132 bool LLParser::ParseUInt32(unsigned &Val) {
1133 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1134 return TokError("expected integer");
1135 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1136 if (Val64 != unsigned(Val64))
1137 return TokError("expected 32-bit integer (too large)");
1145 bool LLParser::ParseUInt64(uint64_t &Val) {
1146 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1147 return TokError("expected integer");
1148 Val = Lex.getAPSIntVal().getLimitedValue();
1154 /// := 'localdynamic'
1155 /// := 'initialexec'
1157 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1158 switch (Lex.getKind()) {
1160 return TokError("expected localdynamic, initialexec or localexec");
1161 case lltok::kw_localdynamic:
1162 TLM = GlobalVariable::LocalDynamicTLSModel;
1164 case lltok::kw_initialexec:
1165 TLM = GlobalVariable::InitialExecTLSModel;
1167 case lltok::kw_localexec:
1168 TLM = GlobalVariable::LocalExecTLSModel;
1176 /// ParseOptionalThreadLocal
1178 /// := 'thread_local'
1179 /// := 'thread_local' '(' tlsmodel ')'
1180 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1181 TLM = GlobalVariable::NotThreadLocal;
1182 if (!EatIfPresent(lltok::kw_thread_local))
1185 TLM = GlobalVariable::GeneralDynamicTLSModel;
1186 if (Lex.getKind() == lltok::lparen) {
1188 return ParseTLSModel(TLM) ||
1189 ParseToken(lltok::rparen, "expected ')' after thread local model");
1194 /// ParseOptionalAddrSpace
1196 /// := 'addrspace' '(' uint32 ')'
1197 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1199 if (!EatIfPresent(lltok::kw_addrspace))
1201 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1202 ParseUInt32(AddrSpace) ||
1203 ParseToken(lltok::rparen, "expected ')' in address space");
1206 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1207 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1208 bool HaveError = false;
1213 lltok::Kind Token = Lex.getKind();
1215 default: // End of attributes.
1217 case lltok::kw_align: {
1219 if (ParseOptionalAlignment(Alignment))
1221 B.addAlignmentAttr(Alignment);
1224 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1225 case lltok::kw_dereferenceable: {
1227 if (ParseOptionalDereferenceableBytes(Bytes))
1229 B.addDereferenceableAttr(Bytes);
1232 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1233 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1234 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1235 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1236 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1237 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1238 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1239 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1240 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1241 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1242 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1243 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1245 case lltok::kw_alignstack:
1246 case lltok::kw_alwaysinline:
1247 case lltok::kw_builtin:
1248 case lltok::kw_inlinehint:
1249 case lltok::kw_jumptable:
1250 case lltok::kw_minsize:
1251 case lltok::kw_naked:
1252 case lltok::kw_nobuiltin:
1253 case lltok::kw_noduplicate:
1254 case lltok::kw_noimplicitfloat:
1255 case lltok::kw_noinline:
1256 case lltok::kw_nonlazybind:
1257 case lltok::kw_noredzone:
1258 case lltok::kw_noreturn:
1259 case lltok::kw_nounwind:
1260 case lltok::kw_optnone:
1261 case lltok::kw_optsize:
1262 case lltok::kw_returns_twice:
1263 case lltok::kw_sanitize_address:
1264 case lltok::kw_sanitize_memory:
1265 case lltok::kw_sanitize_thread:
1267 case lltok::kw_sspreq:
1268 case lltok::kw_sspstrong:
1269 case lltok::kw_uwtable:
1270 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1278 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1279 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1280 bool HaveError = false;
1285 lltok::Kind Token = Lex.getKind();
1287 default: // End of attributes.
1289 case lltok::kw_dereferenceable: {
1291 if (ParseOptionalDereferenceableBytes(Bytes))
1293 B.addDereferenceableAttr(Bytes);
1296 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1297 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1298 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1299 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1300 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1303 case lltok::kw_align:
1304 case lltok::kw_byval:
1305 case lltok::kw_inalloca:
1306 case lltok::kw_nest:
1307 case lltok::kw_nocapture:
1308 case lltok::kw_returned:
1309 case lltok::kw_sret:
1310 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1313 case lltok::kw_alignstack:
1314 case lltok::kw_alwaysinline:
1315 case lltok::kw_builtin:
1316 case lltok::kw_cold:
1317 case lltok::kw_inlinehint:
1318 case lltok::kw_jumptable:
1319 case lltok::kw_minsize:
1320 case lltok::kw_naked:
1321 case lltok::kw_nobuiltin:
1322 case lltok::kw_noduplicate:
1323 case lltok::kw_noimplicitfloat:
1324 case lltok::kw_noinline:
1325 case lltok::kw_nonlazybind:
1326 case lltok::kw_noredzone:
1327 case lltok::kw_noreturn:
1328 case lltok::kw_nounwind:
1329 case lltok::kw_optnone:
1330 case lltok::kw_optsize:
1331 case lltok::kw_returns_twice:
1332 case lltok::kw_sanitize_address:
1333 case lltok::kw_sanitize_memory:
1334 case lltok::kw_sanitize_thread:
1336 case lltok::kw_sspreq:
1337 case lltok::kw_sspstrong:
1338 case lltok::kw_uwtable:
1339 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1342 case lltok::kw_readnone:
1343 case lltok::kw_readonly:
1344 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1351 /// ParseOptionalLinkage
1358 /// ::= 'linkonce_odr'
1359 /// ::= 'available_externally'
1362 /// ::= 'extern_weak'
1364 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1366 switch (Lex.getKind()) {
1367 default: Res=GlobalValue::ExternalLinkage; return false;
1368 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1369 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1370 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1371 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1372 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1373 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1374 case lltok::kw_available_externally:
1375 Res = GlobalValue::AvailableExternallyLinkage;
1377 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1378 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1379 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1380 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1387 /// ParseOptionalVisibility
1393 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1394 switch (Lex.getKind()) {
1395 default: Res = GlobalValue::DefaultVisibility; return false;
1396 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1397 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1398 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1404 /// ParseOptionalDLLStorageClass
1409 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1410 switch (Lex.getKind()) {
1411 default: Res = GlobalValue::DefaultStorageClass; return false;
1412 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1413 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1419 /// ParseOptionalCallingConv
1423 /// ::= 'intel_ocl_bicc'
1425 /// ::= 'x86_stdcallcc'
1426 /// ::= 'x86_fastcallcc'
1427 /// ::= 'x86_thiscallcc'
1428 /// ::= 'x86_vectorcallcc'
1429 /// ::= 'arm_apcscc'
1430 /// ::= 'arm_aapcscc'
1431 /// ::= 'arm_aapcs_vfpcc'
1432 /// ::= 'msp430_intrcc'
1433 /// ::= 'ptx_kernel'
1434 /// ::= 'ptx_device'
1436 /// ::= 'spir_kernel'
1437 /// ::= 'x86_64_sysvcc'
1438 /// ::= 'x86_64_win64cc'
1439 /// ::= 'webkit_jscc'
1441 /// ::= 'preserve_mostcc'
1442 /// ::= 'preserve_allcc'
1446 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1447 switch (Lex.getKind()) {
1448 default: CC = CallingConv::C; return false;
1449 case lltok::kw_ccc: CC = CallingConv::C; break;
1450 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1451 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1452 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1453 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1454 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1455 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1456 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1457 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1458 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1459 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1460 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1461 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1462 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1463 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1464 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1465 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1466 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1467 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1468 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1469 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1470 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1471 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1472 case lltok::kw_cc: {
1474 return ParseUInt32(CC);
1482 /// ParseInstructionMetadata
1483 /// ::= !dbg !42 (',' !dbg !57)*
1484 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1485 PerFunctionState *PFS) {
1487 if (Lex.getKind() != lltok::MetadataVar)
1488 return TokError("expected metadata after comma");
1490 std::string Name = Lex.getStrVal();
1491 unsigned MDK = M->getMDKindID(Name);
1498 Inst->setMetadata(MDK, N);
1499 if (MDK == LLVMContext::MD_tbaa)
1500 InstsWithTBAATag.push_back(Inst);
1502 // If this is the end of the list, we're done.
1503 } while (EatIfPresent(lltok::comma));
1507 /// ParseOptionalAlignment
1510 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1512 if (!EatIfPresent(lltok::kw_align))
1514 LocTy AlignLoc = Lex.getLoc();
1515 if (ParseUInt32(Alignment)) return true;
1516 if (!isPowerOf2_32(Alignment))
1517 return Error(AlignLoc, "alignment is not a power of two");
1518 if (Alignment > Value::MaximumAlignment)
1519 return Error(AlignLoc, "huge alignments are not supported yet");
1523 /// ParseOptionalDereferenceableBytes
1525 /// ::= 'dereferenceable' '(' 4 ')'
1526 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1528 if (!EatIfPresent(lltok::kw_dereferenceable))
1530 LocTy ParenLoc = Lex.getLoc();
1531 if (!EatIfPresent(lltok::lparen))
1532 return Error(ParenLoc, "expected '('");
1533 LocTy DerefLoc = Lex.getLoc();
1534 if (ParseUInt64(Bytes)) return true;
1535 ParenLoc = Lex.getLoc();
1536 if (!EatIfPresent(lltok::rparen))
1537 return Error(ParenLoc, "expected ')'");
1539 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1543 /// ParseOptionalCommaAlign
1547 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1549 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1550 bool &AteExtraComma) {
1551 AteExtraComma = false;
1552 while (EatIfPresent(lltok::comma)) {
1553 // Metadata at the end is an early exit.
1554 if (Lex.getKind() == lltok::MetadataVar) {
1555 AteExtraComma = true;
1559 if (Lex.getKind() != lltok::kw_align)
1560 return Error(Lex.getLoc(), "expected metadata or 'align'");
1562 if (ParseOptionalAlignment(Alignment)) return true;
1568 /// ParseScopeAndOrdering
1569 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1572 /// This sets Scope and Ordering to the parsed values.
1573 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1574 AtomicOrdering &Ordering) {
1578 Scope = CrossThread;
1579 if (EatIfPresent(lltok::kw_singlethread))
1580 Scope = SingleThread;
1582 return ParseOrdering(Ordering);
1586 /// ::= AtomicOrdering
1588 /// This sets Ordering to the parsed value.
1589 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1590 switch (Lex.getKind()) {
1591 default: return TokError("Expected ordering on atomic instruction");
1592 case lltok::kw_unordered: Ordering = Unordered; break;
1593 case lltok::kw_monotonic: Ordering = Monotonic; break;
1594 case lltok::kw_acquire: Ordering = Acquire; break;
1595 case lltok::kw_release: Ordering = Release; break;
1596 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1597 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1603 /// ParseOptionalStackAlignment
1605 /// ::= 'alignstack' '(' 4 ')'
1606 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1608 if (!EatIfPresent(lltok::kw_alignstack))
1610 LocTy ParenLoc = Lex.getLoc();
1611 if (!EatIfPresent(lltok::lparen))
1612 return Error(ParenLoc, "expected '('");
1613 LocTy AlignLoc = Lex.getLoc();
1614 if (ParseUInt32(Alignment)) return true;
1615 ParenLoc = Lex.getLoc();
1616 if (!EatIfPresent(lltok::rparen))
1617 return Error(ParenLoc, "expected ')'");
1618 if (!isPowerOf2_32(Alignment))
1619 return Error(AlignLoc, "stack alignment is not a power of two");
1623 /// ParseIndexList - This parses the index list for an insert/extractvalue
1624 /// instruction. This sets AteExtraComma in the case where we eat an extra
1625 /// comma at the end of the line and find that it is followed by metadata.
1626 /// Clients that don't allow metadata can call the version of this function that
1627 /// only takes one argument.
1630 /// ::= (',' uint32)+
1632 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1633 bool &AteExtraComma) {
1634 AteExtraComma = false;
1636 if (Lex.getKind() != lltok::comma)
1637 return TokError("expected ',' as start of index list");
1639 while (EatIfPresent(lltok::comma)) {
1640 if (Lex.getKind() == lltok::MetadataVar) {
1641 AteExtraComma = true;
1645 if (ParseUInt32(Idx)) return true;
1646 Indices.push_back(Idx);
1652 //===----------------------------------------------------------------------===//
1654 //===----------------------------------------------------------------------===//
1656 /// ParseType - Parse a type.
1657 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1658 SMLoc TypeLoc = Lex.getLoc();
1659 switch (Lex.getKind()) {
1661 return TokError(Msg);
1663 // Type ::= 'float' | 'void' (etc)
1664 Result = Lex.getTyVal();
1668 // Type ::= StructType
1669 if (ParseAnonStructType(Result, false))
1672 case lltok::lsquare:
1673 // Type ::= '[' ... ']'
1674 Lex.Lex(); // eat the lsquare.
1675 if (ParseArrayVectorType(Result, false))
1678 case lltok::less: // Either vector or packed struct.
1679 // Type ::= '<' ... '>'
1681 if (Lex.getKind() == lltok::lbrace) {
1682 if (ParseAnonStructType(Result, true) ||
1683 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1685 } else if (ParseArrayVectorType(Result, true))
1688 case lltok::LocalVar: {
1690 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1692 // If the type hasn't been defined yet, create a forward definition and
1693 // remember where that forward def'n was seen (in case it never is defined).
1695 Entry.first = StructType::create(Context, Lex.getStrVal());
1696 Entry.second = Lex.getLoc();
1698 Result = Entry.first;
1703 case lltok::LocalVarID: {
1705 if (Lex.getUIntVal() >= NumberedTypes.size())
1706 NumberedTypes.resize(Lex.getUIntVal()+1);
1707 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1709 // If the type hasn't been defined yet, create a forward definition and
1710 // remember where that forward def'n was seen (in case it never is defined).
1712 Entry.first = StructType::create(Context);
1713 Entry.second = Lex.getLoc();
1715 Result = Entry.first;
1721 // Parse the type suffixes.
1723 switch (Lex.getKind()) {
1726 if (!AllowVoid && Result->isVoidTy())
1727 return Error(TypeLoc, "void type only allowed for function results");
1730 // Type ::= Type '*'
1732 if (Result->isLabelTy())
1733 return TokError("basic block pointers are invalid");
1734 if (Result->isVoidTy())
1735 return TokError("pointers to void are invalid - use i8* instead");
1736 if (!PointerType::isValidElementType(Result))
1737 return TokError("pointer to this type is invalid");
1738 Result = PointerType::getUnqual(Result);
1742 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1743 case lltok::kw_addrspace: {
1744 if (Result->isLabelTy())
1745 return TokError("basic block pointers are invalid");
1746 if (Result->isVoidTy())
1747 return TokError("pointers to void are invalid; use i8* instead");
1748 if (!PointerType::isValidElementType(Result))
1749 return TokError("pointer to this type is invalid");
1751 if (ParseOptionalAddrSpace(AddrSpace) ||
1752 ParseToken(lltok::star, "expected '*' in address space"))
1755 Result = PointerType::get(Result, AddrSpace);
1759 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1761 if (ParseFunctionType(Result))
1768 /// ParseParameterList
1770 /// ::= '(' Arg (',' Arg)* ')'
1772 /// ::= Type OptionalAttributes Value OptionalAttributes
1773 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1774 PerFunctionState &PFS, bool IsMustTailCall,
1775 bool InVarArgsFunc) {
1776 if (ParseToken(lltok::lparen, "expected '(' in call"))
1779 unsigned AttrIndex = 1;
1780 while (Lex.getKind() != lltok::rparen) {
1781 // If this isn't the first argument, we need a comma.
1782 if (!ArgList.empty() &&
1783 ParseToken(lltok::comma, "expected ',' in argument list"))
1786 // Parse an ellipsis if this is a musttail call in a variadic function.
1787 if (Lex.getKind() == lltok::dotdotdot) {
1788 const char *Msg = "unexpected ellipsis in argument list for ";
1789 if (!IsMustTailCall)
1790 return TokError(Twine(Msg) + "non-musttail call");
1792 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1793 Lex.Lex(); // Lex the '...', it is purely for readability.
1794 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1797 // Parse the argument.
1799 Type *ArgTy = nullptr;
1800 AttrBuilder ArgAttrs;
1802 if (ParseType(ArgTy, ArgLoc))
1805 if (ArgTy->isMetadataTy()) {
1806 if (ParseMetadataAsValue(V, PFS))
1809 // Otherwise, handle normal operands.
1810 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1813 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1818 if (IsMustTailCall && InVarArgsFunc)
1819 return TokError("expected '...' at end of argument list for musttail call "
1820 "in varargs function");
1822 Lex.Lex(); // Lex the ')'.
1828 /// ParseArgumentList - Parse the argument list for a function type or function
1830 /// ::= '(' ArgTypeListI ')'
1834 /// ::= ArgTypeList ',' '...'
1835 /// ::= ArgType (',' ArgType)*
1837 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1840 assert(Lex.getKind() == lltok::lparen);
1841 Lex.Lex(); // eat the (.
1843 if (Lex.getKind() == lltok::rparen) {
1845 } else if (Lex.getKind() == lltok::dotdotdot) {
1849 LocTy TypeLoc = Lex.getLoc();
1850 Type *ArgTy = nullptr;
1854 if (ParseType(ArgTy) ||
1855 ParseOptionalParamAttrs(Attrs)) return true;
1857 if (ArgTy->isVoidTy())
1858 return Error(TypeLoc, "argument can not have void type");
1860 if (Lex.getKind() == lltok::LocalVar) {
1861 Name = Lex.getStrVal();
1865 if (!FunctionType::isValidArgumentType(ArgTy))
1866 return Error(TypeLoc, "invalid type for function argument");
1868 unsigned AttrIndex = 1;
1869 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1870 AttributeSet::get(ArgTy->getContext(),
1871 AttrIndex++, Attrs), Name));
1873 while (EatIfPresent(lltok::comma)) {
1874 // Handle ... at end of arg list.
1875 if (EatIfPresent(lltok::dotdotdot)) {
1880 // Otherwise must be an argument type.
1881 TypeLoc = Lex.getLoc();
1882 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1884 if (ArgTy->isVoidTy())
1885 return Error(TypeLoc, "argument can not have void type");
1887 if (Lex.getKind() == lltok::LocalVar) {
1888 Name = Lex.getStrVal();
1894 if (!ArgTy->isFirstClassType())
1895 return Error(TypeLoc, "invalid type for function argument");
1897 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1898 AttributeSet::get(ArgTy->getContext(),
1899 AttrIndex++, Attrs),
1904 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1907 /// ParseFunctionType
1908 /// ::= Type ArgumentList OptionalAttrs
1909 bool LLParser::ParseFunctionType(Type *&Result) {
1910 assert(Lex.getKind() == lltok::lparen);
1912 if (!FunctionType::isValidReturnType(Result))
1913 return TokError("invalid function return type");
1915 SmallVector<ArgInfo, 8> ArgList;
1917 if (ParseArgumentList(ArgList, isVarArg))
1920 // Reject names on the arguments lists.
1921 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1922 if (!ArgList[i].Name.empty())
1923 return Error(ArgList[i].Loc, "argument name invalid in function type");
1924 if (ArgList[i].Attrs.hasAttributes(i + 1))
1925 return Error(ArgList[i].Loc,
1926 "argument attributes invalid in function type");
1929 SmallVector<Type*, 16> ArgListTy;
1930 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1931 ArgListTy.push_back(ArgList[i].Ty);
1933 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1937 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1939 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1940 SmallVector<Type*, 8> Elts;
1941 if (ParseStructBody(Elts)) return true;
1943 Result = StructType::get(Context, Elts, Packed);
1947 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1948 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1949 std::pair<Type*, LocTy> &Entry,
1951 // If the type was already defined, diagnose the redefinition.
1952 if (Entry.first && !Entry.second.isValid())
1953 return Error(TypeLoc, "redefinition of type");
1955 // If we have opaque, just return without filling in the definition for the
1956 // struct. This counts as a definition as far as the .ll file goes.
1957 if (EatIfPresent(lltok::kw_opaque)) {
1958 // This type is being defined, so clear the location to indicate this.
1959 Entry.second = SMLoc();
1961 // If this type number has never been uttered, create it.
1963 Entry.first = StructType::create(Context, Name);
1964 ResultTy = Entry.first;
1968 // If the type starts with '<', then it is either a packed struct or a vector.
1969 bool isPacked = EatIfPresent(lltok::less);
1971 // If we don't have a struct, then we have a random type alias, which we
1972 // accept for compatibility with old files. These types are not allowed to be
1973 // forward referenced and not allowed to be recursive.
1974 if (Lex.getKind() != lltok::lbrace) {
1976 return Error(TypeLoc, "forward references to non-struct type");
1980 return ParseArrayVectorType(ResultTy, true);
1981 return ParseType(ResultTy);
1984 // This type is being defined, so clear the location to indicate this.
1985 Entry.second = SMLoc();
1987 // If this type number has never been uttered, create it.
1989 Entry.first = StructType::create(Context, Name);
1991 StructType *STy = cast<StructType>(Entry.first);
1993 SmallVector<Type*, 8> Body;
1994 if (ParseStructBody(Body) ||
1995 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1998 STy->setBody(Body, isPacked);
2004 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2007 /// ::= '{' Type (',' Type)* '}'
2008 /// ::= '<' '{' '}' '>'
2009 /// ::= '<' '{' Type (',' Type)* '}' '>'
2010 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2011 assert(Lex.getKind() == lltok::lbrace);
2012 Lex.Lex(); // Consume the '{'
2014 // Handle the empty struct.
2015 if (EatIfPresent(lltok::rbrace))
2018 LocTy EltTyLoc = Lex.getLoc();
2020 if (ParseType(Ty)) return true;
2023 if (!StructType::isValidElementType(Ty))
2024 return Error(EltTyLoc, "invalid element type for struct");
2026 while (EatIfPresent(lltok::comma)) {
2027 EltTyLoc = Lex.getLoc();
2028 if (ParseType(Ty)) return true;
2030 if (!StructType::isValidElementType(Ty))
2031 return Error(EltTyLoc, "invalid element type for struct");
2036 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2039 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2040 /// token has already been consumed.
2042 /// ::= '[' APSINTVAL 'x' Types ']'
2043 /// ::= '<' APSINTVAL 'x' Types '>'
2044 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2045 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2046 Lex.getAPSIntVal().getBitWidth() > 64)
2047 return TokError("expected number in address space");
2049 LocTy SizeLoc = Lex.getLoc();
2050 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2053 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2056 LocTy TypeLoc = Lex.getLoc();
2057 Type *EltTy = nullptr;
2058 if (ParseType(EltTy)) return true;
2060 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2061 "expected end of sequential type"))
2066 return Error(SizeLoc, "zero element vector is illegal");
2067 if ((unsigned)Size != Size)
2068 return Error(SizeLoc, "size too large for vector");
2069 if (!VectorType::isValidElementType(EltTy))
2070 return Error(TypeLoc, "invalid vector element type");
2071 Result = VectorType::get(EltTy, unsigned(Size));
2073 if (!ArrayType::isValidElementType(EltTy))
2074 return Error(TypeLoc, "invalid array element type");
2075 Result = ArrayType::get(EltTy, Size);
2080 //===----------------------------------------------------------------------===//
2081 // Function Semantic Analysis.
2082 //===----------------------------------------------------------------------===//
2084 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2086 : P(p), F(f), FunctionNumber(functionNumber) {
2088 // Insert unnamed arguments into the NumberedVals list.
2089 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2092 NumberedVals.push_back(AI);
2095 LLParser::PerFunctionState::~PerFunctionState() {
2096 // If there were any forward referenced non-basicblock values, delete them.
2097 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2098 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2099 if (!isa<BasicBlock>(I->second.first)) {
2100 I->second.first->replaceAllUsesWith(
2101 UndefValue::get(I->second.first->getType()));
2102 delete I->second.first;
2103 I->second.first = nullptr;
2106 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2107 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2108 if (!isa<BasicBlock>(I->second.first)) {
2109 I->second.first->replaceAllUsesWith(
2110 UndefValue::get(I->second.first->getType()));
2111 delete I->second.first;
2112 I->second.first = nullptr;
2116 bool LLParser::PerFunctionState::FinishFunction() {
2117 if (!ForwardRefVals.empty())
2118 return P.Error(ForwardRefVals.begin()->second.second,
2119 "use of undefined value '%" + ForwardRefVals.begin()->first +
2121 if (!ForwardRefValIDs.empty())
2122 return P.Error(ForwardRefValIDs.begin()->second.second,
2123 "use of undefined value '%" +
2124 Twine(ForwardRefValIDs.begin()->first) + "'");
2129 /// GetVal - Get a value with the specified name or ID, creating a
2130 /// forward reference record if needed. This can return null if the value
2131 /// exists but does not have the right type.
2132 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2133 Type *Ty, LocTy Loc) {
2134 // Look this name up in the normal function symbol table.
2135 Value *Val = F.getValueSymbolTable().lookup(Name);
2137 // If this is a forward reference for the value, see if we already created a
2138 // forward ref record.
2140 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2141 I = ForwardRefVals.find(Name);
2142 if (I != ForwardRefVals.end())
2143 Val = I->second.first;
2146 // If we have the value in the symbol table or fwd-ref table, return it.
2148 if (Val->getType() == Ty) return Val;
2149 if (Ty->isLabelTy())
2150 P.Error(Loc, "'%" + Name + "' is not a basic block");
2152 P.Error(Loc, "'%" + Name + "' defined with type '" +
2153 getTypeString(Val->getType()) + "'");
2157 // Don't make placeholders with invalid type.
2158 if (!Ty->isFirstClassType()) {
2159 P.Error(Loc, "invalid use of a non-first-class type");
2163 // Otherwise, create a new forward reference for this value and remember it.
2165 if (Ty->isLabelTy())
2166 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2168 FwdVal = new Argument(Ty, Name);
2170 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2174 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2176 // Look this name up in the normal function symbol table.
2177 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2179 // If this is a forward reference for the value, see if we already created a
2180 // forward ref record.
2182 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2183 I = ForwardRefValIDs.find(ID);
2184 if (I != ForwardRefValIDs.end())
2185 Val = I->second.first;
2188 // If we have the value in the symbol table or fwd-ref table, return it.
2190 if (Val->getType() == Ty) return Val;
2191 if (Ty->isLabelTy())
2192 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2194 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2195 getTypeString(Val->getType()) + "'");
2199 if (!Ty->isFirstClassType()) {
2200 P.Error(Loc, "invalid use of a non-first-class type");
2204 // Otherwise, create a new forward reference for this value and remember it.
2206 if (Ty->isLabelTy())
2207 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2209 FwdVal = new Argument(Ty);
2211 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2215 /// SetInstName - After an instruction is parsed and inserted into its
2216 /// basic block, this installs its name.
2217 bool LLParser::PerFunctionState::SetInstName(int NameID,
2218 const std::string &NameStr,
2219 LocTy NameLoc, Instruction *Inst) {
2220 // If this instruction has void type, it cannot have a name or ID specified.
2221 if (Inst->getType()->isVoidTy()) {
2222 if (NameID != -1 || !NameStr.empty())
2223 return P.Error(NameLoc, "instructions returning void cannot have a name");
2227 // If this was a numbered instruction, verify that the instruction is the
2228 // expected value and resolve any forward references.
2229 if (NameStr.empty()) {
2230 // If neither a name nor an ID was specified, just use the next ID.
2232 NameID = NumberedVals.size();
2234 if (unsigned(NameID) != NumberedVals.size())
2235 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2236 Twine(NumberedVals.size()) + "'");
2238 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2239 ForwardRefValIDs.find(NameID);
2240 if (FI != ForwardRefValIDs.end()) {
2241 if (FI->second.first->getType() != Inst->getType())
2242 return P.Error(NameLoc, "instruction forward referenced with type '" +
2243 getTypeString(FI->second.first->getType()) + "'");
2244 FI->second.first->replaceAllUsesWith(Inst);
2245 delete FI->second.first;
2246 ForwardRefValIDs.erase(FI);
2249 NumberedVals.push_back(Inst);
2253 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2254 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2255 FI = ForwardRefVals.find(NameStr);
2256 if (FI != ForwardRefVals.end()) {
2257 if (FI->second.first->getType() != Inst->getType())
2258 return P.Error(NameLoc, "instruction forward referenced with type '" +
2259 getTypeString(FI->second.first->getType()) + "'");
2260 FI->second.first->replaceAllUsesWith(Inst);
2261 delete FI->second.first;
2262 ForwardRefVals.erase(FI);
2265 // Set the name on the instruction.
2266 Inst->setName(NameStr);
2268 if (Inst->getName() != NameStr)
2269 return P.Error(NameLoc, "multiple definition of local value named '" +
2274 /// GetBB - Get a basic block with the specified name or ID, creating a
2275 /// forward reference record if needed.
2276 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2278 return cast_or_null<BasicBlock>(GetVal(Name,
2279 Type::getLabelTy(F.getContext()), Loc));
2282 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2283 return cast_or_null<BasicBlock>(GetVal(ID,
2284 Type::getLabelTy(F.getContext()), Loc));
2287 /// DefineBB - Define the specified basic block, which is either named or
2288 /// unnamed. If there is an error, this returns null otherwise it returns
2289 /// the block being defined.
2290 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2294 BB = GetBB(NumberedVals.size(), Loc);
2296 BB = GetBB(Name, Loc);
2297 if (!BB) return nullptr; // Already diagnosed error.
2299 // Move the block to the end of the function. Forward ref'd blocks are
2300 // inserted wherever they happen to be referenced.
2301 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2303 // Remove the block from forward ref sets.
2305 ForwardRefValIDs.erase(NumberedVals.size());
2306 NumberedVals.push_back(BB);
2308 // BB forward references are already in the function symbol table.
2309 ForwardRefVals.erase(Name);
2315 //===----------------------------------------------------------------------===//
2317 //===----------------------------------------------------------------------===//
2319 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2320 /// type implied. For example, if we parse "4" we don't know what integer type
2321 /// it has. The value will later be combined with its type and checked for
2322 /// sanity. PFS is used to convert function-local operands of metadata (since
2323 /// metadata operands are not just parsed here but also converted to values).
2324 /// PFS can be null when we are not parsing metadata values inside a function.
2325 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2326 ID.Loc = Lex.getLoc();
2327 switch (Lex.getKind()) {
2328 default: return TokError("expected value token");
2329 case lltok::GlobalID: // @42
2330 ID.UIntVal = Lex.getUIntVal();
2331 ID.Kind = ValID::t_GlobalID;
2333 case lltok::GlobalVar: // @foo
2334 ID.StrVal = Lex.getStrVal();
2335 ID.Kind = ValID::t_GlobalName;
2337 case lltok::LocalVarID: // %42
2338 ID.UIntVal = Lex.getUIntVal();
2339 ID.Kind = ValID::t_LocalID;
2341 case lltok::LocalVar: // %foo
2342 ID.StrVal = Lex.getStrVal();
2343 ID.Kind = ValID::t_LocalName;
2346 ID.APSIntVal = Lex.getAPSIntVal();
2347 ID.Kind = ValID::t_APSInt;
2349 case lltok::APFloat:
2350 ID.APFloatVal = Lex.getAPFloatVal();
2351 ID.Kind = ValID::t_APFloat;
2353 case lltok::kw_true:
2354 ID.ConstantVal = ConstantInt::getTrue(Context);
2355 ID.Kind = ValID::t_Constant;
2357 case lltok::kw_false:
2358 ID.ConstantVal = ConstantInt::getFalse(Context);
2359 ID.Kind = ValID::t_Constant;
2361 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2362 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2363 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2365 case lltok::lbrace: {
2366 // ValID ::= '{' ConstVector '}'
2368 SmallVector<Constant*, 16> Elts;
2369 if (ParseGlobalValueVector(Elts) ||
2370 ParseToken(lltok::rbrace, "expected end of struct constant"))
2373 ID.ConstantStructElts = new Constant*[Elts.size()];
2374 ID.UIntVal = Elts.size();
2375 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2376 ID.Kind = ValID::t_ConstantStruct;
2380 // ValID ::= '<' ConstVector '>' --> Vector.
2381 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2383 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2385 SmallVector<Constant*, 16> Elts;
2386 LocTy FirstEltLoc = Lex.getLoc();
2387 if (ParseGlobalValueVector(Elts) ||
2389 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2390 ParseToken(lltok::greater, "expected end of constant"))
2393 if (isPackedStruct) {
2394 ID.ConstantStructElts = new Constant*[Elts.size()];
2395 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2396 ID.UIntVal = Elts.size();
2397 ID.Kind = ValID::t_PackedConstantStruct;
2402 return Error(ID.Loc, "constant vector must not be empty");
2404 if (!Elts[0]->getType()->isIntegerTy() &&
2405 !Elts[0]->getType()->isFloatingPointTy() &&
2406 !Elts[0]->getType()->isPointerTy())
2407 return Error(FirstEltLoc,
2408 "vector elements must have integer, pointer or floating point type");
2410 // Verify that all the vector elements have the same type.
2411 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2412 if (Elts[i]->getType() != Elts[0]->getType())
2413 return Error(FirstEltLoc,
2414 "vector element #" + Twine(i) +
2415 " is not of type '" + getTypeString(Elts[0]->getType()));
2417 ID.ConstantVal = ConstantVector::get(Elts);
2418 ID.Kind = ValID::t_Constant;
2421 case lltok::lsquare: { // Array Constant
2423 SmallVector<Constant*, 16> Elts;
2424 LocTy FirstEltLoc = Lex.getLoc();
2425 if (ParseGlobalValueVector(Elts) ||
2426 ParseToken(lltok::rsquare, "expected end of array constant"))
2429 // Handle empty element.
2431 // Use undef instead of an array because it's inconvenient to determine
2432 // the element type at this point, there being no elements to examine.
2433 ID.Kind = ValID::t_EmptyArray;
2437 if (!Elts[0]->getType()->isFirstClassType())
2438 return Error(FirstEltLoc, "invalid array element type: " +
2439 getTypeString(Elts[0]->getType()));
2441 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2443 // Verify all elements are correct type!
2444 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2445 if (Elts[i]->getType() != Elts[0]->getType())
2446 return Error(FirstEltLoc,
2447 "array element #" + Twine(i) +
2448 " is not of type '" + getTypeString(Elts[0]->getType()));
2451 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2452 ID.Kind = ValID::t_Constant;
2455 case lltok::kw_c: // c "foo"
2457 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2459 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2460 ID.Kind = ValID::t_Constant;
2463 case lltok::kw_asm: {
2464 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2466 bool HasSideEffect, AlignStack, AsmDialect;
2468 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2469 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2470 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2471 ParseStringConstant(ID.StrVal) ||
2472 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2473 ParseToken(lltok::StringConstant, "expected constraint string"))
2475 ID.StrVal2 = Lex.getStrVal();
2476 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2477 (unsigned(AsmDialect)<<2);
2478 ID.Kind = ValID::t_InlineAsm;
2482 case lltok::kw_blockaddress: {
2483 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2488 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2490 ParseToken(lltok::comma, "expected comma in block address expression")||
2491 ParseValID(Label) ||
2492 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2495 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2496 return Error(Fn.Loc, "expected function name in blockaddress");
2497 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2498 return Error(Label.Loc, "expected basic block name in blockaddress");
2500 // Try to find the function (but skip it if it's forward-referenced).
2501 GlobalValue *GV = nullptr;
2502 if (Fn.Kind == ValID::t_GlobalID) {
2503 if (Fn.UIntVal < NumberedVals.size())
2504 GV = NumberedVals[Fn.UIntVal];
2505 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2506 GV = M->getNamedValue(Fn.StrVal);
2508 Function *F = nullptr;
2510 // Confirm that it's actually a function with a definition.
2511 if (!isa<Function>(GV))
2512 return Error(Fn.Loc, "expected function name in blockaddress");
2513 F = cast<Function>(GV);
2514 if (F->isDeclaration())
2515 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2519 // Make a global variable as a placeholder for this reference.
2520 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2522 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2523 GlobalValue::InternalLinkage, nullptr, "");
2524 ID.ConstantVal = FwdRef;
2525 ID.Kind = ValID::t_Constant;
2529 // We found the function; now find the basic block. Don't use PFS, since we
2530 // might be inside a constant expression.
2532 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2533 if (Label.Kind == ValID::t_LocalID)
2534 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2536 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2538 return Error(Label.Loc, "referenced value is not a basic block");
2540 if (Label.Kind == ValID::t_LocalID)
2541 return Error(Label.Loc, "cannot take address of numeric label after "
2542 "the function is defined");
2543 BB = dyn_cast_or_null<BasicBlock>(
2544 F->getValueSymbolTable().lookup(Label.StrVal));
2546 return Error(Label.Loc, "referenced value is not a basic block");
2549 ID.ConstantVal = BlockAddress::get(F, BB);
2550 ID.Kind = ValID::t_Constant;
2554 case lltok::kw_trunc:
2555 case lltok::kw_zext:
2556 case lltok::kw_sext:
2557 case lltok::kw_fptrunc:
2558 case lltok::kw_fpext:
2559 case lltok::kw_bitcast:
2560 case lltok::kw_addrspacecast:
2561 case lltok::kw_uitofp:
2562 case lltok::kw_sitofp:
2563 case lltok::kw_fptoui:
2564 case lltok::kw_fptosi:
2565 case lltok::kw_inttoptr:
2566 case lltok::kw_ptrtoint: {
2567 unsigned Opc = Lex.getUIntVal();
2568 Type *DestTy = nullptr;
2571 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2572 ParseGlobalTypeAndValue(SrcVal) ||
2573 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2574 ParseType(DestTy) ||
2575 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2577 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2578 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2579 getTypeString(SrcVal->getType()) + "' to '" +
2580 getTypeString(DestTy) + "'");
2581 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2583 ID.Kind = ValID::t_Constant;
2586 case lltok::kw_extractvalue: {
2589 SmallVector<unsigned, 4> Indices;
2590 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2591 ParseGlobalTypeAndValue(Val) ||
2592 ParseIndexList(Indices) ||
2593 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2596 if (!Val->getType()->isAggregateType())
2597 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2598 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2599 return Error(ID.Loc, "invalid indices for extractvalue");
2600 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2601 ID.Kind = ValID::t_Constant;
2604 case lltok::kw_insertvalue: {
2606 Constant *Val0, *Val1;
2607 SmallVector<unsigned, 4> Indices;
2608 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2609 ParseGlobalTypeAndValue(Val0) ||
2610 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2611 ParseGlobalTypeAndValue(Val1) ||
2612 ParseIndexList(Indices) ||
2613 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2615 if (!Val0->getType()->isAggregateType())
2616 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2617 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2618 return Error(ID.Loc, "invalid indices for insertvalue");
2619 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2620 ID.Kind = ValID::t_Constant;
2623 case lltok::kw_icmp:
2624 case lltok::kw_fcmp: {
2625 unsigned PredVal, Opc = Lex.getUIntVal();
2626 Constant *Val0, *Val1;
2628 if (ParseCmpPredicate(PredVal, Opc) ||
2629 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2630 ParseGlobalTypeAndValue(Val0) ||
2631 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2632 ParseGlobalTypeAndValue(Val1) ||
2633 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2636 if (Val0->getType() != Val1->getType())
2637 return Error(ID.Loc, "compare operands must have the same type");
2639 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2641 if (Opc == Instruction::FCmp) {
2642 if (!Val0->getType()->isFPOrFPVectorTy())
2643 return Error(ID.Loc, "fcmp requires floating point operands");
2644 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2646 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2647 if (!Val0->getType()->isIntOrIntVectorTy() &&
2648 !Val0->getType()->getScalarType()->isPointerTy())
2649 return Error(ID.Loc, "icmp requires pointer or integer operands");
2650 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2652 ID.Kind = ValID::t_Constant;
2656 // Binary Operators.
2658 case lltok::kw_fadd:
2660 case lltok::kw_fsub:
2662 case lltok::kw_fmul:
2663 case lltok::kw_udiv:
2664 case lltok::kw_sdiv:
2665 case lltok::kw_fdiv:
2666 case lltok::kw_urem:
2667 case lltok::kw_srem:
2668 case lltok::kw_frem:
2670 case lltok::kw_lshr:
2671 case lltok::kw_ashr: {
2675 unsigned Opc = Lex.getUIntVal();
2676 Constant *Val0, *Val1;
2678 LocTy ModifierLoc = Lex.getLoc();
2679 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2680 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2681 if (EatIfPresent(lltok::kw_nuw))
2683 if (EatIfPresent(lltok::kw_nsw)) {
2685 if (EatIfPresent(lltok::kw_nuw))
2688 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2689 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2690 if (EatIfPresent(lltok::kw_exact))
2693 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2694 ParseGlobalTypeAndValue(Val0) ||
2695 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2696 ParseGlobalTypeAndValue(Val1) ||
2697 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2699 if (Val0->getType() != Val1->getType())
2700 return Error(ID.Loc, "operands of constexpr must have same type");
2701 if (!Val0->getType()->isIntOrIntVectorTy()) {
2703 return Error(ModifierLoc, "nuw only applies to integer operations");
2705 return Error(ModifierLoc, "nsw only applies to integer operations");
2707 // Check that the type is valid for the operator.
2709 case Instruction::Add:
2710 case Instruction::Sub:
2711 case Instruction::Mul:
2712 case Instruction::UDiv:
2713 case Instruction::SDiv:
2714 case Instruction::URem:
2715 case Instruction::SRem:
2716 case Instruction::Shl:
2717 case Instruction::AShr:
2718 case Instruction::LShr:
2719 if (!Val0->getType()->isIntOrIntVectorTy())
2720 return Error(ID.Loc, "constexpr requires integer operands");
2722 case Instruction::FAdd:
2723 case Instruction::FSub:
2724 case Instruction::FMul:
2725 case Instruction::FDiv:
2726 case Instruction::FRem:
2727 if (!Val0->getType()->isFPOrFPVectorTy())
2728 return Error(ID.Loc, "constexpr requires fp operands");
2730 default: llvm_unreachable("Unknown binary operator!");
2733 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2734 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2735 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2736 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2738 ID.Kind = ValID::t_Constant;
2742 // Logical Operations
2745 case lltok::kw_xor: {
2746 unsigned Opc = Lex.getUIntVal();
2747 Constant *Val0, *Val1;
2749 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2750 ParseGlobalTypeAndValue(Val0) ||
2751 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2752 ParseGlobalTypeAndValue(Val1) ||
2753 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2755 if (Val0->getType() != Val1->getType())
2756 return Error(ID.Loc, "operands of constexpr must have same type");
2757 if (!Val0->getType()->isIntOrIntVectorTy())
2758 return Error(ID.Loc,
2759 "constexpr requires integer or integer vector operands");
2760 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2761 ID.Kind = ValID::t_Constant;
2765 case lltok::kw_getelementptr:
2766 case lltok::kw_shufflevector:
2767 case lltok::kw_insertelement:
2768 case lltok::kw_extractelement:
2769 case lltok::kw_select: {
2770 unsigned Opc = Lex.getUIntVal();
2771 SmallVector<Constant*, 16> Elts;
2772 bool InBounds = false;
2774 if (Opc == Instruction::GetElementPtr)
2775 InBounds = EatIfPresent(lltok::kw_inbounds);
2776 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2777 ParseGlobalValueVector(Elts) ||
2778 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2781 if (Opc == Instruction::GetElementPtr) {
2782 if (Elts.size() == 0 ||
2783 !Elts[0]->getType()->getScalarType()->isPointerTy())
2784 return Error(ID.Loc, "getelementptr requires pointer operand");
2786 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2787 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2788 return Error(ID.Loc, "invalid indices for getelementptr");
2789 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2791 } else if (Opc == Instruction::Select) {
2792 if (Elts.size() != 3)
2793 return Error(ID.Loc, "expected three operands to select");
2794 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2796 return Error(ID.Loc, Reason);
2797 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2798 } else if (Opc == Instruction::ShuffleVector) {
2799 if (Elts.size() != 3)
2800 return Error(ID.Loc, "expected three operands to shufflevector");
2801 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2802 return Error(ID.Loc, "invalid operands to shufflevector");
2804 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2805 } else if (Opc == Instruction::ExtractElement) {
2806 if (Elts.size() != 2)
2807 return Error(ID.Loc, "expected two operands to extractelement");
2808 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2809 return Error(ID.Loc, "invalid extractelement operands");
2810 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2812 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2813 if (Elts.size() != 3)
2814 return Error(ID.Loc, "expected three operands to insertelement");
2815 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2816 return Error(ID.Loc, "invalid insertelement operands");
2818 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2821 ID.Kind = ValID::t_Constant;
2830 /// ParseGlobalValue - Parse a global value with the specified type.
2831 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2835 bool Parsed = ParseValID(ID) ||
2836 ConvertValIDToValue(Ty, ID, V, nullptr);
2837 if (V && !(C = dyn_cast<Constant>(V)))
2838 return Error(ID.Loc, "global values must be constants");
2842 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2844 return ParseType(Ty) ||
2845 ParseGlobalValue(Ty, V);
2848 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2851 LocTy KwLoc = Lex.getLoc();
2852 if (!EatIfPresent(lltok::kw_comdat))
2855 if (EatIfPresent(lltok::lparen)) {
2856 if (Lex.getKind() != lltok::ComdatVar)
2857 return TokError("expected comdat variable");
2858 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2860 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2863 if (GlobalName.empty())
2864 return TokError("comdat cannot be unnamed");
2865 C = getComdat(GlobalName, KwLoc);
2871 /// ParseGlobalValueVector
2873 /// ::= TypeAndValue (',' TypeAndValue)*
2874 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2876 if (Lex.getKind() == lltok::rbrace ||
2877 Lex.getKind() == lltok::rsquare ||
2878 Lex.getKind() == lltok::greater ||
2879 Lex.getKind() == lltok::rparen)
2883 if (ParseGlobalTypeAndValue(C)) return true;
2886 while (EatIfPresent(lltok::comma)) {
2887 if (ParseGlobalTypeAndValue(C)) return true;
2894 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2895 SmallVector<Metadata *, 16> Elts;
2896 if (ParseMDNodeVector(Elts))
2899 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2906 /// ::= !MDLocation(...)
2907 bool LLParser::ParseMDNode(MDNode *&N) {
2908 if (Lex.getKind() == lltok::MetadataVar)
2909 return ParseSpecializedMDNode(N);
2911 return ParseToken(lltok::exclaim, "expected '!' here") ||
2915 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2917 if (Lex.getKind() == lltok::lbrace)
2918 return ParseMDTuple(N);
2921 return ParseMDNodeID(N);
2924 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
2925 MDUnsignedField<uint32_t> &Result) {
2928 "field '" + Name + "' cannot be specified more than once");
2930 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2931 return TokError("expected unsigned integer");
2932 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(Result.Max + 1ull);
2934 if (Val64 > Result.Max)
2935 return TokError("value for '" + Name + "' too large, limit is " +
2937 Result.assign(Val64);
2942 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
2945 "field '" + Name + "' cannot be specified more than once");
2948 if (ParseMetadata(MD, nullptr))
2955 template <class ParserTy>
2956 bool LLParser::ParseMDFieldsImpl(ParserTy parseField) {
2957 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
2960 if (ParseToken(lltok::lparen, "expected '(' here"))
2962 if (EatIfPresent(lltok::rparen))
2966 if (Lex.getKind() != lltok::LabelStr)
2967 return TokError("expected field label here");
2971 } while (EatIfPresent(lltok::comma));
2973 return ParseToken(lltok::rparen, "expected ')' here");
2976 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
2977 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
2978 #define DISPATCH_TO_PARSER(CLASS) \
2979 if (Lex.getStrVal() == #CLASS) \
2980 return Parse##CLASS(N, IsDistinct);
2982 DISPATCH_TO_PARSER(MDLocation);
2983 #undef DISPATCH_TO_PARSER
2985 return TokError("expected metadata type");
2988 #define PARSE_MD_FIELD(NAME) \
2990 if (Lex.getStrVal() == #NAME) { \
2991 LocTy Loc = Lex.getLoc(); \
2993 if (ParseMDField(Loc, #NAME, NAME)) \
2999 /// ParseMDLocationFields:
3000 /// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3001 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3002 MDUnsignedField<uint32_t> line(0, ~0u >> 8);
3003 MDUnsignedField<uint32_t> column(0, ~0u >> 16);
3006 if (ParseMDFieldsImpl([&]() -> bool {
3007 PARSE_MD_FIELD(line);
3008 PARSE_MD_FIELD(column);
3009 PARSE_MD_FIELD(scope);
3010 PARSE_MD_FIELD(inlinedAt);
3011 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");
3016 return TokError("missing required field 'scope'");
3018 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3019 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3022 #undef PARSE_MD_FIELD
3024 /// ParseMetadataAsValue
3025 /// ::= metadata i32 %local
3026 /// ::= metadata i32 @global
3027 /// ::= metadata i32 7
3029 /// ::= metadata !{...}
3030 /// ::= metadata !"string"
3031 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3032 // Note: the type 'metadata' has already been parsed.
3034 if (ParseMetadata(MD, &PFS))
3037 V = MetadataAsValue::get(Context, MD);
3041 /// ParseValueAsMetadata
3045 bool LLParser::ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS) {
3048 if (ParseType(Ty, "expected metadata operand", Loc))
3050 if (Ty->isMetadataTy())
3051 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3054 if (ParseValue(Ty, V, PFS))
3057 MD = ValueAsMetadata::get(V);
3068 /// ::= !MDLocation(...)
3069 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3070 if (Lex.getKind() == lltok::MetadataVar) {
3072 if (ParseSpecializedMDNode(N))
3080 if (Lex.getKind() != lltok::exclaim)
3081 return ParseValueAsMetadata(MD, PFS);
3084 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3088 // ::= '!' STRINGCONSTANT
3089 if (Lex.getKind() == lltok::StringConstant) {
3091 if (ParseMDString(S))
3101 if (ParseMDNodeTail(N))
3108 //===----------------------------------------------------------------------===//
3109 // Function Parsing.
3110 //===----------------------------------------------------------------------===//
3112 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3113 PerFunctionState *PFS) {
3114 if (Ty->isFunctionTy())
3115 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3118 case ValID::t_LocalID:
3119 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3120 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3121 return V == nullptr;
3122 case ValID::t_LocalName:
3123 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3124 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3125 return V == nullptr;
3126 case ValID::t_InlineAsm: {
3127 PointerType *PTy = dyn_cast<PointerType>(Ty);
3129 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3130 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3131 return Error(ID.Loc, "invalid type for inline asm constraint string");
3132 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3133 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3136 case ValID::t_GlobalName:
3137 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3138 return V == nullptr;
3139 case ValID::t_GlobalID:
3140 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3141 return V == nullptr;
3142 case ValID::t_APSInt:
3143 if (!Ty->isIntegerTy())
3144 return Error(ID.Loc, "integer constant must have integer type");
3145 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3146 V = ConstantInt::get(Context, ID.APSIntVal);
3148 case ValID::t_APFloat:
3149 if (!Ty->isFloatingPointTy() ||
3150 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3151 return Error(ID.Loc, "floating point constant invalid for type");
3153 // The lexer has no type info, so builds all half, float, and double FP
3154 // constants as double. Fix this here. Long double does not need this.
3155 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3158 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3160 else if (Ty->isFloatTy())
3161 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3164 V = ConstantFP::get(Context, ID.APFloatVal);
3166 if (V->getType() != Ty)
3167 return Error(ID.Loc, "floating point constant does not have type '" +
3168 getTypeString(Ty) + "'");
3172 if (!Ty->isPointerTy())
3173 return Error(ID.Loc, "null must be a pointer type");
3174 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3176 case ValID::t_Undef:
3177 // FIXME: LabelTy should not be a first-class type.
3178 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3179 return Error(ID.Loc, "invalid type for undef constant");
3180 V = UndefValue::get(Ty);
3182 case ValID::t_EmptyArray:
3183 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3184 return Error(ID.Loc, "invalid empty array initializer");
3185 V = UndefValue::get(Ty);
3188 // FIXME: LabelTy should not be a first-class type.
3189 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3190 return Error(ID.Loc, "invalid type for null constant");
3191 V = Constant::getNullValue(Ty);
3193 case ValID::t_Constant:
3194 if (ID.ConstantVal->getType() != Ty)
3195 return Error(ID.Loc, "constant expression type mismatch");
3199 case ValID::t_ConstantStruct:
3200 case ValID::t_PackedConstantStruct:
3201 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3202 if (ST->getNumElements() != ID.UIntVal)
3203 return Error(ID.Loc,
3204 "initializer with struct type has wrong # elements");
3205 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3206 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3208 // Verify that the elements are compatible with the structtype.
3209 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3210 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3211 return Error(ID.Loc, "element " + Twine(i) +
3212 " of struct initializer doesn't match struct element type");
3214 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3217 return Error(ID.Loc, "constant expression type mismatch");
3220 llvm_unreachable("Invalid ValID");
3223 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3226 return ParseValID(ID, PFS) ||
3227 ConvertValIDToValue(Ty, ID, V, PFS);
3230 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3232 return ParseType(Ty) ||
3233 ParseValue(Ty, V, PFS);
3236 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3237 PerFunctionState &PFS) {
3240 if (ParseTypeAndValue(V, PFS)) return true;
3241 if (!isa<BasicBlock>(V))
3242 return Error(Loc, "expected a basic block");
3243 BB = cast<BasicBlock>(V);
3249 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3250 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3251 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3252 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3253 // Parse the linkage.
3254 LocTy LinkageLoc = Lex.getLoc();
3257 unsigned Visibility;
3258 unsigned DLLStorageClass;
3259 AttrBuilder RetAttrs;
3261 Type *RetType = nullptr;
3262 LocTy RetTypeLoc = Lex.getLoc();
3263 if (ParseOptionalLinkage(Linkage) ||
3264 ParseOptionalVisibility(Visibility) ||
3265 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3266 ParseOptionalCallingConv(CC) ||
3267 ParseOptionalReturnAttrs(RetAttrs) ||
3268 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3271 // Verify that the linkage is ok.
3272 switch ((GlobalValue::LinkageTypes)Linkage) {
3273 case GlobalValue::ExternalLinkage:
3274 break; // always ok.
3275 case GlobalValue::ExternalWeakLinkage:
3277 return Error(LinkageLoc, "invalid linkage for function definition");
3279 case GlobalValue::PrivateLinkage:
3280 case GlobalValue::InternalLinkage:
3281 case GlobalValue::AvailableExternallyLinkage:
3282 case GlobalValue::LinkOnceAnyLinkage:
3283 case GlobalValue::LinkOnceODRLinkage:
3284 case GlobalValue::WeakAnyLinkage:
3285 case GlobalValue::WeakODRLinkage:
3287 return Error(LinkageLoc, "invalid linkage for function declaration");
3289 case GlobalValue::AppendingLinkage:
3290 case GlobalValue::CommonLinkage:
3291 return Error(LinkageLoc, "invalid function linkage type");
3294 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3295 return Error(LinkageLoc,
3296 "symbol with local linkage must have default visibility");
3298 if (!FunctionType::isValidReturnType(RetType))
3299 return Error(RetTypeLoc, "invalid function return type");
3301 LocTy NameLoc = Lex.getLoc();
3303 std::string FunctionName;
3304 if (Lex.getKind() == lltok::GlobalVar) {
3305 FunctionName = Lex.getStrVal();
3306 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3307 unsigned NameID = Lex.getUIntVal();
3309 if (NameID != NumberedVals.size())
3310 return TokError("function expected to be numbered '%" +
3311 Twine(NumberedVals.size()) + "'");
3313 return TokError("expected function name");
3318 if (Lex.getKind() != lltok::lparen)
3319 return TokError("expected '(' in function argument list");
3321 SmallVector<ArgInfo, 8> ArgList;
3323 AttrBuilder FuncAttrs;
3324 std::vector<unsigned> FwdRefAttrGrps;
3326 std::string Section;
3330 LocTy UnnamedAddrLoc;
3331 Constant *Prefix = nullptr;
3332 Constant *Prologue = nullptr;
3335 if (ParseArgumentList(ArgList, isVarArg) ||
3336 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3338 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3340 (EatIfPresent(lltok::kw_section) &&
3341 ParseStringConstant(Section)) ||
3342 parseOptionalComdat(FunctionName, C) ||
3343 ParseOptionalAlignment(Alignment) ||
3344 (EatIfPresent(lltok::kw_gc) &&
3345 ParseStringConstant(GC)) ||
3346 (EatIfPresent(lltok::kw_prefix) &&
3347 ParseGlobalTypeAndValue(Prefix)) ||
3348 (EatIfPresent(lltok::kw_prologue) &&
3349 ParseGlobalTypeAndValue(Prologue)))
3352 if (FuncAttrs.contains(Attribute::Builtin))
3353 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3355 // If the alignment was parsed as an attribute, move to the alignment field.
3356 if (FuncAttrs.hasAlignmentAttr()) {
3357 Alignment = FuncAttrs.getAlignment();
3358 FuncAttrs.removeAttribute(Attribute::Alignment);
3361 // Okay, if we got here, the function is syntactically valid. Convert types
3362 // and do semantic checks.
3363 std::vector<Type*> ParamTypeList;
3364 SmallVector<AttributeSet, 8> Attrs;
3366 if (RetAttrs.hasAttributes())
3367 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3368 AttributeSet::ReturnIndex,
3371 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3372 ParamTypeList.push_back(ArgList[i].Ty);
3373 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3374 AttrBuilder B(ArgList[i].Attrs, i + 1);
3375 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3379 if (FuncAttrs.hasAttributes())
3380 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3381 AttributeSet::FunctionIndex,
3384 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3386 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3387 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3390 FunctionType::get(RetType, ParamTypeList, isVarArg);
3391 PointerType *PFT = PointerType::getUnqual(FT);
3394 if (!FunctionName.empty()) {
3395 // If this was a definition of a forward reference, remove the definition
3396 // from the forward reference table and fill in the forward ref.
3397 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3398 ForwardRefVals.find(FunctionName);
3399 if (FRVI != ForwardRefVals.end()) {
3400 Fn = M->getFunction(FunctionName);
3402 return Error(FRVI->second.second, "invalid forward reference to "
3403 "function as global value!");
3404 if (Fn->getType() != PFT)
3405 return Error(FRVI->second.second, "invalid forward reference to "
3406 "function '" + FunctionName + "' with wrong type!");
3408 ForwardRefVals.erase(FRVI);
3409 } else if ((Fn = M->getFunction(FunctionName))) {
3410 // Reject redefinitions.
3411 return Error(NameLoc, "invalid redefinition of function '" +
3412 FunctionName + "'");
3413 } else if (M->getNamedValue(FunctionName)) {
3414 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3418 // If this is a definition of a forward referenced function, make sure the
3420 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3421 = ForwardRefValIDs.find(NumberedVals.size());
3422 if (I != ForwardRefValIDs.end()) {
3423 Fn = cast<Function>(I->second.first);
3424 if (Fn->getType() != PFT)
3425 return Error(NameLoc, "type of definition and forward reference of '@" +
3426 Twine(NumberedVals.size()) + "' disagree");
3427 ForwardRefValIDs.erase(I);
3432 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3433 else // Move the forward-reference to the correct spot in the module.
3434 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3436 if (FunctionName.empty())
3437 NumberedVals.push_back(Fn);
3439 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3440 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3441 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3442 Fn->setCallingConv(CC);
3443 Fn->setAttributes(PAL);
3444 Fn->setUnnamedAddr(UnnamedAddr);
3445 Fn->setAlignment(Alignment);
3446 Fn->setSection(Section);
3448 if (!GC.empty()) Fn->setGC(GC.c_str());
3449 Fn->setPrefixData(Prefix);
3450 Fn->setPrologueData(Prologue);
3451 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3453 // Add all of the arguments we parsed to the function.
3454 Function::arg_iterator ArgIt = Fn->arg_begin();
3455 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3456 // If the argument has a name, insert it into the argument symbol table.
3457 if (ArgList[i].Name.empty()) continue;
3459 // Set the name, if it conflicted, it will be auto-renamed.
3460 ArgIt->setName(ArgList[i].Name);
3462 if (ArgIt->getName() != ArgList[i].Name)
3463 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3464 ArgList[i].Name + "'");
3470 // Check the declaration has no block address forward references.
3472 if (FunctionName.empty()) {
3473 ID.Kind = ValID::t_GlobalID;
3474 ID.UIntVal = NumberedVals.size() - 1;
3476 ID.Kind = ValID::t_GlobalName;
3477 ID.StrVal = FunctionName;
3479 auto Blocks = ForwardRefBlockAddresses.find(ID);
3480 if (Blocks != ForwardRefBlockAddresses.end())
3481 return Error(Blocks->first.Loc,
3482 "cannot take blockaddress inside a declaration");
3486 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
3488 if (FunctionNumber == -1) {
3489 ID.Kind = ValID::t_GlobalName;
3490 ID.StrVal = F.getName();
3492 ID.Kind = ValID::t_GlobalID;
3493 ID.UIntVal = FunctionNumber;
3496 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
3497 if (Blocks == P.ForwardRefBlockAddresses.end())
3500 for (const auto &I : Blocks->second) {
3501 const ValID &BBID = I.first;
3502 GlobalValue *GV = I.second;
3504 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
3505 "Expected local id or name");
3507 if (BBID.Kind == ValID::t_LocalName)
3508 BB = GetBB(BBID.StrVal, BBID.Loc);
3510 BB = GetBB(BBID.UIntVal, BBID.Loc);
3512 return P.Error(BBID.Loc, "referenced value is not a basic block");
3514 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
3515 GV->eraseFromParent();
3518 P.ForwardRefBlockAddresses.erase(Blocks);
3522 /// ParseFunctionBody
3523 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
3524 bool LLParser::ParseFunctionBody(Function &Fn) {
3525 if (Lex.getKind() != lltok::lbrace)
3526 return TokError("expected '{' in function body");
3527 Lex.Lex(); // eat the {.
3529 int FunctionNumber = -1;
3530 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3532 PerFunctionState PFS(*this, Fn, FunctionNumber);
3534 // Resolve block addresses and allow basic blocks to be forward-declared
3535 // within this function.
3536 if (PFS.resolveForwardRefBlockAddresses())
3538 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
3540 // We need at least one basic block.
3541 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
3542 return TokError("function body requires at least one basic block");
3544 while (Lex.getKind() != lltok::rbrace &&
3545 Lex.getKind() != lltok::kw_uselistorder)
3546 if (ParseBasicBlock(PFS)) return true;
3548 while (Lex.getKind() != lltok::rbrace)
3549 if (ParseUseListOrder(&PFS))
3555 // Verify function is ok.
3556 return PFS.FinishFunction();
3560 /// ::= LabelStr? Instruction*
3561 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3562 // If this basic block starts out with a name, remember it.
3564 LocTy NameLoc = Lex.getLoc();
3565 if (Lex.getKind() == lltok::LabelStr) {
3566 Name = Lex.getStrVal();
3570 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3571 if (!BB) return true;
3573 std::string NameStr;
3575 // Parse the instructions in this block until we get a terminator.
3578 // This instruction may have three possibilities for a name: a) none
3579 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3580 LocTy NameLoc = Lex.getLoc();
3584 if (Lex.getKind() == lltok::LocalVarID) {
3585 NameID = Lex.getUIntVal();
3587 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3589 } else if (Lex.getKind() == lltok::LocalVar) {
3590 NameStr = Lex.getStrVal();
3592 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3596 switch (ParseInstruction(Inst, BB, PFS)) {
3597 default: llvm_unreachable("Unknown ParseInstruction result!");
3598 case InstError: return true;
3600 BB->getInstList().push_back(Inst);
3602 // With a normal result, we check to see if the instruction is followed by
3603 // a comma and metadata.
3604 if (EatIfPresent(lltok::comma))
3605 if (ParseInstructionMetadata(Inst, &PFS))
3608 case InstExtraComma:
3609 BB->getInstList().push_back(Inst);
3611 // If the instruction parser ate an extra comma at the end of it, it
3612 // *must* be followed by metadata.
3613 if (ParseInstructionMetadata(Inst, &PFS))
3618 // Set the name on the instruction.
3619 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3620 } while (!isa<TerminatorInst>(Inst));
3625 //===----------------------------------------------------------------------===//
3626 // Instruction Parsing.
3627 //===----------------------------------------------------------------------===//
3629 /// ParseInstruction - Parse one of the many different instructions.
3631 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3632 PerFunctionState &PFS) {
3633 lltok::Kind Token = Lex.getKind();
3634 if (Token == lltok::Eof)
3635 return TokError("found end of file when expecting more instructions");
3636 LocTy Loc = Lex.getLoc();
3637 unsigned KeywordVal = Lex.getUIntVal();
3638 Lex.Lex(); // Eat the keyword.
3641 default: return Error(Loc, "expected instruction opcode");
3642 // Terminator Instructions.
3643 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3644 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3645 case lltok::kw_br: return ParseBr(Inst, PFS);
3646 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3647 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3648 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3649 case lltok::kw_resume: return ParseResume(Inst, PFS);
3650 // Binary Operators.
3654 case lltok::kw_shl: {
3655 bool NUW = EatIfPresent(lltok::kw_nuw);
3656 bool NSW = EatIfPresent(lltok::kw_nsw);
3657 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3659 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3661 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3662 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3665 case lltok::kw_fadd:
3666 case lltok::kw_fsub:
3667 case lltok::kw_fmul:
3668 case lltok::kw_fdiv:
3669 case lltok::kw_frem: {
3670 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3671 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3675 Inst->setFastMathFlags(FMF);
3679 case lltok::kw_sdiv:
3680 case lltok::kw_udiv:
3681 case lltok::kw_lshr:
3682 case lltok::kw_ashr: {
3683 bool Exact = EatIfPresent(lltok::kw_exact);
3685 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3686 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3690 case lltok::kw_urem:
3691 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3694 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3695 case lltok::kw_icmp:
3696 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3698 case lltok::kw_trunc:
3699 case lltok::kw_zext:
3700 case lltok::kw_sext:
3701 case lltok::kw_fptrunc:
3702 case lltok::kw_fpext:
3703 case lltok::kw_bitcast:
3704 case lltok::kw_addrspacecast:
3705 case lltok::kw_uitofp:
3706 case lltok::kw_sitofp:
3707 case lltok::kw_fptoui:
3708 case lltok::kw_fptosi:
3709 case lltok::kw_inttoptr:
3710 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3712 case lltok::kw_select: return ParseSelect(Inst, PFS);
3713 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3714 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3715 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3716 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3717 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3718 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3720 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3721 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3722 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3724 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3725 case lltok::kw_load: return ParseLoad(Inst, PFS);
3726 case lltok::kw_store: return ParseStore(Inst, PFS);
3727 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3728 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3729 case lltok::kw_fence: return ParseFence(Inst, PFS);
3730 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3731 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3732 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3736 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3737 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3738 if (Opc == Instruction::FCmp) {
3739 switch (Lex.getKind()) {
3740 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3741 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3742 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3743 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3744 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3745 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3746 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3747 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3748 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3749 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3750 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3751 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3752 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3753 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3754 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3755 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3756 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3759 switch (Lex.getKind()) {
3760 default: return TokError("expected icmp predicate (e.g. 'eq')");
3761 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3762 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3763 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3764 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3765 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3766 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3767 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3768 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3769 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3770 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3777 //===----------------------------------------------------------------------===//
3778 // Terminator Instructions.
3779 //===----------------------------------------------------------------------===//
3781 /// ParseRet - Parse a return instruction.
3782 /// ::= 'ret' void (',' !dbg, !1)*
3783 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3784 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3785 PerFunctionState &PFS) {
3786 SMLoc TypeLoc = Lex.getLoc();
3788 if (ParseType(Ty, true /*void allowed*/)) return true;
3790 Type *ResType = PFS.getFunction().getReturnType();
3792 if (Ty->isVoidTy()) {
3793 if (!ResType->isVoidTy())
3794 return Error(TypeLoc, "value doesn't match function result type '" +
3795 getTypeString(ResType) + "'");
3797 Inst = ReturnInst::Create(Context);
3802 if (ParseValue(Ty, RV, PFS)) return true;
3804 if (ResType != RV->getType())
3805 return Error(TypeLoc, "value doesn't match function result type '" +
3806 getTypeString(ResType) + "'");
3808 Inst = ReturnInst::Create(Context, RV);
3814 /// ::= 'br' TypeAndValue
3815 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3816 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3819 BasicBlock *Op1, *Op2;
3820 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3822 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3823 Inst = BranchInst::Create(BB);
3827 if (Op0->getType() != Type::getInt1Ty(Context))
3828 return Error(Loc, "branch condition must have 'i1' type");
3830 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3831 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3832 ParseToken(lltok::comma, "expected ',' after true destination") ||
3833 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3836 Inst = BranchInst::Create(Op1, Op2, Op0);
3842 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3844 /// ::= (TypeAndValue ',' TypeAndValue)*
3845 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3846 LocTy CondLoc, BBLoc;
3848 BasicBlock *DefaultBB;
3849 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3850 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3851 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3852 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3855 if (!Cond->getType()->isIntegerTy())
3856 return Error(CondLoc, "switch condition must have integer type");
3858 // Parse the jump table pairs.
3859 SmallPtrSet<Value*, 32> SeenCases;
3860 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3861 while (Lex.getKind() != lltok::rsquare) {
3865 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3866 ParseToken(lltok::comma, "expected ',' after case value") ||
3867 ParseTypeAndBasicBlock(DestBB, PFS))
3870 if (!SeenCases.insert(Constant).second)
3871 return Error(CondLoc, "duplicate case value in switch");
3872 if (!isa<ConstantInt>(Constant))
3873 return Error(CondLoc, "case value is not a constant integer");
3875 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3878 Lex.Lex(); // Eat the ']'.
3880 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3881 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3882 SI->addCase(Table[i].first, Table[i].second);
3889 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3890 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3893 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3894 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3895 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3898 if (!Address->getType()->isPointerTy())
3899 return Error(AddrLoc, "indirectbr address must have pointer type");
3901 // Parse the destination list.
3902 SmallVector<BasicBlock*, 16> DestList;
3904 if (Lex.getKind() != lltok::rsquare) {
3906 if (ParseTypeAndBasicBlock(DestBB, PFS))
3908 DestList.push_back(DestBB);
3910 while (EatIfPresent(lltok::comma)) {
3911 if (ParseTypeAndBasicBlock(DestBB, PFS))
3913 DestList.push_back(DestBB);
3917 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3920 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3921 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3922 IBI->addDestination(DestList[i]);
3929 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3930 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3931 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3932 LocTy CallLoc = Lex.getLoc();
3933 AttrBuilder RetAttrs, FnAttrs;
3934 std::vector<unsigned> FwdRefAttrGrps;
3937 Type *RetType = nullptr;
3940 SmallVector<ParamInfo, 16> ArgList;
3942 BasicBlock *NormalBB, *UnwindBB;
3943 if (ParseOptionalCallingConv(CC) ||
3944 ParseOptionalReturnAttrs(RetAttrs) ||
3945 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3946 ParseValID(CalleeID) ||
3947 ParseParameterList(ArgList, PFS) ||
3948 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3950 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3951 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3952 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3953 ParseTypeAndBasicBlock(UnwindBB, PFS))
3956 // If RetType is a non-function pointer type, then this is the short syntax
3957 // for the call, which means that RetType is just the return type. Infer the
3958 // rest of the function argument types from the arguments that are present.
3959 PointerType *PFTy = nullptr;
3960 FunctionType *Ty = nullptr;
3961 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3962 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3963 // Pull out the types of all of the arguments...
3964 std::vector<Type*> ParamTypes;
3965 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3966 ParamTypes.push_back(ArgList[i].V->getType());
3968 if (!FunctionType::isValidReturnType(RetType))
3969 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3971 Ty = FunctionType::get(RetType, ParamTypes, false);
3972 PFTy = PointerType::getUnqual(Ty);
3975 // Look up the callee.
3977 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3979 // Set up the Attribute for the function.
3980 SmallVector<AttributeSet, 8> Attrs;
3981 if (RetAttrs.hasAttributes())
3982 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3983 AttributeSet::ReturnIndex,
3986 SmallVector<Value*, 8> Args;
3988 // Loop through FunctionType's arguments and ensure they are specified
3989 // correctly. Also, gather any parameter attributes.
3990 FunctionType::param_iterator I = Ty->param_begin();
3991 FunctionType::param_iterator E = Ty->param_end();
3992 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3993 Type *ExpectedTy = nullptr;
3996 } else if (!Ty->isVarArg()) {
3997 return Error(ArgList[i].Loc, "too many arguments specified");
4000 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4001 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4002 getTypeString(ExpectedTy) + "'");
4003 Args.push_back(ArgList[i].V);
4004 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4005 AttrBuilder B(ArgList[i].Attrs, i + 1);
4006 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4011 return Error(CallLoc, "not enough parameters specified for call");
4013 if (FnAttrs.hasAttributes())
4014 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4015 AttributeSet::FunctionIndex,
4018 // Finish off the Attribute and check them
4019 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4021 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4022 II->setCallingConv(CC);
4023 II->setAttributes(PAL);
4024 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4030 /// ::= 'resume' TypeAndValue
4031 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4032 Value *Exn; LocTy ExnLoc;
4033 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4036 ResumeInst *RI = ResumeInst::Create(Exn);
4041 //===----------------------------------------------------------------------===//
4042 // Binary Operators.
4043 //===----------------------------------------------------------------------===//
4046 /// ::= ArithmeticOps TypeAndValue ',' Value
4048 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4049 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4050 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4051 unsigned Opc, unsigned OperandType) {
4052 LocTy Loc; Value *LHS, *RHS;
4053 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4054 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4055 ParseValue(LHS->getType(), RHS, PFS))
4059 switch (OperandType) {
4060 default: llvm_unreachable("Unknown operand type!");
4061 case 0: // int or FP.
4062 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4063 LHS->getType()->isFPOrFPVectorTy();
4065 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4066 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4070 return Error(Loc, "invalid operand type for instruction");
4072 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4077 /// ::= ArithmeticOps TypeAndValue ',' Value {
4078 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4080 LocTy Loc; Value *LHS, *RHS;
4081 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4082 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4083 ParseValue(LHS->getType(), RHS, PFS))
4086 if (!LHS->getType()->isIntOrIntVectorTy())
4087 return Error(Loc,"instruction requires integer or integer vector operands");
4089 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4095 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4096 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4097 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4099 // Parse the integer/fp comparison predicate.
4103 if (ParseCmpPredicate(Pred, Opc) ||
4104 ParseTypeAndValue(LHS, Loc, PFS) ||
4105 ParseToken(lltok::comma, "expected ',' after compare value") ||
4106 ParseValue(LHS->getType(), RHS, PFS))
4109 if (Opc == Instruction::FCmp) {
4110 if (!LHS->getType()->isFPOrFPVectorTy())
4111 return Error(Loc, "fcmp requires floating point operands");
4112 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4114 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4115 if (!LHS->getType()->isIntOrIntVectorTy() &&
4116 !LHS->getType()->getScalarType()->isPointerTy())
4117 return Error(Loc, "icmp requires integer operands");
4118 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4123 //===----------------------------------------------------------------------===//
4124 // Other Instructions.
4125 //===----------------------------------------------------------------------===//
4129 /// ::= CastOpc TypeAndValue 'to' Type
4130 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4134 Type *DestTy = nullptr;
4135 if (ParseTypeAndValue(Op, Loc, PFS) ||
4136 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4140 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4141 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4142 return Error(Loc, "invalid cast opcode for cast from '" +
4143 getTypeString(Op->getType()) + "' to '" +
4144 getTypeString(DestTy) + "'");
4146 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4151 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4152 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4154 Value *Op0, *Op1, *Op2;
4155 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4156 ParseToken(lltok::comma, "expected ',' after select condition") ||
4157 ParseTypeAndValue(Op1, PFS) ||
4158 ParseToken(lltok::comma, "expected ',' after select value") ||
4159 ParseTypeAndValue(Op2, PFS))
4162 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4163 return Error(Loc, Reason);
4165 Inst = SelectInst::Create(Op0, Op1, Op2);
4170 /// ::= 'va_arg' TypeAndValue ',' Type
4171 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4173 Type *EltTy = nullptr;
4175 if (ParseTypeAndValue(Op, PFS) ||
4176 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4177 ParseType(EltTy, TypeLoc))
4180 if (!EltTy->isFirstClassType())
4181 return Error(TypeLoc, "va_arg requires operand with first class type");
4183 Inst = new VAArgInst(Op, EltTy);
4187 /// ParseExtractElement
4188 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4189 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4192 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4193 ParseToken(lltok::comma, "expected ',' after extract value") ||
4194 ParseTypeAndValue(Op1, PFS))
4197 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4198 return Error(Loc, "invalid extractelement operands");
4200 Inst = ExtractElementInst::Create(Op0, Op1);
4204 /// ParseInsertElement
4205 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4206 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4208 Value *Op0, *Op1, *Op2;
4209 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4210 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4211 ParseTypeAndValue(Op1, PFS) ||
4212 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4213 ParseTypeAndValue(Op2, PFS))
4216 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4217 return Error(Loc, "invalid insertelement operands");
4219 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4223 /// ParseShuffleVector
4224 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4225 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4227 Value *Op0, *Op1, *Op2;
4228 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4229 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4230 ParseTypeAndValue(Op1, PFS) ||
4231 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4232 ParseTypeAndValue(Op2, PFS))
4235 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4236 return Error(Loc, "invalid shufflevector operands");
4238 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4243 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4244 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4245 Type *Ty = nullptr; LocTy TypeLoc;
4248 if (ParseType(Ty, TypeLoc) ||
4249 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4250 ParseValue(Ty, Op0, PFS) ||
4251 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4252 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4253 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4256 bool AteExtraComma = false;
4257 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4259 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4261 if (!EatIfPresent(lltok::comma))
4264 if (Lex.getKind() == lltok::MetadataVar) {
4265 AteExtraComma = true;
4269 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4270 ParseValue(Ty, Op0, PFS) ||
4271 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4272 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4273 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4277 if (!Ty->isFirstClassType())
4278 return Error(TypeLoc, "phi node must have first class type");
4280 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4281 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4282 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4284 return AteExtraComma ? InstExtraComma : InstNormal;
4288 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4290 /// ::= 'catch' TypeAndValue
4292 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4293 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4294 Type *Ty = nullptr; LocTy TyLoc;
4295 Value *PersFn; LocTy PersFnLoc;
4297 if (ParseType(Ty, TyLoc) ||
4298 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4299 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4302 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4303 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4305 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4306 LandingPadInst::ClauseType CT;
4307 if (EatIfPresent(lltok::kw_catch))
4308 CT = LandingPadInst::Catch;
4309 else if (EatIfPresent(lltok::kw_filter))
4310 CT = LandingPadInst::Filter;
4312 return TokError("expected 'catch' or 'filter' clause type");
4316 if (ParseTypeAndValue(V, VLoc, PFS)) {
4321 // A 'catch' type expects a non-array constant. A filter clause expects an
4323 if (CT == LandingPadInst::Catch) {
4324 if (isa<ArrayType>(V->getType()))
4325 Error(VLoc, "'catch' clause has an invalid type");
4327 if (!isa<ArrayType>(V->getType()))
4328 Error(VLoc, "'filter' clause has an invalid type");
4331 LP->addClause(cast<Constant>(V));
4339 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4340 /// ParameterList OptionalAttrs
4341 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4342 /// ParameterList OptionalAttrs
4343 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4344 /// ParameterList OptionalAttrs
4345 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4346 CallInst::TailCallKind TCK) {
4347 AttrBuilder RetAttrs, FnAttrs;
4348 std::vector<unsigned> FwdRefAttrGrps;
4351 Type *RetType = nullptr;
4354 SmallVector<ParamInfo, 16> ArgList;
4355 LocTy CallLoc = Lex.getLoc();
4357 if ((TCK != CallInst::TCK_None &&
4358 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4359 ParseOptionalCallingConv(CC) ||
4360 ParseOptionalReturnAttrs(RetAttrs) ||
4361 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4362 ParseValID(CalleeID) ||
4363 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
4364 PFS.getFunction().isVarArg()) ||
4365 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4369 // If RetType is a non-function pointer type, then this is the short syntax
4370 // for the call, which means that RetType is just the return type. Infer the
4371 // rest of the function argument types from the arguments that are present.
4372 PointerType *PFTy = nullptr;
4373 FunctionType *Ty = nullptr;
4374 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4375 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4376 // Pull out the types of all of the arguments...
4377 std::vector<Type*> ParamTypes;
4378 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4379 ParamTypes.push_back(ArgList[i].V->getType());
4381 if (!FunctionType::isValidReturnType(RetType))
4382 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4384 Ty = FunctionType::get(RetType, ParamTypes, false);
4385 PFTy = PointerType::getUnqual(Ty);
4388 // Look up the callee.
4390 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4392 // Set up the Attribute for the function.
4393 SmallVector<AttributeSet, 8> Attrs;
4394 if (RetAttrs.hasAttributes())
4395 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4396 AttributeSet::ReturnIndex,
4399 SmallVector<Value*, 8> Args;
4401 // Loop through FunctionType's arguments and ensure they are specified
4402 // correctly. Also, gather any parameter attributes.
4403 FunctionType::param_iterator I = Ty->param_begin();
4404 FunctionType::param_iterator E = Ty->param_end();
4405 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4406 Type *ExpectedTy = nullptr;
4409 } else if (!Ty->isVarArg()) {
4410 return Error(ArgList[i].Loc, "too many arguments specified");
4413 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4414 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4415 getTypeString(ExpectedTy) + "'");
4416 Args.push_back(ArgList[i].V);
4417 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4418 AttrBuilder B(ArgList[i].Attrs, i + 1);
4419 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4424 return Error(CallLoc, "not enough parameters specified for call");
4426 if (FnAttrs.hasAttributes())
4427 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4428 AttributeSet::FunctionIndex,
4431 // Finish off the Attribute and check them
4432 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4434 CallInst *CI = CallInst::Create(Callee, Args);
4435 CI->setTailCallKind(TCK);
4436 CI->setCallingConv(CC);
4437 CI->setAttributes(PAL);
4438 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4443 //===----------------------------------------------------------------------===//
4444 // Memory Instructions.
4445 //===----------------------------------------------------------------------===//
4448 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4449 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4450 Value *Size = nullptr;
4452 unsigned Alignment = 0;
4455 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4457 if (ParseType(Ty)) return true;
4459 bool AteExtraComma = false;
4460 if (EatIfPresent(lltok::comma)) {
4461 if (Lex.getKind() == lltok::kw_align) {
4462 if (ParseOptionalAlignment(Alignment)) return true;
4463 } else if (Lex.getKind() == lltok::MetadataVar) {
4464 AteExtraComma = true;
4466 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4467 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4472 if (Size && !Size->getType()->isIntegerTy())
4473 return Error(SizeLoc, "element count must have integer type");
4475 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4476 AI->setUsedWithInAlloca(IsInAlloca);
4478 return AteExtraComma ? InstExtraComma : InstNormal;
4482 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4483 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4484 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4485 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4486 Value *Val; LocTy Loc;
4487 unsigned Alignment = 0;
4488 bool AteExtraComma = false;
4489 bool isAtomic = false;
4490 AtomicOrdering Ordering = NotAtomic;
4491 SynchronizationScope Scope = CrossThread;
4493 if (Lex.getKind() == lltok::kw_atomic) {
4498 bool isVolatile = false;
4499 if (Lex.getKind() == lltok::kw_volatile) {
4504 if (ParseTypeAndValue(Val, Loc, PFS) ||
4505 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4506 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4509 if (!Val->getType()->isPointerTy() ||
4510 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4511 return Error(Loc, "load operand must be a pointer to a first class type");
4512 if (isAtomic && !Alignment)
4513 return Error(Loc, "atomic load must have explicit non-zero alignment");
4514 if (Ordering == Release || Ordering == AcquireRelease)
4515 return Error(Loc, "atomic load cannot use Release ordering");
4517 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4518 return AteExtraComma ? InstExtraComma : InstNormal;
4523 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4524 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4525 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4526 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4527 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4528 unsigned Alignment = 0;
4529 bool AteExtraComma = false;
4530 bool isAtomic = false;
4531 AtomicOrdering Ordering = NotAtomic;
4532 SynchronizationScope Scope = CrossThread;
4534 if (Lex.getKind() == lltok::kw_atomic) {
4539 bool isVolatile = false;
4540 if (Lex.getKind() == lltok::kw_volatile) {
4545 if (ParseTypeAndValue(Val, Loc, PFS) ||
4546 ParseToken(lltok::comma, "expected ',' after store operand") ||
4547 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4548 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4549 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4552 if (!Ptr->getType()->isPointerTy())
4553 return Error(PtrLoc, "store operand must be a pointer");
4554 if (!Val->getType()->isFirstClassType())
4555 return Error(Loc, "store operand must be a first class value");
4556 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4557 return Error(Loc, "stored value and pointer type do not match");
4558 if (isAtomic && !Alignment)
4559 return Error(Loc, "atomic store must have explicit non-zero alignment");
4560 if (Ordering == Acquire || Ordering == AcquireRelease)
4561 return Error(Loc, "atomic store cannot use Acquire ordering");
4563 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4564 return AteExtraComma ? InstExtraComma : InstNormal;
4568 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4569 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4570 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4571 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4572 bool AteExtraComma = false;
4573 AtomicOrdering SuccessOrdering = NotAtomic;
4574 AtomicOrdering FailureOrdering = NotAtomic;
4575 SynchronizationScope Scope = CrossThread;
4576 bool isVolatile = false;
4577 bool isWeak = false;
4579 if (EatIfPresent(lltok::kw_weak))
4582 if (EatIfPresent(lltok::kw_volatile))
4585 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4586 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4587 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4588 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4589 ParseTypeAndValue(New, NewLoc, PFS) ||
4590 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4591 ParseOrdering(FailureOrdering))
4594 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4595 return TokError("cmpxchg cannot be unordered");
4596 if (SuccessOrdering < FailureOrdering)
4597 return TokError("cmpxchg must be at least as ordered on success as failure");
4598 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4599 return TokError("cmpxchg failure ordering cannot include release semantics");
4600 if (!Ptr->getType()->isPointerTy())
4601 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4602 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4603 return Error(CmpLoc, "compare value and pointer type do not match");
4604 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4605 return Error(NewLoc, "new value and pointer type do not match");
4606 if (!New->getType()->isIntegerTy())
4607 return Error(NewLoc, "cmpxchg operand must be an integer");
4608 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4609 if (Size < 8 || (Size & (Size - 1)))
4610 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4613 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4614 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4615 CXI->setVolatile(isVolatile);
4616 CXI->setWeak(isWeak);
4618 return AteExtraComma ? InstExtraComma : InstNormal;
4622 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4623 /// 'singlethread'? AtomicOrdering
4624 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4625 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4626 bool AteExtraComma = false;
4627 AtomicOrdering Ordering = NotAtomic;
4628 SynchronizationScope Scope = CrossThread;
4629 bool isVolatile = false;
4630 AtomicRMWInst::BinOp Operation;
4632 if (EatIfPresent(lltok::kw_volatile))
4635 switch (Lex.getKind()) {
4636 default: return TokError("expected binary operation in atomicrmw");
4637 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4638 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4639 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4640 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4641 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4642 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4643 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4644 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4645 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4646 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4647 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4649 Lex.Lex(); // Eat the operation.
4651 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4652 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4653 ParseTypeAndValue(Val, ValLoc, PFS) ||
4654 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4657 if (Ordering == Unordered)
4658 return TokError("atomicrmw cannot be unordered");
4659 if (!Ptr->getType()->isPointerTy())
4660 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4661 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4662 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4663 if (!Val->getType()->isIntegerTy())
4664 return Error(ValLoc, "atomicrmw operand must be an integer");
4665 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4666 if (Size < 8 || (Size & (Size - 1)))
4667 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4670 AtomicRMWInst *RMWI =
4671 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4672 RMWI->setVolatile(isVolatile);
4674 return AteExtraComma ? InstExtraComma : InstNormal;
4678 /// ::= 'fence' 'singlethread'? AtomicOrdering
4679 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4680 AtomicOrdering Ordering = NotAtomic;
4681 SynchronizationScope Scope = CrossThread;
4682 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4685 if (Ordering == Unordered)
4686 return TokError("fence cannot be unordered");
4687 if (Ordering == Monotonic)
4688 return TokError("fence cannot be monotonic");
4690 Inst = new FenceInst(Context, Ordering, Scope);
4694 /// ParseGetElementPtr
4695 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4696 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4697 Value *Ptr = nullptr;
4698 Value *Val = nullptr;
4701 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4703 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4705 Type *BaseType = Ptr->getType();
4706 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4707 if (!BasePointerType)
4708 return Error(Loc, "base of getelementptr must be a pointer");
4710 SmallVector<Value*, 16> Indices;
4711 bool AteExtraComma = false;
4712 while (EatIfPresent(lltok::comma)) {
4713 if (Lex.getKind() == lltok::MetadataVar) {
4714 AteExtraComma = true;
4717 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4718 if (!Val->getType()->getScalarType()->isIntegerTy())
4719 return Error(EltLoc, "getelementptr index must be an integer");
4720 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4721 return Error(EltLoc, "getelementptr index type missmatch");
4722 if (Val->getType()->isVectorTy()) {
4723 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4724 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4725 if (ValNumEl != PtrNumEl)
4726 return Error(EltLoc,
4727 "getelementptr vector index has a wrong number of elements");
4729 Indices.push_back(Val);
4732 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4733 return Error(Loc, "base element of getelementptr must be sized");
4735 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4736 return Error(Loc, "invalid getelementptr indices");
4737 Inst = GetElementPtrInst::Create(Ptr, Indices);
4739 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4740 return AteExtraComma ? InstExtraComma : InstNormal;
4743 /// ParseExtractValue
4744 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4745 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4746 Value *Val; LocTy Loc;
4747 SmallVector<unsigned, 4> Indices;
4749 if (ParseTypeAndValue(Val, Loc, PFS) ||
4750 ParseIndexList(Indices, AteExtraComma))
4753 if (!Val->getType()->isAggregateType())
4754 return Error(Loc, "extractvalue operand must be aggregate type");
4756 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4757 return Error(Loc, "invalid indices for extractvalue");
4758 Inst = ExtractValueInst::Create(Val, Indices);
4759 return AteExtraComma ? InstExtraComma : InstNormal;
4762 /// ParseInsertValue
4763 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4764 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4765 Value *Val0, *Val1; LocTy Loc0, Loc1;
4766 SmallVector<unsigned, 4> Indices;
4768 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4769 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4770 ParseTypeAndValue(Val1, Loc1, PFS) ||
4771 ParseIndexList(Indices, AteExtraComma))
4774 if (!Val0->getType()->isAggregateType())
4775 return Error(Loc0, "insertvalue operand must be aggregate type");
4777 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4778 return Error(Loc0, "invalid indices for insertvalue");
4779 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4780 return AteExtraComma ? InstExtraComma : InstNormal;
4783 //===----------------------------------------------------------------------===//
4784 // Embedded metadata.
4785 //===----------------------------------------------------------------------===//
4787 /// ParseMDNodeVector
4788 /// ::= { Element (',' Element)* }
4790 /// ::= 'null' | TypeAndValue
4791 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
4792 if (ParseToken(lltok::lbrace, "expected '{' here"))
4795 // Check for an empty list.
4796 if (EatIfPresent(lltok::rbrace))
4800 // Null is a special case since it is typeless.
4801 if (EatIfPresent(lltok::kw_null)) {
4802 Elts.push_back(nullptr);
4807 if (ParseMetadata(MD, nullptr))
4810 } while (EatIfPresent(lltok::comma));
4812 return ParseToken(lltok::rbrace, "expected end of metadata node");
4815 //===----------------------------------------------------------------------===//
4816 // Use-list order directives.
4817 //===----------------------------------------------------------------------===//
4818 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
4821 return Error(Loc, "value has no uses");
4823 unsigned NumUses = 0;
4824 SmallDenseMap<const Use *, unsigned, 16> Order;
4825 for (const Use &U : V->uses()) {
4826 if (++NumUses > Indexes.size())
4828 Order[&U] = Indexes[NumUses - 1];
4831 return Error(Loc, "value only has one use");
4832 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
4833 return Error(Loc, "wrong number of indexes, expected " +
4834 Twine(std::distance(V->use_begin(), V->use_end())));
4836 V->sortUseList([&](const Use &L, const Use &R) {
4837 return Order.lookup(&L) < Order.lookup(&R);
4842 /// ParseUseListOrderIndexes
4843 /// ::= '{' uint32 (',' uint32)+ '}'
4844 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
4845 SMLoc Loc = Lex.getLoc();
4846 if (ParseToken(lltok::lbrace, "expected '{' here"))
4848 if (Lex.getKind() == lltok::rbrace)
4849 return Lex.Error("expected non-empty list of uselistorder indexes");
4851 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
4852 // indexes should be distinct numbers in the range [0, size-1], and should
4854 unsigned Offset = 0;
4856 bool IsOrdered = true;
4857 assert(Indexes.empty() && "Expected empty order vector");
4860 if (ParseUInt32(Index))
4863 // Update consistency checks.
4864 Offset += Index - Indexes.size();
4865 Max = std::max(Max, Index);
4866 IsOrdered &= Index == Indexes.size();
4868 Indexes.push_back(Index);
4869 } while (EatIfPresent(lltok::comma));
4871 if (ParseToken(lltok::rbrace, "expected '}' here"))
4874 if (Indexes.size() < 2)
4875 return Error(Loc, "expected >= 2 uselistorder indexes");
4876 if (Offset != 0 || Max >= Indexes.size())
4877 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
4879 return Error(Loc, "expected uselistorder indexes to change the order");
4884 /// ParseUseListOrder
4885 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
4886 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
4887 SMLoc Loc = Lex.getLoc();
4888 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
4892 SmallVector<unsigned, 16> Indexes;
4893 if (ParseTypeAndValue(V, PFS) ||
4894 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
4895 ParseUseListOrderIndexes(Indexes))
4898 return sortUseListOrder(V, Indexes, Loc);
4901 /// ParseUseListOrderBB
4902 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
4903 bool LLParser::ParseUseListOrderBB() {
4904 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
4905 SMLoc Loc = Lex.getLoc();
4909 SmallVector<unsigned, 16> Indexes;
4910 if (ParseValID(Fn) ||
4911 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4912 ParseValID(Label) ||
4913 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
4914 ParseUseListOrderIndexes(Indexes))
4917 // Check the function.
4919 if (Fn.Kind == ValID::t_GlobalName)
4920 GV = M->getNamedValue(Fn.StrVal);
4921 else if (Fn.Kind == ValID::t_GlobalID)
4922 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
4924 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4926 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
4927 auto *F = dyn_cast<Function>(GV);
4929 return Error(Fn.Loc, "expected function name in uselistorder_bb");
4930 if (F->isDeclaration())
4931 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
4933 // Check the basic block.
4934 if (Label.Kind == ValID::t_LocalID)
4935 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
4936 if (Label.Kind != ValID::t_LocalName)
4937 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
4938 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
4940 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
4941 if (!isa<BasicBlock>(V))
4942 return Error(Label.Loc, "expected basic block in uselistorder_bb");
4944 return sortUseListOrder(V, Indexes, Loc);