1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/InlineAsm.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/ValueSymbolTable.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/SaveAndRestore.h"
30 #include "llvm/Support/raw_ostream.h"
33 static std::string getTypeString(Type *T) {
35 raw_string_ostream Tmp(Result);
40 /// Run: module ::= toplevelentity*
41 bool LLParser::Run() {
45 return ParseTopLevelEntities() ||
46 ValidateEndOfModule();
49 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51 bool LLParser::ValidateEndOfModule() {
52 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
53 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55 // Handle any function attribute group forward references.
56 for (std::map<Value*, std::vector<unsigned> >::iterator
57 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
60 std::vector<unsigned> &Vec = I->second;
63 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65 B.merge(NumberedAttrBuilders[*VI]);
67 if (Function *Fn = dyn_cast<Function>(V)) {
68 AttributeSet AS = Fn->getAttributes();
69 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
70 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
71 AS.getFnAttributes());
75 // If the alignment was parsed as an attribute, move to the alignment
77 if (FnAttrs.hasAlignmentAttr()) {
78 Fn->setAlignment(FnAttrs.getAlignment());
79 FnAttrs.removeAttribute(Attribute::Alignment);
82 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
83 AttributeSet::get(Context,
84 AttributeSet::FunctionIndex,
86 Fn->setAttributes(AS);
87 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
88 AttributeSet AS = CI->getAttributes();
89 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
90 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
91 AS.getFnAttributes());
93 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
94 AttributeSet::get(Context,
95 AttributeSet::FunctionIndex,
97 CI->setAttributes(AS);
98 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
99 AttributeSet AS = II->getAttributes();
100 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
101 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
102 AS.getFnAttributes());
104 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
105 AttributeSet::get(Context,
106 AttributeSet::FunctionIndex,
108 II->setAttributes(AS);
110 llvm_unreachable("invalid object with forward attribute group reference");
114 // If there are entries in ForwardRefBlockAddresses at this point, the
115 // function was never defined.
116 if (!ForwardRefBlockAddresses.empty())
117 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
118 "expected function name in blockaddress");
120 for (const auto &NT : NumberedTypes)
121 if (NT.second.second.isValid())
122 return Error(NT.second.second,
123 "use of undefined type '%" + Twine(NT.first) + "'");
125 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
126 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
127 if (I->second.second.isValid())
128 return Error(I->second.second,
129 "use of undefined type named '" + I->getKey() + "'");
131 if (!ForwardRefComdats.empty())
132 return Error(ForwardRefComdats.begin()->second,
133 "use of undefined comdat '$" +
134 ForwardRefComdats.begin()->first + "'");
136 if (!ForwardRefVals.empty())
137 return Error(ForwardRefVals.begin()->second.second,
138 "use of undefined value '@" + ForwardRefVals.begin()->first +
141 if (!ForwardRefValIDs.empty())
142 return Error(ForwardRefValIDs.begin()->second.second,
143 "use of undefined value '@" +
144 Twine(ForwardRefValIDs.begin()->first) + "'");
146 if (!ForwardRefMDNodes.empty())
147 return Error(ForwardRefMDNodes.begin()->second.second,
148 "use of undefined metadata '!" +
149 Twine(ForwardRefMDNodes.begin()->first) + "'");
151 // Resolve metadata cycles.
152 for (auto &N : NumberedMetadata) {
153 if (N.second && !N.second->isResolved())
154 N.second->resolveCycles();
157 // Look for intrinsic functions and CallInst that need to be upgraded
158 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
159 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
161 UpgradeDebugInfo(*M);
166 //===----------------------------------------------------------------------===//
167 // Top-Level Entities
168 //===----------------------------------------------------------------------===//
170 bool LLParser::ParseTopLevelEntities() {
172 switch (Lex.getKind()) {
173 default: return TokError("expected top-level entity");
174 case lltok::Eof: return false;
175 case lltok::kw_declare: if (ParseDeclare()) return true; break;
176 case lltok::kw_define: if (ParseDefine()) return true; break;
177 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
178 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
179 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
180 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
181 case lltok::LocalVar: if (ParseNamedType()) return true; break;
182 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
183 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
184 case lltok::ComdatVar: if (parseComdat()) return true; break;
185 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
186 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
188 // The Global variable production with no name can have many different
189 // optional leading prefixes, the production is:
190 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
191 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
192 // ('constant'|'global') ...
193 case lltok::kw_private: // OptionalLinkage
194 case lltok::kw_internal: // OptionalLinkage
195 case lltok::kw_weak: // OptionalLinkage
196 case lltok::kw_weak_odr: // OptionalLinkage
197 case lltok::kw_linkonce: // OptionalLinkage
198 case lltok::kw_linkonce_odr: // OptionalLinkage
199 case lltok::kw_appending: // OptionalLinkage
200 case lltok::kw_common: // OptionalLinkage
201 case lltok::kw_extern_weak: // OptionalLinkage
202 case lltok::kw_external: // OptionalLinkage
203 case lltok::kw_default: // OptionalVisibility
204 case lltok::kw_hidden: // OptionalVisibility
205 case lltok::kw_protected: // OptionalVisibility
206 case lltok::kw_dllimport: // OptionalDLLStorageClass
207 case lltok::kw_dllexport: // OptionalDLLStorageClass
208 case lltok::kw_thread_local: // OptionalThreadLocal
209 case lltok::kw_addrspace: // OptionalAddrSpace
210 case lltok::kw_constant: // GlobalType
211 case lltok::kw_global: { // GlobalType
212 unsigned Linkage, Visibility, DLLStorageClass;
214 GlobalVariable::ThreadLocalMode TLM;
216 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
217 ParseOptionalVisibility(Visibility) ||
218 ParseOptionalDLLStorageClass(DLLStorageClass) ||
219 ParseOptionalThreadLocal(TLM) ||
220 parseOptionalUnnamedAddr(UnnamedAddr) ||
221 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
222 DLLStorageClass, TLM, UnnamedAddr))
227 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
228 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
229 case lltok::kw_uselistorder_bb:
230 if (ParseUseListOrderBB()) return true; break;
237 /// ::= 'module' 'asm' STRINGCONSTANT
238 bool LLParser::ParseModuleAsm() {
239 assert(Lex.getKind() == lltok::kw_module);
243 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
244 ParseStringConstant(AsmStr)) return true;
246 M->appendModuleInlineAsm(AsmStr);
251 /// ::= 'target' 'triple' '=' STRINGCONSTANT
252 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
253 bool LLParser::ParseTargetDefinition() {
254 assert(Lex.getKind() == lltok::kw_target);
257 default: return TokError("unknown target property");
258 case lltok::kw_triple:
260 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
261 ParseStringConstant(Str))
263 M->setTargetTriple(Str);
265 case lltok::kw_datalayout:
267 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
268 ParseStringConstant(Str))
270 M->setDataLayout(Str);
276 /// ::= 'deplibs' '=' '[' ']'
277 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
278 /// FIXME: Remove in 4.0. Currently parse, but ignore.
279 bool LLParser::ParseDepLibs() {
280 assert(Lex.getKind() == lltok::kw_deplibs);
282 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
283 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
286 if (EatIfPresent(lltok::rsquare))
291 if (ParseStringConstant(Str)) return true;
292 } while (EatIfPresent(lltok::comma));
294 return ParseToken(lltok::rsquare, "expected ']' at end of list");
297 /// ParseUnnamedType:
298 /// ::= LocalVarID '=' 'type' type
299 bool LLParser::ParseUnnamedType() {
300 LocTy TypeLoc = Lex.getLoc();
301 unsigned TypeID = Lex.getUIntVal();
302 Lex.Lex(); // eat LocalVarID;
304 if (ParseToken(lltok::equal, "expected '=' after name") ||
305 ParseToken(lltok::kw_type, "expected 'type' after '='"))
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 (NumberedMetadata.count(MID)) {
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 Result = FwdRef.first.get();
538 NumberedMetadata[MID].reset(Result);
542 /// ParseNamedMetadata:
543 /// !foo = !{ !1, !2 }
544 bool LLParser::ParseNamedMetadata() {
545 assert(Lex.getKind() == lltok::MetadataVar);
546 std::string Name = Lex.getStrVal();
549 if (ParseToken(lltok::equal, "expected '=' here") ||
550 ParseToken(lltok::exclaim, "Expected '!' here") ||
551 ParseToken(lltok::lbrace, "Expected '{' here"))
554 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
555 if (Lex.getKind() != lltok::rbrace)
557 if (ParseToken(lltok::exclaim, "Expected '!' here"))
561 if (ParseMDNodeID(N)) return true;
563 } while (EatIfPresent(lltok::comma));
565 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
571 /// ParseStandaloneMetadata:
573 bool LLParser::ParseStandaloneMetadata() {
574 assert(Lex.getKind() == lltok::exclaim);
576 unsigned MetadataID = 0;
579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here"))
583 // Detect common error, from old metadata syntax.
584 if (Lex.getKind() == lltok::Type)
585 return TokError("unexpected type in metadata definition");
587 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
588 if (Lex.getKind() == lltok::MetadataVar) {
589 if (ParseSpecializedMDNode(Init, IsDistinct))
591 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
592 ParseMDTuple(Init, IsDistinct))
595 // See if this was forward referenced, if so, handle it.
596 auto FI = ForwardRefMDNodes.find(MetadataID);
597 if (FI != ForwardRefMDNodes.end()) {
598 FI->second.first->replaceAllUsesWith(Init);
599 ForwardRefMDNodes.erase(FI);
601 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
603 if (NumberedMetadata.count(MetadataID))
604 return TokError("Metadata id is already used");
605 NumberedMetadata[MetadataID].reset(Init);
611 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
612 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
613 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
617 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
618 /// OptionalDLLStorageClass OptionalThreadLocal
619 /// OptionalUnNammedAddr 'alias' Aliasee
624 /// Everything through OptionalUnNammedAddr has already been parsed.
626 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
627 unsigned Visibility, unsigned DLLStorageClass,
628 GlobalVariable::ThreadLocalMode TLM,
630 assert(Lex.getKind() == lltok::kw_alias);
633 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
635 if(!GlobalAlias::isValidLinkage(Linkage))
636 return Error(NameLoc, "invalid linkage type for alias");
638 if (!isValidVisibilityForLinkage(Visibility, L))
639 return Error(NameLoc,
640 "symbol with local linkage must have default visibility");
643 LocTy AliaseeLoc = Lex.getLoc();
644 if (Lex.getKind() != lltok::kw_bitcast &&
645 Lex.getKind() != lltok::kw_getelementptr &&
646 Lex.getKind() != lltok::kw_addrspacecast &&
647 Lex.getKind() != lltok::kw_inttoptr) {
648 if (ParseGlobalTypeAndValue(Aliasee))
651 // The bitcast dest type is not present, it is implied by the dest type.
655 if (ID.Kind != ValID::t_Constant)
656 return Error(AliaseeLoc, "invalid aliasee");
657 Aliasee = ID.ConstantVal;
660 Type *AliaseeType = Aliasee->getType();
661 auto *PTy = dyn_cast<PointerType>(AliaseeType);
663 return Error(AliaseeLoc, "An alias must have pointer type");
664 Type *Ty = PTy->getElementType();
665 unsigned AddrSpace = PTy->getAddressSpace();
667 // Okay, create the alias but do not insert it into the module yet.
668 std::unique_ptr<GlobalAlias> GA(
669 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
670 Name, Aliasee, /*Parent*/ nullptr));
671 GA->setThreadLocalMode(TLM);
672 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
673 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
674 GA->setUnnamedAddr(UnnamedAddr);
676 // See if this value already exists in the symbol table. If so, it is either
677 // a redefinition or a definition of a forward reference.
678 if (GlobalValue *Val = M->getNamedValue(Name)) {
679 // See if this was a redefinition. If so, there is no entry in
681 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
682 I = ForwardRefVals.find(Name);
683 if (I == ForwardRefVals.end())
684 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
686 // Otherwise, this was a definition of forward ref. Verify that types
688 if (Val->getType() != GA->getType())
689 return Error(NameLoc,
690 "forward reference and definition of alias have different types");
692 // If they agree, just RAUW the old value with the alias and remove the
694 Val->replaceAllUsesWith(GA.get());
695 Val->eraseFromParent();
696 ForwardRefVals.erase(I);
699 // Insert into the module, we know its name won't collide now.
700 M->getAliasList().push_back(GA.get());
701 assert(GA->getName() == Name && "Should not be a name conflict!");
703 // The module owns this now
710 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
711 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
712 /// OptionalExternallyInitialized GlobalType Type Const
713 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
714 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
715 /// OptionalExternallyInitialized GlobalType Type Const
717 /// Everything up to and including OptionalUnNammedAddr has been parsed
720 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
721 unsigned Linkage, bool HasLinkage,
722 unsigned Visibility, unsigned DLLStorageClass,
723 GlobalVariable::ThreadLocalMode TLM,
725 if (!isValidVisibilityForLinkage(Visibility, Linkage))
726 return Error(NameLoc,
727 "symbol with local linkage must have default visibility");
730 bool IsConstant, IsExternallyInitialized;
731 LocTy IsExternallyInitializedLoc;
735 if (ParseOptionalAddrSpace(AddrSpace) ||
736 ParseOptionalToken(lltok::kw_externally_initialized,
737 IsExternallyInitialized,
738 &IsExternallyInitializedLoc) ||
739 ParseGlobalType(IsConstant) ||
740 ParseType(Ty, TyLoc))
743 // If the linkage is specified and is external, then no initializer is
745 Constant *Init = nullptr;
746 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
747 Linkage != GlobalValue::ExternalLinkage)) {
748 if (ParseGlobalValue(Ty, Init))
752 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
753 return Error(TyLoc, "invalid type for global variable");
755 GlobalValue *GVal = nullptr;
757 // See if the global was forward referenced, if so, use the global.
759 GVal = M->getNamedValue(Name);
761 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
762 return Error(NameLoc, "redefinition of global '@" + Name + "'");
765 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
766 I = ForwardRefValIDs.find(NumberedVals.size());
767 if (I != ForwardRefValIDs.end()) {
768 GVal = I->second.first;
769 ForwardRefValIDs.erase(I);
775 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
776 Name, nullptr, GlobalVariable::NotThreadLocal,
779 if (GVal->getType()->getElementType() != Ty)
781 "forward reference and definition of global have different types");
783 GV = cast<GlobalVariable>(GVal);
785 // Move the forward-reference to the correct spot in the module.
786 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
790 NumberedVals.push_back(GV);
792 // Set the parsed properties on the global.
794 GV->setInitializer(Init);
795 GV->setConstant(IsConstant);
796 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
797 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
798 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
799 GV->setExternallyInitialized(IsExternallyInitialized);
800 GV->setThreadLocalMode(TLM);
801 GV->setUnnamedAddr(UnnamedAddr);
803 // Parse attributes on the global.
804 while (Lex.getKind() == lltok::comma) {
807 if (Lex.getKind() == lltok::kw_section) {
809 GV->setSection(Lex.getStrVal());
810 if (ParseToken(lltok::StringConstant, "expected global section string"))
812 } else if (Lex.getKind() == lltok::kw_align) {
814 if (ParseOptionalAlignment(Alignment)) return true;
815 GV->setAlignment(Alignment);
818 if (parseOptionalComdat(Name, C))
823 return TokError("unknown global variable property!");
830 /// ParseUnnamedAttrGrp
831 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
832 bool LLParser::ParseUnnamedAttrGrp() {
833 assert(Lex.getKind() == lltok::kw_attributes);
834 LocTy AttrGrpLoc = Lex.getLoc();
837 if (Lex.getKind() != lltok::AttrGrpID)
838 return TokError("expected attribute group id");
840 unsigned VarID = Lex.getUIntVal();
841 std::vector<unsigned> unused;
845 if (ParseToken(lltok::equal, "expected '=' here") ||
846 ParseToken(lltok::lbrace, "expected '{' here") ||
847 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
849 ParseToken(lltok::rbrace, "expected end of attribute group"))
852 if (!NumberedAttrBuilders[VarID].hasAttributes())
853 return Error(AttrGrpLoc, "attribute group has no attributes");
858 /// ParseFnAttributeValuePairs
859 /// ::= <attr> | <attr> '=' <value>
860 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
861 std::vector<unsigned> &FwdRefAttrGrps,
862 bool inAttrGrp, LocTy &BuiltinLoc) {
863 bool HaveError = false;
868 lltok::Kind Token = Lex.getKind();
869 if (Token == lltok::kw_builtin)
870 BuiltinLoc = Lex.getLoc();
873 if (!inAttrGrp) return HaveError;
874 return Error(Lex.getLoc(), "unterminated attribute group");
879 case lltok::AttrGrpID: {
880 // Allow a function to reference an attribute group:
882 // define void @foo() #1 { ... }
886 "cannot have an attribute group reference in an attribute group");
888 unsigned AttrGrpNum = Lex.getUIntVal();
889 if (inAttrGrp) break;
891 // Save the reference to the attribute group. We'll fill it in later.
892 FwdRefAttrGrps.push_back(AttrGrpNum);
895 // Target-dependent attributes:
896 case lltok::StringConstant: {
897 std::string Attr = Lex.getStrVal();
900 if (EatIfPresent(lltok::equal) &&
901 ParseStringConstant(Val))
904 B.addAttribute(Attr, Val);
908 // Target-independent attributes:
909 case lltok::kw_align: {
910 // As a hack, we allow function alignment to be initially parsed as an
911 // attribute on a function declaration/definition or added to an attribute
912 // group and later moved to the alignment field.
916 if (ParseToken(lltok::equal, "expected '=' here") ||
917 ParseUInt32(Alignment))
920 if (ParseOptionalAlignment(Alignment))
923 B.addAlignmentAttr(Alignment);
926 case lltok::kw_alignstack: {
930 if (ParseToken(lltok::equal, "expected '=' here") ||
931 ParseUInt32(Alignment))
934 if (ParseOptionalStackAlignment(Alignment))
937 B.addStackAlignmentAttr(Alignment);
940 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
941 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
942 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
943 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
944 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
945 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
946 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
947 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
948 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
949 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
950 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
951 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
952 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
953 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
954 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
955 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
956 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
957 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
958 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
959 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
960 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
961 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
962 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
963 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
964 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
965 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
966 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
969 case lltok::kw_inreg:
970 case lltok::kw_signext:
971 case lltok::kw_zeroext:
974 "invalid use of attribute on a function");
976 case lltok::kw_byval:
977 case lltok::kw_dereferenceable:
978 case lltok::kw_inalloca:
980 case lltok::kw_noalias:
981 case lltok::kw_nocapture:
982 case lltok::kw_nonnull:
983 case lltok::kw_returned:
987 "invalid use of parameter-only attribute on a function");
995 //===----------------------------------------------------------------------===//
996 // GlobalValue Reference/Resolution Routines.
997 //===----------------------------------------------------------------------===//
999 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1000 /// forward reference record if needed. This can return null if the value
1001 /// exists but does not have the right type.
1002 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1004 PointerType *PTy = dyn_cast<PointerType>(Ty);
1006 Error(Loc, "global variable reference must have pointer type");
1010 // Look this name up in the normal function symbol table.
1012 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1014 // If this is a forward reference for the value, see if we already created a
1015 // forward ref record.
1017 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1018 I = ForwardRefVals.find(Name);
1019 if (I != ForwardRefVals.end())
1020 Val = I->second.first;
1023 // If we have the value in the symbol table or fwd-ref table, return it.
1025 if (Val->getType() == Ty) return Val;
1026 Error(Loc, "'@" + Name + "' defined with type '" +
1027 getTypeString(Val->getType()) + "'");
1031 // Otherwise, create a new forward reference for this value and remember it.
1032 GlobalValue *FwdVal;
1033 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1034 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1036 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1037 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1038 nullptr, GlobalVariable::NotThreadLocal,
1039 PTy->getAddressSpace());
1041 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1045 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1046 PointerType *PTy = dyn_cast<PointerType>(Ty);
1048 Error(Loc, "global variable reference must have pointer type");
1052 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1054 // If this is a forward reference for the value, see if we already created a
1055 // forward ref record.
1057 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1058 I = ForwardRefValIDs.find(ID);
1059 if (I != ForwardRefValIDs.end())
1060 Val = I->second.first;
1063 // If we have the value in the symbol table or fwd-ref table, return it.
1065 if (Val->getType() == Ty) return Val;
1066 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1067 getTypeString(Val->getType()) + "'");
1071 // Otherwise, create a new forward reference for this value and remember it.
1072 GlobalValue *FwdVal;
1073 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1074 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1076 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1077 GlobalValue::ExternalWeakLinkage, nullptr, "");
1079 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1084 //===----------------------------------------------------------------------===//
1085 // Comdat Reference/Resolution Routines.
1086 //===----------------------------------------------------------------------===//
1088 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1089 // Look this name up in the comdat symbol table.
1090 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1091 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1092 if (I != ComdatSymTab.end())
1095 // Otherwise, create a new forward reference for this value and remember it.
1096 Comdat *C = M->getOrInsertComdat(Name);
1097 ForwardRefComdats[Name] = Loc;
1102 //===----------------------------------------------------------------------===//
1104 //===----------------------------------------------------------------------===//
1106 /// ParseToken - If the current token has the specified kind, eat it and return
1107 /// success. Otherwise, emit the specified error and return failure.
1108 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1109 if (Lex.getKind() != T)
1110 return TokError(ErrMsg);
1115 /// ParseStringConstant
1116 /// ::= StringConstant
1117 bool LLParser::ParseStringConstant(std::string &Result) {
1118 if (Lex.getKind() != lltok::StringConstant)
1119 return TokError("expected string constant");
1120 Result = Lex.getStrVal();
1127 bool LLParser::ParseUInt32(unsigned &Val) {
1128 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1129 return TokError("expected integer");
1130 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1131 if (Val64 != unsigned(Val64))
1132 return TokError("expected 32-bit integer (too large)");
1140 bool LLParser::ParseUInt64(uint64_t &Val) {
1141 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1142 return TokError("expected integer");
1143 Val = Lex.getAPSIntVal().getLimitedValue();
1149 /// := 'localdynamic'
1150 /// := 'initialexec'
1152 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1153 switch (Lex.getKind()) {
1155 return TokError("expected localdynamic, initialexec or localexec");
1156 case lltok::kw_localdynamic:
1157 TLM = GlobalVariable::LocalDynamicTLSModel;
1159 case lltok::kw_initialexec:
1160 TLM = GlobalVariable::InitialExecTLSModel;
1162 case lltok::kw_localexec:
1163 TLM = GlobalVariable::LocalExecTLSModel;
1171 /// ParseOptionalThreadLocal
1173 /// := 'thread_local'
1174 /// := 'thread_local' '(' tlsmodel ')'
1175 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1176 TLM = GlobalVariable::NotThreadLocal;
1177 if (!EatIfPresent(lltok::kw_thread_local))
1180 TLM = GlobalVariable::GeneralDynamicTLSModel;
1181 if (Lex.getKind() == lltok::lparen) {
1183 return ParseTLSModel(TLM) ||
1184 ParseToken(lltok::rparen, "expected ')' after thread local model");
1189 /// ParseOptionalAddrSpace
1191 /// := 'addrspace' '(' uint32 ')'
1192 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1194 if (!EatIfPresent(lltok::kw_addrspace))
1196 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1197 ParseUInt32(AddrSpace) ||
1198 ParseToken(lltok::rparen, "expected ')' in address space");
1201 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1202 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1203 bool HaveError = false;
1208 lltok::Kind Token = Lex.getKind();
1210 default: // End of attributes.
1212 case lltok::kw_align: {
1214 if (ParseOptionalAlignment(Alignment))
1216 B.addAlignmentAttr(Alignment);
1219 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1220 case lltok::kw_dereferenceable: {
1222 if (ParseOptionalDereferenceableBytes(Bytes))
1224 B.addDereferenceableAttr(Bytes);
1227 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1228 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1229 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1230 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1231 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1232 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1233 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1234 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1235 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1236 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1237 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1238 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1240 case lltok::kw_alignstack:
1241 case lltok::kw_alwaysinline:
1242 case lltok::kw_builtin:
1243 case lltok::kw_inlinehint:
1244 case lltok::kw_jumptable:
1245 case lltok::kw_minsize:
1246 case lltok::kw_naked:
1247 case lltok::kw_nobuiltin:
1248 case lltok::kw_noduplicate:
1249 case lltok::kw_noimplicitfloat:
1250 case lltok::kw_noinline:
1251 case lltok::kw_nonlazybind:
1252 case lltok::kw_noredzone:
1253 case lltok::kw_noreturn:
1254 case lltok::kw_nounwind:
1255 case lltok::kw_optnone:
1256 case lltok::kw_optsize:
1257 case lltok::kw_returns_twice:
1258 case lltok::kw_sanitize_address:
1259 case lltok::kw_sanitize_memory:
1260 case lltok::kw_sanitize_thread:
1262 case lltok::kw_sspreq:
1263 case lltok::kw_sspstrong:
1264 case lltok::kw_uwtable:
1265 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1273 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1274 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1275 bool HaveError = false;
1280 lltok::Kind Token = Lex.getKind();
1282 default: // End of attributes.
1284 case lltok::kw_dereferenceable: {
1286 if (ParseOptionalDereferenceableBytes(Bytes))
1288 B.addDereferenceableAttr(Bytes);
1291 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1292 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1293 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1294 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1295 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1298 case lltok::kw_align:
1299 case lltok::kw_byval:
1300 case lltok::kw_inalloca:
1301 case lltok::kw_nest:
1302 case lltok::kw_nocapture:
1303 case lltok::kw_returned:
1304 case lltok::kw_sret:
1305 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1308 case lltok::kw_alignstack:
1309 case lltok::kw_alwaysinline:
1310 case lltok::kw_builtin:
1311 case lltok::kw_cold:
1312 case lltok::kw_inlinehint:
1313 case lltok::kw_jumptable:
1314 case lltok::kw_minsize:
1315 case lltok::kw_naked:
1316 case lltok::kw_nobuiltin:
1317 case lltok::kw_noduplicate:
1318 case lltok::kw_noimplicitfloat:
1319 case lltok::kw_noinline:
1320 case lltok::kw_nonlazybind:
1321 case lltok::kw_noredzone:
1322 case lltok::kw_noreturn:
1323 case lltok::kw_nounwind:
1324 case lltok::kw_optnone:
1325 case lltok::kw_optsize:
1326 case lltok::kw_returns_twice:
1327 case lltok::kw_sanitize_address:
1328 case lltok::kw_sanitize_memory:
1329 case lltok::kw_sanitize_thread:
1331 case lltok::kw_sspreq:
1332 case lltok::kw_sspstrong:
1333 case lltok::kw_uwtable:
1334 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1337 case lltok::kw_readnone:
1338 case lltok::kw_readonly:
1339 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1346 /// ParseOptionalLinkage
1353 /// ::= 'linkonce_odr'
1354 /// ::= 'available_externally'
1357 /// ::= 'extern_weak'
1359 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1361 switch (Lex.getKind()) {
1362 default: Res=GlobalValue::ExternalLinkage; return false;
1363 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1364 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1365 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1366 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1367 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1368 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1369 case lltok::kw_available_externally:
1370 Res = GlobalValue::AvailableExternallyLinkage;
1372 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1373 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1374 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1375 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1382 /// ParseOptionalVisibility
1388 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1389 switch (Lex.getKind()) {
1390 default: Res = GlobalValue::DefaultVisibility; return false;
1391 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1392 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1393 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1399 /// ParseOptionalDLLStorageClass
1404 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1405 switch (Lex.getKind()) {
1406 default: Res = GlobalValue::DefaultStorageClass; return false;
1407 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1408 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1414 /// ParseOptionalCallingConv
1418 /// ::= 'intel_ocl_bicc'
1420 /// ::= 'x86_stdcallcc'
1421 /// ::= 'x86_fastcallcc'
1422 /// ::= 'x86_thiscallcc'
1423 /// ::= 'x86_vectorcallcc'
1424 /// ::= 'arm_apcscc'
1425 /// ::= 'arm_aapcscc'
1426 /// ::= 'arm_aapcs_vfpcc'
1427 /// ::= 'msp430_intrcc'
1428 /// ::= 'ptx_kernel'
1429 /// ::= 'ptx_device'
1431 /// ::= 'spir_kernel'
1432 /// ::= 'x86_64_sysvcc'
1433 /// ::= 'x86_64_win64cc'
1434 /// ::= 'webkit_jscc'
1436 /// ::= 'preserve_mostcc'
1437 /// ::= 'preserve_allcc'
1441 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1442 switch (Lex.getKind()) {
1443 default: CC = CallingConv::C; return false;
1444 case lltok::kw_ccc: CC = CallingConv::C; break;
1445 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1446 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1447 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1448 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1449 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1450 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1451 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1452 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1453 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1454 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1455 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1456 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1457 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1458 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1459 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1460 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1461 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1462 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1463 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1464 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1465 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1466 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1467 case lltok::kw_cc: {
1469 return ParseUInt32(CC);
1477 /// ParseInstructionMetadata
1478 /// ::= !dbg !42 (',' !dbg !57)*
1479 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1480 PerFunctionState *PFS) {
1482 if (Lex.getKind() != lltok::MetadataVar)
1483 return TokError("expected metadata after comma");
1485 std::string Name = Lex.getStrVal();
1486 unsigned MDK = M->getMDKindID(Name);
1493 Inst->setMetadata(MDK, N);
1494 if (MDK == LLVMContext::MD_tbaa)
1495 InstsWithTBAATag.push_back(Inst);
1497 // If this is the end of the list, we're done.
1498 } while (EatIfPresent(lltok::comma));
1502 /// ParseOptionalAlignment
1505 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1507 if (!EatIfPresent(lltok::kw_align))
1509 LocTy AlignLoc = Lex.getLoc();
1510 if (ParseUInt32(Alignment)) return true;
1511 if (!isPowerOf2_32(Alignment))
1512 return Error(AlignLoc, "alignment is not a power of two");
1513 if (Alignment > Value::MaximumAlignment)
1514 return Error(AlignLoc, "huge alignments are not supported yet");
1518 /// ParseOptionalDereferenceableBytes
1520 /// ::= 'dereferenceable' '(' 4 ')'
1521 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1523 if (!EatIfPresent(lltok::kw_dereferenceable))
1525 LocTy ParenLoc = Lex.getLoc();
1526 if (!EatIfPresent(lltok::lparen))
1527 return Error(ParenLoc, "expected '('");
1528 LocTy DerefLoc = Lex.getLoc();
1529 if (ParseUInt64(Bytes)) return true;
1530 ParenLoc = Lex.getLoc();
1531 if (!EatIfPresent(lltok::rparen))
1532 return Error(ParenLoc, "expected ')'");
1534 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1538 /// ParseOptionalCommaAlign
1542 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1544 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1545 bool &AteExtraComma) {
1546 AteExtraComma = false;
1547 while (EatIfPresent(lltok::comma)) {
1548 // Metadata at the end is an early exit.
1549 if (Lex.getKind() == lltok::MetadataVar) {
1550 AteExtraComma = true;
1554 if (Lex.getKind() != lltok::kw_align)
1555 return Error(Lex.getLoc(), "expected metadata or 'align'");
1557 if (ParseOptionalAlignment(Alignment)) return true;
1563 /// ParseScopeAndOrdering
1564 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1567 /// This sets Scope and Ordering to the parsed values.
1568 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1569 AtomicOrdering &Ordering) {
1573 Scope = CrossThread;
1574 if (EatIfPresent(lltok::kw_singlethread))
1575 Scope = SingleThread;
1577 return ParseOrdering(Ordering);
1581 /// ::= AtomicOrdering
1583 /// This sets Ordering to the parsed value.
1584 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1585 switch (Lex.getKind()) {
1586 default: return TokError("Expected ordering on atomic instruction");
1587 case lltok::kw_unordered: Ordering = Unordered; break;
1588 case lltok::kw_monotonic: Ordering = Monotonic; break;
1589 case lltok::kw_acquire: Ordering = Acquire; break;
1590 case lltok::kw_release: Ordering = Release; break;
1591 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1592 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1598 /// ParseOptionalStackAlignment
1600 /// ::= 'alignstack' '(' 4 ')'
1601 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1603 if (!EatIfPresent(lltok::kw_alignstack))
1605 LocTy ParenLoc = Lex.getLoc();
1606 if (!EatIfPresent(lltok::lparen))
1607 return Error(ParenLoc, "expected '('");
1608 LocTy AlignLoc = Lex.getLoc();
1609 if (ParseUInt32(Alignment)) return true;
1610 ParenLoc = Lex.getLoc();
1611 if (!EatIfPresent(lltok::rparen))
1612 return Error(ParenLoc, "expected ')'");
1613 if (!isPowerOf2_32(Alignment))
1614 return Error(AlignLoc, "stack alignment is not a power of two");
1618 /// ParseIndexList - This parses the index list for an insert/extractvalue
1619 /// instruction. This sets AteExtraComma in the case where we eat an extra
1620 /// comma at the end of the line and find that it is followed by metadata.
1621 /// Clients that don't allow metadata can call the version of this function that
1622 /// only takes one argument.
1625 /// ::= (',' uint32)+
1627 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1628 bool &AteExtraComma) {
1629 AteExtraComma = false;
1631 if (Lex.getKind() != lltok::comma)
1632 return TokError("expected ',' as start of index list");
1634 while (EatIfPresent(lltok::comma)) {
1635 if (Lex.getKind() == lltok::MetadataVar) {
1636 if (Indices.empty()) return TokError("expected index");
1637 AteExtraComma = true;
1641 if (ParseUInt32(Idx)) return true;
1642 Indices.push_back(Idx);
1648 //===----------------------------------------------------------------------===//
1650 //===----------------------------------------------------------------------===//
1652 /// ParseType - Parse a type.
1653 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1654 SMLoc TypeLoc = Lex.getLoc();
1655 switch (Lex.getKind()) {
1657 return TokError(Msg);
1659 // Type ::= 'float' | 'void' (etc)
1660 Result = Lex.getTyVal();
1664 // Type ::= StructType
1665 if (ParseAnonStructType(Result, false))
1668 case lltok::lsquare:
1669 // Type ::= '[' ... ']'
1670 Lex.Lex(); // eat the lsquare.
1671 if (ParseArrayVectorType(Result, false))
1674 case lltok::less: // Either vector or packed struct.
1675 // Type ::= '<' ... '>'
1677 if (Lex.getKind() == lltok::lbrace) {
1678 if (ParseAnonStructType(Result, true) ||
1679 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1681 } else if (ParseArrayVectorType(Result, true))
1684 case lltok::LocalVar: {
1686 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1688 // If the type hasn't been defined yet, create a forward definition and
1689 // remember where that forward def'n was seen (in case it never is defined).
1691 Entry.first = StructType::create(Context, Lex.getStrVal());
1692 Entry.second = Lex.getLoc();
1694 Result = Entry.first;
1699 case lltok::LocalVarID: {
1701 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1703 // If the type hasn't been defined yet, create a forward definition and
1704 // remember where that forward def'n was seen (in case it never is defined).
1706 Entry.first = StructType::create(Context);
1707 Entry.second = Lex.getLoc();
1709 Result = Entry.first;
1715 // Parse the type suffixes.
1717 switch (Lex.getKind()) {
1720 if (!AllowVoid && Result->isVoidTy())
1721 return Error(TypeLoc, "void type only allowed for function results");
1724 // Type ::= Type '*'
1726 if (Result->isLabelTy())
1727 return TokError("basic block pointers are invalid");
1728 if (Result->isVoidTy())
1729 return TokError("pointers to void are invalid - use i8* instead");
1730 if (!PointerType::isValidElementType(Result))
1731 return TokError("pointer to this type is invalid");
1732 Result = PointerType::getUnqual(Result);
1736 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1737 case lltok::kw_addrspace: {
1738 if (Result->isLabelTy())
1739 return TokError("basic block pointers are invalid");
1740 if (Result->isVoidTy())
1741 return TokError("pointers to void are invalid; use i8* instead");
1742 if (!PointerType::isValidElementType(Result))
1743 return TokError("pointer to this type is invalid");
1745 if (ParseOptionalAddrSpace(AddrSpace) ||
1746 ParseToken(lltok::star, "expected '*' in address space"))
1749 Result = PointerType::get(Result, AddrSpace);
1753 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1755 if (ParseFunctionType(Result))
1762 /// ParseParameterList
1764 /// ::= '(' Arg (',' Arg)* ')'
1766 /// ::= Type OptionalAttributes Value OptionalAttributes
1767 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1768 PerFunctionState &PFS, bool IsMustTailCall,
1769 bool InVarArgsFunc) {
1770 if (ParseToken(lltok::lparen, "expected '(' in call"))
1773 unsigned AttrIndex = 1;
1774 while (Lex.getKind() != lltok::rparen) {
1775 // If this isn't the first argument, we need a comma.
1776 if (!ArgList.empty() &&
1777 ParseToken(lltok::comma, "expected ',' in argument list"))
1780 // Parse an ellipsis if this is a musttail call in a variadic function.
1781 if (Lex.getKind() == lltok::dotdotdot) {
1782 const char *Msg = "unexpected ellipsis in argument list for ";
1783 if (!IsMustTailCall)
1784 return TokError(Twine(Msg) + "non-musttail call");
1786 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1787 Lex.Lex(); // Lex the '...', it is purely for readability.
1788 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1791 // Parse the argument.
1793 Type *ArgTy = nullptr;
1794 AttrBuilder ArgAttrs;
1796 if (ParseType(ArgTy, ArgLoc))
1799 if (ArgTy->isMetadataTy()) {
1800 if (ParseMetadataAsValue(V, PFS))
1803 // Otherwise, handle normal operands.
1804 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1807 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1812 if (IsMustTailCall && InVarArgsFunc)
1813 return TokError("expected '...' at end of argument list for musttail call "
1814 "in varargs function");
1816 Lex.Lex(); // Lex the ')'.
1822 /// ParseArgumentList - Parse the argument list for a function type or function
1824 /// ::= '(' ArgTypeListI ')'
1828 /// ::= ArgTypeList ',' '...'
1829 /// ::= ArgType (',' ArgType)*
1831 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1834 assert(Lex.getKind() == lltok::lparen);
1835 Lex.Lex(); // eat the (.
1837 if (Lex.getKind() == lltok::rparen) {
1839 } else if (Lex.getKind() == lltok::dotdotdot) {
1843 LocTy TypeLoc = Lex.getLoc();
1844 Type *ArgTy = nullptr;
1848 if (ParseType(ArgTy) ||
1849 ParseOptionalParamAttrs(Attrs)) return true;
1851 if (ArgTy->isVoidTy())
1852 return Error(TypeLoc, "argument can not have void type");
1854 if (Lex.getKind() == lltok::LocalVar) {
1855 Name = Lex.getStrVal();
1859 if (!FunctionType::isValidArgumentType(ArgTy))
1860 return Error(TypeLoc, "invalid type for function argument");
1862 unsigned AttrIndex = 1;
1863 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1864 AttributeSet::get(ArgTy->getContext(),
1865 AttrIndex++, Attrs), Name));
1867 while (EatIfPresent(lltok::comma)) {
1868 // Handle ... at end of arg list.
1869 if (EatIfPresent(lltok::dotdotdot)) {
1874 // Otherwise must be an argument type.
1875 TypeLoc = Lex.getLoc();
1876 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1878 if (ArgTy->isVoidTy())
1879 return Error(TypeLoc, "argument can not have void type");
1881 if (Lex.getKind() == lltok::LocalVar) {
1882 Name = Lex.getStrVal();
1888 if (!ArgTy->isFirstClassType())
1889 return Error(TypeLoc, "invalid type for function argument");
1891 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1892 AttributeSet::get(ArgTy->getContext(),
1893 AttrIndex++, Attrs),
1898 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1901 /// ParseFunctionType
1902 /// ::= Type ArgumentList OptionalAttrs
1903 bool LLParser::ParseFunctionType(Type *&Result) {
1904 assert(Lex.getKind() == lltok::lparen);
1906 if (!FunctionType::isValidReturnType(Result))
1907 return TokError("invalid function return type");
1909 SmallVector<ArgInfo, 8> ArgList;
1911 if (ParseArgumentList(ArgList, isVarArg))
1914 // Reject names on the arguments lists.
1915 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1916 if (!ArgList[i].Name.empty())
1917 return Error(ArgList[i].Loc, "argument name invalid in function type");
1918 if (ArgList[i].Attrs.hasAttributes(i + 1))
1919 return Error(ArgList[i].Loc,
1920 "argument attributes invalid in function type");
1923 SmallVector<Type*, 16> ArgListTy;
1924 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1925 ArgListTy.push_back(ArgList[i].Ty);
1927 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1931 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1933 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1934 SmallVector<Type*, 8> Elts;
1935 if (ParseStructBody(Elts)) return true;
1937 Result = StructType::get(Context, Elts, Packed);
1941 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1942 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1943 std::pair<Type*, LocTy> &Entry,
1945 // If the type was already defined, diagnose the redefinition.
1946 if (Entry.first && !Entry.second.isValid())
1947 return Error(TypeLoc, "redefinition of type");
1949 // If we have opaque, just return without filling in the definition for the
1950 // struct. This counts as a definition as far as the .ll file goes.
1951 if (EatIfPresent(lltok::kw_opaque)) {
1952 // This type is being defined, so clear the location to indicate this.
1953 Entry.second = SMLoc();
1955 // If this type number has never been uttered, create it.
1957 Entry.first = StructType::create(Context, Name);
1958 ResultTy = Entry.first;
1962 // If the type starts with '<', then it is either a packed struct or a vector.
1963 bool isPacked = EatIfPresent(lltok::less);
1965 // If we don't have a struct, then we have a random type alias, which we
1966 // accept for compatibility with old files. These types are not allowed to be
1967 // forward referenced and not allowed to be recursive.
1968 if (Lex.getKind() != lltok::lbrace) {
1970 return Error(TypeLoc, "forward references to non-struct type");
1974 return ParseArrayVectorType(ResultTy, true);
1975 return ParseType(ResultTy);
1978 // This type is being defined, so clear the location to indicate this.
1979 Entry.second = SMLoc();
1981 // If this type number has never been uttered, create it.
1983 Entry.first = StructType::create(Context, Name);
1985 StructType *STy = cast<StructType>(Entry.first);
1987 SmallVector<Type*, 8> Body;
1988 if (ParseStructBody(Body) ||
1989 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1992 STy->setBody(Body, isPacked);
1998 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2001 /// ::= '{' Type (',' Type)* '}'
2002 /// ::= '<' '{' '}' '>'
2003 /// ::= '<' '{' Type (',' Type)* '}' '>'
2004 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2005 assert(Lex.getKind() == lltok::lbrace);
2006 Lex.Lex(); // Consume the '{'
2008 // Handle the empty struct.
2009 if (EatIfPresent(lltok::rbrace))
2012 LocTy EltTyLoc = Lex.getLoc();
2014 if (ParseType(Ty)) return true;
2017 if (!StructType::isValidElementType(Ty))
2018 return Error(EltTyLoc, "invalid element type for struct");
2020 while (EatIfPresent(lltok::comma)) {
2021 EltTyLoc = Lex.getLoc();
2022 if (ParseType(Ty)) return true;
2024 if (!StructType::isValidElementType(Ty))
2025 return Error(EltTyLoc, "invalid element type for struct");
2030 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2033 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2034 /// token has already been consumed.
2036 /// ::= '[' APSINTVAL 'x' Types ']'
2037 /// ::= '<' APSINTVAL 'x' Types '>'
2038 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2039 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2040 Lex.getAPSIntVal().getBitWidth() > 64)
2041 return TokError("expected number in address space");
2043 LocTy SizeLoc = Lex.getLoc();
2044 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2047 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2050 LocTy TypeLoc = Lex.getLoc();
2051 Type *EltTy = nullptr;
2052 if (ParseType(EltTy)) return true;
2054 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2055 "expected end of sequential type"))
2060 return Error(SizeLoc, "zero element vector is illegal");
2061 if ((unsigned)Size != Size)
2062 return Error(SizeLoc, "size too large for vector");
2063 if (!VectorType::isValidElementType(EltTy))
2064 return Error(TypeLoc, "invalid vector element type");
2065 Result = VectorType::get(EltTy, unsigned(Size));
2067 if (!ArrayType::isValidElementType(EltTy))
2068 return Error(TypeLoc, "invalid array element type");
2069 Result = ArrayType::get(EltTy, Size);
2074 //===----------------------------------------------------------------------===//
2075 // Function Semantic Analysis.
2076 //===----------------------------------------------------------------------===//
2078 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2080 : P(p), F(f), FunctionNumber(functionNumber) {
2082 // Insert unnamed arguments into the NumberedVals list.
2083 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2086 NumberedVals.push_back(AI);
2089 LLParser::PerFunctionState::~PerFunctionState() {
2090 // If there were any forward referenced non-basicblock values, delete them.
2091 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2092 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2093 if (!isa<BasicBlock>(I->second.first)) {
2094 I->second.first->replaceAllUsesWith(
2095 UndefValue::get(I->second.first->getType()));
2096 delete I->second.first;
2097 I->second.first = nullptr;
2100 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2101 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2102 if (!isa<BasicBlock>(I->second.first)) {
2103 I->second.first->replaceAllUsesWith(
2104 UndefValue::get(I->second.first->getType()));
2105 delete I->second.first;
2106 I->second.first = nullptr;
2110 bool LLParser::PerFunctionState::FinishFunction() {
2111 if (!ForwardRefVals.empty())
2112 return P.Error(ForwardRefVals.begin()->second.second,
2113 "use of undefined value '%" + ForwardRefVals.begin()->first +
2115 if (!ForwardRefValIDs.empty())
2116 return P.Error(ForwardRefValIDs.begin()->second.second,
2117 "use of undefined value '%" +
2118 Twine(ForwardRefValIDs.begin()->first) + "'");
2123 /// GetVal - Get a value with the specified name or ID, creating a
2124 /// forward reference record if needed. This can return null if the value
2125 /// exists but does not have the right type.
2126 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2127 Type *Ty, LocTy Loc) {
2128 // Look this name up in the normal function symbol table.
2129 Value *Val = F.getValueSymbolTable().lookup(Name);
2131 // If this is a forward reference for the value, see if we already created a
2132 // forward ref record.
2134 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2135 I = ForwardRefVals.find(Name);
2136 if (I != ForwardRefVals.end())
2137 Val = I->second.first;
2140 // If we have the value in the symbol table or fwd-ref table, return it.
2142 if (Val->getType() == Ty) return Val;
2143 if (Ty->isLabelTy())
2144 P.Error(Loc, "'%" + Name + "' is not a basic block");
2146 P.Error(Loc, "'%" + Name + "' defined with type '" +
2147 getTypeString(Val->getType()) + "'");
2151 // Don't make placeholders with invalid type.
2152 if (!Ty->isFirstClassType()) {
2153 P.Error(Loc, "invalid use of a non-first-class type");
2157 // Otherwise, create a new forward reference for this value and remember it.
2159 if (Ty->isLabelTy())
2160 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2162 FwdVal = new Argument(Ty, Name);
2164 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2168 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2170 // Look this name up in the normal function symbol table.
2171 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2173 // If this is a forward reference for the value, see if we already created a
2174 // forward ref record.
2176 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2177 I = ForwardRefValIDs.find(ID);
2178 if (I != ForwardRefValIDs.end())
2179 Val = I->second.first;
2182 // If we have the value in the symbol table or fwd-ref table, return it.
2184 if (Val->getType() == Ty) return Val;
2185 if (Ty->isLabelTy())
2186 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2188 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2189 getTypeString(Val->getType()) + "'");
2193 if (!Ty->isFirstClassType()) {
2194 P.Error(Loc, "invalid use of a non-first-class type");
2198 // Otherwise, create a new forward reference for this value and remember it.
2200 if (Ty->isLabelTy())
2201 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2203 FwdVal = new Argument(Ty);
2205 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2209 /// SetInstName - After an instruction is parsed and inserted into its
2210 /// basic block, this installs its name.
2211 bool LLParser::PerFunctionState::SetInstName(int NameID,
2212 const std::string &NameStr,
2213 LocTy NameLoc, Instruction *Inst) {
2214 // If this instruction has void type, it cannot have a name or ID specified.
2215 if (Inst->getType()->isVoidTy()) {
2216 if (NameID != -1 || !NameStr.empty())
2217 return P.Error(NameLoc, "instructions returning void cannot have a name");
2221 // If this was a numbered instruction, verify that the instruction is the
2222 // expected value and resolve any forward references.
2223 if (NameStr.empty()) {
2224 // If neither a name nor an ID was specified, just use the next ID.
2226 NameID = NumberedVals.size();
2228 if (unsigned(NameID) != NumberedVals.size())
2229 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2230 Twine(NumberedVals.size()) + "'");
2232 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2233 ForwardRefValIDs.find(NameID);
2234 if (FI != ForwardRefValIDs.end()) {
2235 if (FI->second.first->getType() != Inst->getType())
2236 return P.Error(NameLoc, "instruction forward referenced with type '" +
2237 getTypeString(FI->second.first->getType()) + "'");
2238 FI->second.first->replaceAllUsesWith(Inst);
2239 delete FI->second.first;
2240 ForwardRefValIDs.erase(FI);
2243 NumberedVals.push_back(Inst);
2247 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2248 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2249 FI = ForwardRefVals.find(NameStr);
2250 if (FI != ForwardRefVals.end()) {
2251 if (FI->second.first->getType() != Inst->getType())
2252 return P.Error(NameLoc, "instruction forward referenced with type '" +
2253 getTypeString(FI->second.first->getType()) + "'");
2254 FI->second.first->replaceAllUsesWith(Inst);
2255 delete FI->second.first;
2256 ForwardRefVals.erase(FI);
2259 // Set the name on the instruction.
2260 Inst->setName(NameStr);
2262 if (Inst->getName() != NameStr)
2263 return P.Error(NameLoc, "multiple definition of local value named '" +
2268 /// GetBB - Get a basic block with the specified name or ID, creating a
2269 /// forward reference record if needed.
2270 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2272 return cast_or_null<BasicBlock>(GetVal(Name,
2273 Type::getLabelTy(F.getContext()), Loc));
2276 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2277 return cast_or_null<BasicBlock>(GetVal(ID,
2278 Type::getLabelTy(F.getContext()), Loc));
2281 /// DefineBB - Define the specified basic block, which is either named or
2282 /// unnamed. If there is an error, this returns null otherwise it returns
2283 /// the block being defined.
2284 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2288 BB = GetBB(NumberedVals.size(), Loc);
2290 BB = GetBB(Name, Loc);
2291 if (!BB) return nullptr; // Already diagnosed error.
2293 // Move the block to the end of the function. Forward ref'd blocks are
2294 // inserted wherever they happen to be referenced.
2295 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2297 // Remove the block from forward ref sets.
2299 ForwardRefValIDs.erase(NumberedVals.size());
2300 NumberedVals.push_back(BB);
2302 // BB forward references are already in the function symbol table.
2303 ForwardRefVals.erase(Name);
2309 //===----------------------------------------------------------------------===//
2311 //===----------------------------------------------------------------------===//
2313 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2314 /// type implied. For example, if we parse "4" we don't know what integer type
2315 /// it has. The value will later be combined with its type and checked for
2316 /// sanity. PFS is used to convert function-local operands of metadata (since
2317 /// metadata operands are not just parsed here but also converted to values).
2318 /// PFS can be null when we are not parsing metadata values inside a function.
2319 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2320 ID.Loc = Lex.getLoc();
2321 switch (Lex.getKind()) {
2322 default: return TokError("expected value token");
2323 case lltok::GlobalID: // @42
2324 ID.UIntVal = Lex.getUIntVal();
2325 ID.Kind = ValID::t_GlobalID;
2327 case lltok::GlobalVar: // @foo
2328 ID.StrVal = Lex.getStrVal();
2329 ID.Kind = ValID::t_GlobalName;
2331 case lltok::LocalVarID: // %42
2332 ID.UIntVal = Lex.getUIntVal();
2333 ID.Kind = ValID::t_LocalID;
2335 case lltok::LocalVar: // %foo
2336 ID.StrVal = Lex.getStrVal();
2337 ID.Kind = ValID::t_LocalName;
2340 ID.APSIntVal = Lex.getAPSIntVal();
2341 ID.Kind = ValID::t_APSInt;
2343 case lltok::APFloat:
2344 ID.APFloatVal = Lex.getAPFloatVal();
2345 ID.Kind = ValID::t_APFloat;
2347 case lltok::kw_true:
2348 ID.ConstantVal = ConstantInt::getTrue(Context);
2349 ID.Kind = ValID::t_Constant;
2351 case lltok::kw_false:
2352 ID.ConstantVal = ConstantInt::getFalse(Context);
2353 ID.Kind = ValID::t_Constant;
2355 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2356 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2357 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2359 case lltok::lbrace: {
2360 // ValID ::= '{' ConstVector '}'
2362 SmallVector<Constant*, 16> Elts;
2363 if (ParseGlobalValueVector(Elts) ||
2364 ParseToken(lltok::rbrace, "expected end of struct constant"))
2367 ID.ConstantStructElts = new Constant*[Elts.size()];
2368 ID.UIntVal = Elts.size();
2369 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2370 ID.Kind = ValID::t_ConstantStruct;
2374 // ValID ::= '<' ConstVector '>' --> Vector.
2375 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2377 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2379 SmallVector<Constant*, 16> Elts;
2380 LocTy FirstEltLoc = Lex.getLoc();
2381 if (ParseGlobalValueVector(Elts) ||
2383 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2384 ParseToken(lltok::greater, "expected end of constant"))
2387 if (isPackedStruct) {
2388 ID.ConstantStructElts = new Constant*[Elts.size()];
2389 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2390 ID.UIntVal = Elts.size();
2391 ID.Kind = ValID::t_PackedConstantStruct;
2396 return Error(ID.Loc, "constant vector must not be empty");
2398 if (!Elts[0]->getType()->isIntegerTy() &&
2399 !Elts[0]->getType()->isFloatingPointTy() &&
2400 !Elts[0]->getType()->isPointerTy())
2401 return Error(FirstEltLoc,
2402 "vector elements must have integer, pointer or floating point type");
2404 // Verify that all the vector elements have the same type.
2405 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2406 if (Elts[i]->getType() != Elts[0]->getType())
2407 return Error(FirstEltLoc,
2408 "vector element #" + Twine(i) +
2409 " is not of type '" + getTypeString(Elts[0]->getType()));
2411 ID.ConstantVal = ConstantVector::get(Elts);
2412 ID.Kind = ValID::t_Constant;
2415 case lltok::lsquare: { // Array Constant
2417 SmallVector<Constant*, 16> Elts;
2418 LocTy FirstEltLoc = Lex.getLoc();
2419 if (ParseGlobalValueVector(Elts) ||
2420 ParseToken(lltok::rsquare, "expected end of array constant"))
2423 // Handle empty element.
2425 // Use undef instead of an array because it's inconvenient to determine
2426 // the element type at this point, there being no elements to examine.
2427 ID.Kind = ValID::t_EmptyArray;
2431 if (!Elts[0]->getType()->isFirstClassType())
2432 return Error(FirstEltLoc, "invalid array element type: " +
2433 getTypeString(Elts[0]->getType()));
2435 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2437 // Verify all elements are correct type!
2438 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2439 if (Elts[i]->getType() != Elts[0]->getType())
2440 return Error(FirstEltLoc,
2441 "array element #" + Twine(i) +
2442 " is not of type '" + getTypeString(Elts[0]->getType()));
2445 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2446 ID.Kind = ValID::t_Constant;
2449 case lltok::kw_c: // c "foo"
2451 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2453 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2454 ID.Kind = ValID::t_Constant;
2457 case lltok::kw_asm: {
2458 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2460 bool HasSideEffect, AlignStack, AsmDialect;
2462 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2463 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2464 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2465 ParseStringConstant(ID.StrVal) ||
2466 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2467 ParseToken(lltok::StringConstant, "expected constraint string"))
2469 ID.StrVal2 = Lex.getStrVal();
2470 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2471 (unsigned(AsmDialect)<<2);
2472 ID.Kind = ValID::t_InlineAsm;
2476 case lltok::kw_blockaddress: {
2477 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2482 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2484 ParseToken(lltok::comma, "expected comma in block address expression")||
2485 ParseValID(Label) ||
2486 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2489 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2490 return Error(Fn.Loc, "expected function name in blockaddress");
2491 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2492 return Error(Label.Loc, "expected basic block name in blockaddress");
2494 // Try to find the function (but skip it if it's forward-referenced).
2495 GlobalValue *GV = nullptr;
2496 if (Fn.Kind == ValID::t_GlobalID) {
2497 if (Fn.UIntVal < NumberedVals.size())
2498 GV = NumberedVals[Fn.UIntVal];
2499 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2500 GV = M->getNamedValue(Fn.StrVal);
2502 Function *F = nullptr;
2504 // Confirm that it's actually a function with a definition.
2505 if (!isa<Function>(GV))
2506 return Error(Fn.Loc, "expected function name in blockaddress");
2507 F = cast<Function>(GV);
2508 if (F->isDeclaration())
2509 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2513 // Make a global variable as a placeholder for this reference.
2514 GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
2516 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2517 GlobalValue::InternalLinkage, nullptr, "");
2518 ID.ConstantVal = FwdRef;
2519 ID.Kind = ValID::t_Constant;
2523 // We found the function; now find the basic block. Don't use PFS, since we
2524 // might be inside a constant expression.
2526 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2527 if (Label.Kind == ValID::t_LocalID)
2528 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2530 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2532 return Error(Label.Loc, "referenced value is not a basic block");
2534 if (Label.Kind == ValID::t_LocalID)
2535 return Error(Label.Loc, "cannot take address of numeric label after "
2536 "the function is defined");
2537 BB = dyn_cast_or_null<BasicBlock>(
2538 F->getValueSymbolTable().lookup(Label.StrVal));
2540 return Error(Label.Loc, "referenced value is not a basic block");
2543 ID.ConstantVal = BlockAddress::get(F, BB);
2544 ID.Kind = ValID::t_Constant;
2548 case lltok::kw_trunc:
2549 case lltok::kw_zext:
2550 case lltok::kw_sext:
2551 case lltok::kw_fptrunc:
2552 case lltok::kw_fpext:
2553 case lltok::kw_bitcast:
2554 case lltok::kw_addrspacecast:
2555 case lltok::kw_uitofp:
2556 case lltok::kw_sitofp:
2557 case lltok::kw_fptoui:
2558 case lltok::kw_fptosi:
2559 case lltok::kw_inttoptr:
2560 case lltok::kw_ptrtoint: {
2561 unsigned Opc = Lex.getUIntVal();
2562 Type *DestTy = nullptr;
2565 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2566 ParseGlobalTypeAndValue(SrcVal) ||
2567 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2568 ParseType(DestTy) ||
2569 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2571 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2572 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2573 getTypeString(SrcVal->getType()) + "' to '" +
2574 getTypeString(DestTy) + "'");
2575 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2577 ID.Kind = ValID::t_Constant;
2580 case lltok::kw_extractvalue: {
2583 SmallVector<unsigned, 4> Indices;
2584 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2585 ParseGlobalTypeAndValue(Val) ||
2586 ParseIndexList(Indices) ||
2587 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2590 if (!Val->getType()->isAggregateType())
2591 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2592 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2593 return Error(ID.Loc, "invalid indices for extractvalue");
2594 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2595 ID.Kind = ValID::t_Constant;
2598 case lltok::kw_insertvalue: {
2600 Constant *Val0, *Val1;
2601 SmallVector<unsigned, 4> Indices;
2602 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2603 ParseGlobalTypeAndValue(Val0) ||
2604 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2605 ParseGlobalTypeAndValue(Val1) ||
2606 ParseIndexList(Indices) ||
2607 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2609 if (!Val0->getType()->isAggregateType())
2610 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2611 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2612 return Error(ID.Loc, "invalid indices for insertvalue");
2613 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2614 ID.Kind = ValID::t_Constant;
2617 case lltok::kw_icmp:
2618 case lltok::kw_fcmp: {
2619 unsigned PredVal, Opc = Lex.getUIntVal();
2620 Constant *Val0, *Val1;
2622 if (ParseCmpPredicate(PredVal, Opc) ||
2623 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2624 ParseGlobalTypeAndValue(Val0) ||
2625 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2626 ParseGlobalTypeAndValue(Val1) ||
2627 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2630 if (Val0->getType() != Val1->getType())
2631 return Error(ID.Loc, "compare operands must have the same type");
2633 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2635 if (Opc == Instruction::FCmp) {
2636 if (!Val0->getType()->isFPOrFPVectorTy())
2637 return Error(ID.Loc, "fcmp requires floating point operands");
2638 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2640 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2641 if (!Val0->getType()->isIntOrIntVectorTy() &&
2642 !Val0->getType()->getScalarType()->isPointerTy())
2643 return Error(ID.Loc, "icmp requires pointer or integer operands");
2644 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2646 ID.Kind = ValID::t_Constant;
2650 // Binary Operators.
2652 case lltok::kw_fadd:
2654 case lltok::kw_fsub:
2656 case lltok::kw_fmul:
2657 case lltok::kw_udiv:
2658 case lltok::kw_sdiv:
2659 case lltok::kw_fdiv:
2660 case lltok::kw_urem:
2661 case lltok::kw_srem:
2662 case lltok::kw_frem:
2664 case lltok::kw_lshr:
2665 case lltok::kw_ashr: {
2669 unsigned Opc = Lex.getUIntVal();
2670 Constant *Val0, *Val1;
2672 LocTy ModifierLoc = Lex.getLoc();
2673 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2674 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2675 if (EatIfPresent(lltok::kw_nuw))
2677 if (EatIfPresent(lltok::kw_nsw)) {
2679 if (EatIfPresent(lltok::kw_nuw))
2682 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2683 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2684 if (EatIfPresent(lltok::kw_exact))
2687 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2688 ParseGlobalTypeAndValue(Val0) ||
2689 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2690 ParseGlobalTypeAndValue(Val1) ||
2691 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2693 if (Val0->getType() != Val1->getType())
2694 return Error(ID.Loc, "operands of constexpr must have same type");
2695 if (!Val0->getType()->isIntOrIntVectorTy()) {
2697 return Error(ModifierLoc, "nuw only applies to integer operations");
2699 return Error(ModifierLoc, "nsw only applies to integer operations");
2701 // Check that the type is valid for the operator.
2703 case Instruction::Add:
2704 case Instruction::Sub:
2705 case Instruction::Mul:
2706 case Instruction::UDiv:
2707 case Instruction::SDiv:
2708 case Instruction::URem:
2709 case Instruction::SRem:
2710 case Instruction::Shl:
2711 case Instruction::AShr:
2712 case Instruction::LShr:
2713 if (!Val0->getType()->isIntOrIntVectorTy())
2714 return Error(ID.Loc, "constexpr requires integer operands");
2716 case Instruction::FAdd:
2717 case Instruction::FSub:
2718 case Instruction::FMul:
2719 case Instruction::FDiv:
2720 case Instruction::FRem:
2721 if (!Val0->getType()->isFPOrFPVectorTy())
2722 return Error(ID.Loc, "constexpr requires fp operands");
2724 default: llvm_unreachable("Unknown binary operator!");
2727 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2728 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2729 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2730 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2732 ID.Kind = ValID::t_Constant;
2736 // Logical Operations
2739 case lltok::kw_xor: {
2740 unsigned Opc = Lex.getUIntVal();
2741 Constant *Val0, *Val1;
2743 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2744 ParseGlobalTypeAndValue(Val0) ||
2745 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2746 ParseGlobalTypeAndValue(Val1) ||
2747 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2749 if (Val0->getType() != Val1->getType())
2750 return Error(ID.Loc, "operands of constexpr must have same type");
2751 if (!Val0->getType()->isIntOrIntVectorTy())
2752 return Error(ID.Loc,
2753 "constexpr requires integer or integer vector operands");
2754 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2755 ID.Kind = ValID::t_Constant;
2759 case lltok::kw_getelementptr:
2760 case lltok::kw_shufflevector:
2761 case lltok::kw_insertelement:
2762 case lltok::kw_extractelement:
2763 case lltok::kw_select: {
2764 unsigned Opc = Lex.getUIntVal();
2765 SmallVector<Constant*, 16> Elts;
2766 bool InBounds = false;
2768 if (Opc == Instruction::GetElementPtr)
2769 InBounds = EatIfPresent(lltok::kw_inbounds);
2770 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2771 ParseGlobalValueVector(Elts) ||
2772 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2775 if (Opc == Instruction::GetElementPtr) {
2776 if (Elts.size() == 0 ||
2777 !Elts[0]->getType()->getScalarType()->isPointerTy())
2778 return Error(ID.Loc, "getelementptr requires pointer operand");
2780 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2781 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2782 return Error(ID.Loc, "invalid indices for getelementptr");
2783 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2785 } else if (Opc == Instruction::Select) {
2786 if (Elts.size() != 3)
2787 return Error(ID.Loc, "expected three operands to select");
2788 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2790 return Error(ID.Loc, Reason);
2791 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2792 } else if (Opc == Instruction::ShuffleVector) {
2793 if (Elts.size() != 3)
2794 return Error(ID.Loc, "expected three operands to shufflevector");
2795 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2796 return Error(ID.Loc, "invalid operands to shufflevector");
2798 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2799 } else if (Opc == Instruction::ExtractElement) {
2800 if (Elts.size() != 2)
2801 return Error(ID.Loc, "expected two operands to extractelement");
2802 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2803 return Error(ID.Loc, "invalid extractelement operands");
2804 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2806 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2807 if (Elts.size() != 3)
2808 return Error(ID.Loc, "expected three operands to insertelement");
2809 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2810 return Error(ID.Loc, "invalid insertelement operands");
2812 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2815 ID.Kind = ValID::t_Constant;
2824 /// ParseGlobalValue - Parse a global value with the specified type.
2825 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2829 bool Parsed = ParseValID(ID) ||
2830 ConvertValIDToValue(Ty, ID, V, nullptr);
2831 if (V && !(C = dyn_cast<Constant>(V)))
2832 return Error(ID.Loc, "global values must be constants");
2836 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2838 return ParseType(Ty) ||
2839 ParseGlobalValue(Ty, V);
2842 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2845 LocTy KwLoc = Lex.getLoc();
2846 if (!EatIfPresent(lltok::kw_comdat))
2849 if (EatIfPresent(lltok::lparen)) {
2850 if (Lex.getKind() != lltok::ComdatVar)
2851 return TokError("expected comdat variable");
2852 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2854 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2857 if (GlobalName.empty())
2858 return TokError("comdat cannot be unnamed");
2859 C = getComdat(GlobalName, KwLoc);
2865 /// ParseGlobalValueVector
2867 /// ::= TypeAndValue (',' TypeAndValue)*
2868 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2870 if (Lex.getKind() == lltok::rbrace ||
2871 Lex.getKind() == lltok::rsquare ||
2872 Lex.getKind() == lltok::greater ||
2873 Lex.getKind() == lltok::rparen)
2877 if (ParseGlobalTypeAndValue(C)) return true;
2880 while (EatIfPresent(lltok::comma)) {
2881 if (ParseGlobalTypeAndValue(C)) return true;
2888 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2889 SmallVector<Metadata *, 16> Elts;
2890 if (ParseMDNodeVector(Elts))
2893 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2900 /// ::= !MDLocation(...)
2901 bool LLParser::ParseMDNode(MDNode *&N) {
2902 if (Lex.getKind() == lltok::MetadataVar)
2903 return ParseSpecializedMDNode(N);
2905 return ParseToken(lltok::exclaim, "expected '!' here") ||
2909 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2911 if (Lex.getKind() == lltok::lbrace)
2912 return ParseMDTuple(N);
2915 return ParseMDNodeID(N);
2920 /// Structure to represent an optional metadata field.
2921 template <class FieldTy> struct MDFieldImpl {
2922 typedef MDFieldImpl ImplTy;
2926 void assign(FieldTy Val) {
2928 this->Val = std::move(Val);
2931 explicit MDFieldImpl(FieldTy Default)
2932 : Val(std::move(Default)), Seen(false) {}
2935 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
2938 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
2939 : ImplTy(Default), Max(Max) {}
2941 struct LineField : public MDUnsignedField {
2942 LineField() : MDUnsignedField(0, UINT32_MAX) {}
2944 struct ColumnField : public MDUnsignedField {
2945 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
2947 struct DwarfTagField : public MDUnsignedField {
2948 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
2950 struct DwarfAttEncodingField : public MDUnsignedField {
2951 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
2953 struct DwarfVirtualityField : public MDUnsignedField {
2954 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
2956 struct DwarfLangField : public MDUnsignedField {
2957 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
2960 struct MDSignedField : public MDFieldImpl<int64_t> {
2964 MDSignedField(int64_t Default = 0)
2965 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
2966 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
2967 : ImplTy(Default), Min(Min), Max(Max) {}
2970 struct MDBoolField : public MDFieldImpl<bool> {
2971 MDBoolField(bool Default = false) : ImplTy(Default) {}
2973 struct MDField : public MDFieldImpl<Metadata *> {
2974 MDField() : ImplTy(nullptr) {}
2976 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
2977 MDConstant() : ImplTy(nullptr) {}
2979 struct MDStringField : public MDFieldImpl<std::string> {
2980 MDStringField() : ImplTy(std::string()) {}
2982 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
2983 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
2991 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
2992 MDUnsignedField &Result) {
2993 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2994 return TokError("expected unsigned integer");
2996 auto &U = Lex.getAPSIntVal();
2997 if (U.ugt(Result.Max))
2998 return TokError("value for '" + Name + "' too large, limit is " +
3000 Result.assign(U.getZExtValue());
3001 assert(Result.Val <= Result.Max && "Expected value in range");
3007 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3008 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3011 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3012 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3016 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3017 if (Lex.getKind() == lltok::APSInt)
3018 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3020 if (Lex.getKind() != lltok::DwarfTag)
3021 return TokError("expected DWARF tag");
3023 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3024 if (Tag == dwarf::DW_TAG_invalid)
3025 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3026 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3034 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3035 DwarfVirtualityField &Result) {
3036 if (Lex.getKind() == lltok::APSInt)
3037 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3039 if (Lex.getKind() != lltok::DwarfVirtuality)
3040 return TokError("expected DWARF virtuality code");
3042 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3044 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3045 Lex.getStrVal() + "'");
3046 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3047 Result.assign(Virtuality);
3053 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3054 if (Lex.getKind() == lltok::APSInt)
3055 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3057 if (Lex.getKind() != lltok::DwarfLang)
3058 return TokError("expected DWARF language");
3060 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3062 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3064 assert(Lang <= Result.Max && "Expected valid DWARF language");
3065 Result.assign(Lang);
3071 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3072 DwarfAttEncodingField &Result) {
3073 if (Lex.getKind() == lltok::APSInt)
3074 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3076 if (Lex.getKind() != lltok::DwarfAttEncoding)
3077 return TokError("expected DWARF type attribute encoding");
3079 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3081 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3082 Lex.getStrVal() + "'");
3083 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3084 Result.assign(Encoding);
3090 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3091 MDSignedField &Result) {
3092 if (Lex.getKind() != lltok::APSInt)
3093 return TokError("expected signed integer");
3095 auto &S = Lex.getAPSIntVal();
3097 return TokError("value for '" + Name + "' too small, limit is " +
3100 return TokError("value for '" + Name + "' too large, limit is " +
3102 Result.assign(S.getExtValue());
3103 assert(Result.Val >= Result.Min && "Expected value in range");
3104 assert(Result.Val <= Result.Max && "Expected value in range");
3110 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3111 switch (Lex.getKind()) {
3113 return TokError("expected 'true' or 'false'");
3114 case lltok::kw_true:
3115 Result.assign(true);
3117 case lltok::kw_false:
3118 Result.assign(false);
3126 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3127 if (Lex.getKind() == lltok::kw_null) {
3129 Result.assign(nullptr);
3134 if (ParseMetadata(MD, nullptr))
3142 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3144 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3147 Result.assign(cast<ConstantAsMetadata>(MD));
3152 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3154 if (ParseStringConstant(S))
3157 Result.assign(std::move(S));
3162 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3163 SmallVector<Metadata *, 4> MDs;
3164 if (ParseMDNodeVector(MDs))
3167 Result.assign(std::move(MDs));
3171 } // end namespace llvm
3173 template <class ParserTy>
3174 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3176 if (Lex.getKind() != lltok::LabelStr)
3177 return TokError("expected field label here");
3181 } while (EatIfPresent(lltok::comma));
3186 template <class ParserTy>
3187 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3188 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3191 if (ParseToken(lltok::lparen, "expected '(' here"))
3193 if (Lex.getKind() != lltok::rparen)
3194 if (ParseMDFieldsImplBody(parseField))
3197 ClosingLoc = Lex.getLoc();
3198 return ParseToken(lltok::rparen, "expected ')' here");
3201 template <class FieldTy>
3202 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3204 return TokError("field '" + Name + "' cannot be specified more than once");
3206 LocTy Loc = Lex.getLoc();
3208 return ParseMDField(Loc, Name, Result);
3211 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3212 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3214 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3215 if (Lex.getStrVal() == #CLASS) \
3216 return Parse##CLASS(N, IsDistinct);
3217 #include "llvm/IR/Metadata.def"
3219 return TokError("expected metadata type");
3222 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3223 #define NOP_FIELD(NAME, TYPE, INIT)
3224 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3226 return Error(ClosingLoc, "missing required field '" #NAME "'");
3227 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3228 if (Lex.getStrVal() == #NAME) \
3229 return ParseMDField(#NAME, NAME);
3230 #define PARSE_MD_FIELDS() \
3231 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3234 if (ParseMDFieldsImpl([&]() -> bool { \
3235 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3236 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3239 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3241 #define GET_OR_DISTINCT(CLASS, ARGS) \
3242 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3244 /// ParseMDLocationFields:
3245 /// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3246 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3247 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3248 OPTIONAL(line, LineField, ); \
3249 OPTIONAL(column, ColumnField, ); \
3250 REQUIRED(scope, MDField, ); \
3251 OPTIONAL(inlinedAt, MDField, );
3253 #undef VISIT_MD_FIELDS
3255 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3256 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3260 /// ParseGenericDebugNode:
3261 /// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3262 bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3263 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3264 REQUIRED(tag, DwarfTagField, ); \
3265 OPTIONAL(header, MDStringField, ); \
3266 OPTIONAL(operands, MDFieldList, );
3268 #undef VISIT_MD_FIELDS
3270 Result = GET_OR_DISTINCT(GenericDebugNode,
3271 (Context, tag.Val, header.Val, operands.Val));
3275 /// ParseMDSubrange:
3276 /// ::= !MDSubrange(count: 30, lowerBound: 2)
3277 bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
3278 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3279 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3280 OPTIONAL(lowerBound, MDSignedField, );
3282 #undef VISIT_MD_FIELDS
3284 Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3288 /// ParseMDEnumerator:
3289 /// ::= !MDEnumerator(value: 30, name: "SomeKind")
3290 bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
3291 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3292 REQUIRED(name, MDStringField, ); \
3293 REQUIRED(value, MDSignedField, );
3295 #undef VISIT_MD_FIELDS
3297 Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3301 /// ParseMDBasicType:
3302 /// ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3303 bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
3304 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3305 REQUIRED(tag, DwarfTagField, ); \
3306 OPTIONAL(name, MDStringField, ); \
3307 OPTIONAL(size, MDUnsignedField, (0, UINT32_MAX)); \
3308 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3309 OPTIONAL(encoding, DwarfAttEncodingField, );
3311 #undef VISIT_MD_FIELDS
3313 Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3314 align.Val, encoding.Val));
3318 /// ParseMDDerivedType:
3319 /// ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3320 /// line: 7, scope: !1, baseType: !2, size: 32,
3321 /// align: 32, offset: 0, flags: 0, extraData: !3)
3322 bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
3323 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3324 REQUIRED(tag, DwarfTagField, ); \
3325 OPTIONAL(name, MDStringField, ); \
3326 OPTIONAL(file, MDField, ); \
3327 OPTIONAL(line, LineField, ); \
3328 OPTIONAL(scope, MDField, ); \
3329 REQUIRED(baseType, MDField, ); \
3330 OPTIONAL(size, MDUnsignedField, (0, UINT32_MAX)); \
3331 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3332 OPTIONAL(offset, MDUnsignedField, (0, UINT32_MAX)); \
3333 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3334 OPTIONAL(extraData, MDField, );
3336 #undef VISIT_MD_FIELDS
3338 Result = GET_OR_DISTINCT(MDDerivedType,
3339 (Context, tag.Val, name.Val, file.Val, line.Val,
3340 scope.Val, baseType.Val, size.Val, align.Val,
3341 offset.Val, flags.Val, extraData.Val));
3345 bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
3346 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3347 REQUIRED(tag, DwarfTagField, ); \
3348 OPTIONAL(name, MDStringField, ); \
3349 OPTIONAL(file, MDField, ); \
3350 OPTIONAL(line, LineField, ); \
3351 OPTIONAL(scope, MDField, ); \
3352 OPTIONAL(baseType, MDField, ); \
3353 OPTIONAL(size, MDUnsignedField, (0, UINT32_MAX)); \
3354 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3355 OPTIONAL(offset, MDUnsignedField, (0, UINT32_MAX)); \
3356 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3357 OPTIONAL(elements, MDField, ); \
3358 OPTIONAL(runtimeLang, DwarfLangField, ); \
3359 OPTIONAL(vtableHolder, MDField, ); \
3360 OPTIONAL(templateParams, MDField, ); \
3361 OPTIONAL(identifier, MDStringField, );
3363 #undef VISIT_MD_FIELDS
3365 Result = GET_OR_DISTINCT(
3367 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3368 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3369 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3373 bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
3374 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3375 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3376 REQUIRED(types, MDField, );
3378 #undef VISIT_MD_FIELDS
3380 Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3384 /// ParseMDFileType:
3385 /// ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
3386 bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
3387 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3388 REQUIRED(filename, MDStringField, ); \
3389 REQUIRED(directory, MDStringField, );
3391 #undef VISIT_MD_FIELDS
3393 Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3397 /// ParseMDCompileUnit:
3398 /// ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3399 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3400 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3401 /// enums: !1, retainedTypes: !2, subprograms: !3,
3402 /// globals: !4, imports: !5)
3403 bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
3404 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3405 REQUIRED(language, DwarfLangField, ); \
3406 REQUIRED(file, MDField, ); \
3407 OPTIONAL(producer, MDStringField, ); \
3408 OPTIONAL(isOptimized, MDBoolField, ); \
3409 OPTIONAL(flags, MDStringField, ); \
3410 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3411 OPTIONAL(splitDebugFilename, MDStringField, ); \
3412 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3413 OPTIONAL(enums, MDField, ); \
3414 OPTIONAL(retainedTypes, MDField, ); \
3415 OPTIONAL(subprograms, MDField, ); \
3416 OPTIONAL(globals, MDField, ); \
3417 OPTIONAL(imports, MDField, );
3419 #undef VISIT_MD_FIELDS
3421 Result = GET_OR_DISTINCT(MDCompileUnit,
3422 (Context, language.Val, file.Val, producer.Val,
3423 isOptimized.Val, flags.Val, runtimeVersion.Val,
3424 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3425 retainedTypes.Val, subprograms.Val, globals.Val,
3430 /// ParseMDSubprogram:
3431 /// ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3432 /// file: !1, line: 7, type: !2, isLocal: false,
3433 /// isDefinition: true, scopeLine: 8, containingType: !3,
3434 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3435 /// virtualIndex: 10, flags: 11,
3436 /// isOptimized: false, function: void ()* @_Z3foov,
3437 /// templateParams: !4, declaration: !5, variables: !6)
3438 bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
3439 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3440 OPTIONAL(scope, MDField, ); \
3441 REQUIRED(name, MDStringField, ); \
3442 OPTIONAL(linkageName, MDStringField, ); \
3443 OPTIONAL(file, MDField, ); \
3444 OPTIONAL(line, LineField, ); \
3445 OPTIONAL(type, MDField, ); \
3446 OPTIONAL(isLocal, MDBoolField, ); \
3447 OPTIONAL(isDefinition, MDBoolField, (true)); \
3448 OPTIONAL(scopeLine, LineField, ); \
3449 OPTIONAL(containingType, MDField, ); \
3450 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3451 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3452 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3453 OPTIONAL(isOptimized, MDBoolField, ); \
3454 OPTIONAL(function, MDConstant, ); \
3455 OPTIONAL(templateParams, MDField, ); \
3456 OPTIONAL(declaration, MDField, ); \
3457 OPTIONAL(variables, MDField, );
3459 #undef VISIT_MD_FIELDS
3461 Result = GET_OR_DISTINCT(
3462 MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3463 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3464 scopeLine.Val, containingType.Val, virtuality.Val,
3465 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3466 templateParams.Val, declaration.Val, variables.Val));
3470 /// ParseMDLexicalBlock:
3471 /// ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3472 bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
3473 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3474 REQUIRED(scope, MDField, ); \
3475 OPTIONAL(file, MDField, ); \
3476 OPTIONAL(line, LineField, ); \
3477 OPTIONAL(column, ColumnField, );
3479 #undef VISIT_MD_FIELDS
3481 Result = GET_OR_DISTINCT(
3482 MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3486 /// ParseMDLexicalBlockFile:
3487 /// ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3488 bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3489 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3490 REQUIRED(scope, MDField, ); \
3491 OPTIONAL(file, MDField, ); \
3492 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3494 #undef VISIT_MD_FIELDS
3496 Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3497 (Context, scope.Val, file.Val, discriminator.Val));
3501 /// ParseMDNamespace:
3502 /// ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3503 bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
3504 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3505 REQUIRED(scope, MDField, ); \
3506 OPTIONAL(file, MDField, ); \
3507 OPTIONAL(name, MDStringField, ); \
3508 OPTIONAL(line, LineField, );
3510 #undef VISIT_MD_FIELDS
3512 Result = GET_OR_DISTINCT(MDNamespace,
3513 (Context, scope.Val, file.Val, name.Val, line.Val));
3517 /// ParseMDTemplateTypeParameter:
3518 /// ::= !MDTemplateTypeParameter(name: "Ty", type: !1)
3519 bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3520 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3521 OPTIONAL(name, MDStringField, ); \
3522 REQUIRED(type, MDField, );
3524 #undef VISIT_MD_FIELDS
3527 GET_OR_DISTINCT(MDTemplateTypeParameter, (Context, name.Val, type.Val));
3531 /// ParseMDTemplateValueParameter:
3532 /// ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
3533 /// name: "V", type: !1, value: i32 7)
3534 bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3535 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3536 REQUIRED(tag, DwarfTagField, ); \
3537 OPTIONAL(name, MDStringField, ); \
3538 REQUIRED(type, MDField, ); \
3539 REQUIRED(value, MDField, );
3541 #undef VISIT_MD_FIELDS
3543 Result = GET_OR_DISTINCT(MDTemplateValueParameter,
3544 (Context, tag.Val, name.Val, type.Val, value.Val));
3548 /// ParseMDGlobalVariable:
3549 /// ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3550 /// file: !1, line: 7, type: !2, isLocal: false,
3551 /// isDefinition: true, variable: i32* @foo,
3552 /// declaration: !3)
3553 bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
3554 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3555 OPTIONAL(scope, MDField, ); \
3556 REQUIRED(name, MDStringField, ); \
3557 OPTIONAL(linkageName, MDStringField, ); \
3558 OPTIONAL(file, MDField, ); \
3559 OPTIONAL(line, LineField, ); \
3560 OPTIONAL(type, MDField, ); \
3561 OPTIONAL(isLocal, MDBoolField, ); \
3562 OPTIONAL(isDefinition, MDBoolField, (true)); \
3563 OPTIONAL(variable, MDConstant, ); \
3564 OPTIONAL(declaration, MDField, );
3566 #undef VISIT_MD_FIELDS
3568 Result = GET_OR_DISTINCT(MDGlobalVariable,
3569 (Context, scope.Val, name.Val, linkageName.Val,
3570 file.Val, line.Val, type.Val, isLocal.Val,
3571 isDefinition.Val, variable.Val, declaration.Val));
3575 /// ParseMDLocalVariable:
3576 /// ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3577 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
3579 bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
3580 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3581 REQUIRED(tag, DwarfTagField, ); \
3582 OPTIONAL(scope, MDField, ); \
3583 OPTIONAL(name, MDStringField, ); \
3584 OPTIONAL(file, MDField, ); \
3585 OPTIONAL(line, LineField, ); \
3586 OPTIONAL(type, MDField, ); \
3587 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
3588 OPTIONAL(flags, MDUnsignedField, (0, UINT32_MAX)); \
3589 OPTIONAL(inlinedAt, MDField, );
3591 #undef VISIT_MD_FIELDS
3593 Result = GET_OR_DISTINCT(
3594 MDLocalVariable, (Context, tag.Val, scope.Val, name.Val, file.Val,
3595 line.Val, type.Val, arg.Val, flags.Val, inlinedAt.Val));
3599 /// ParseMDExpression:
3600 /// ::= !MDExpression(0, 7, -1)
3601 bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
3602 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3605 if (ParseToken(lltok::lparen, "expected '(' here"))
3608 SmallVector<uint64_t, 8> Elements;
3609 if (Lex.getKind() != lltok::rparen)
3611 if (Lex.getKind() == lltok::DwarfOp) {
3612 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3614 Elements.push_back(Op);
3617 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3620 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3621 return TokError("expected unsigned integer");
3623 auto &U = Lex.getAPSIntVal();
3624 if (U.ugt(UINT64_MAX))
3625 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3626 Elements.push_back(U.getZExtValue());
3628 } while (EatIfPresent(lltok::comma));
3630 if (ParseToken(lltok::rparen, "expected ')' here"))
3633 Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3637 /// ParseMDObjCProperty:
3638 /// ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3639 /// getter: "getFoo", attributes: 7, type: !2)
3640 bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
3641 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3642 REQUIRED(name, MDStringField, ); \
3643 OPTIONAL(file, MDField, ); \
3644 OPTIONAL(line, LineField, ); \
3645 OPTIONAL(setter, MDStringField, ); \
3646 OPTIONAL(getter, MDStringField, ); \
3647 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3648 OPTIONAL(type, MDField, );
3650 #undef VISIT_MD_FIELDS
3652 Result = GET_OR_DISTINCT(MDObjCProperty,
3653 (Context, name.Val, file.Val, line.Val, setter.Val,
3654 getter.Val, attributes.Val, type.Val));
3658 /// ParseMDImportedEntity:
3659 /// ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3660 /// line: 7, name: "foo")
3661 bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
3662 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3663 REQUIRED(tag, DwarfTagField, ); \
3664 REQUIRED(scope, MDField, ); \
3665 OPTIONAL(entity, MDField, ); \
3666 OPTIONAL(line, LineField, ); \
3667 OPTIONAL(name, MDStringField, );
3669 #undef VISIT_MD_FIELDS
3671 Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3672 entity.Val, line.Val, name.Val));
3676 #undef PARSE_MD_FIELD
3678 #undef REQUIRE_FIELD
3679 #undef DECLARE_FIELD
3681 /// ParseMetadataAsValue
3682 /// ::= metadata i32 %local
3683 /// ::= metadata i32 @global
3684 /// ::= metadata i32 7
3686 /// ::= metadata !{...}
3687 /// ::= metadata !"string"
3688 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3689 // Note: the type 'metadata' has already been parsed.
3691 if (ParseMetadata(MD, &PFS))
3694 V = MetadataAsValue::get(Context, MD);
3698 /// ParseValueAsMetadata
3702 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3703 PerFunctionState *PFS) {
3706 if (ParseType(Ty, TypeMsg, Loc))
3708 if (Ty->isMetadataTy())
3709 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3712 if (ParseValue(Ty, V, PFS))
3715 MD = ValueAsMetadata::get(V);
3726 /// ::= !MDLocation(...)
3727 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3728 if (Lex.getKind() == lltok::MetadataVar) {
3730 if (ParseSpecializedMDNode(N))
3738 if (Lex.getKind() != lltok::exclaim)
3739 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3742 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3746 // ::= '!' STRINGCONSTANT
3747 if (Lex.getKind() == lltok::StringConstant) {
3749 if (ParseMDString(S))
3759 if (ParseMDNodeTail(N))
3766 //===----------------------------------------------------------------------===//
3767 // Function Parsing.
3768 //===----------------------------------------------------------------------===//
3770 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3771 PerFunctionState *PFS) {
3772 if (Ty->isFunctionTy())
3773 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3776 case ValID::t_LocalID:
3777 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3778 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3779 return V == nullptr;
3780 case ValID::t_LocalName:
3781 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3782 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3783 return V == nullptr;
3784 case ValID::t_InlineAsm: {
3785 PointerType *PTy = dyn_cast<PointerType>(Ty);
3787 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3788 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3789 return Error(ID.Loc, "invalid type for inline asm constraint string");
3790 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3791 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3794 case ValID::t_GlobalName:
3795 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3796 return V == nullptr;
3797 case ValID::t_GlobalID:
3798 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3799 return V == nullptr;
3800 case ValID::t_APSInt:
3801 if (!Ty->isIntegerTy())
3802 return Error(ID.Loc, "integer constant must have integer type");
3803 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3804 V = ConstantInt::get(Context, ID.APSIntVal);
3806 case ValID::t_APFloat:
3807 if (!Ty->isFloatingPointTy() ||
3808 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3809 return Error(ID.Loc, "floating point constant invalid for type");
3811 // The lexer has no type info, so builds all half, float, and double FP
3812 // constants as double. Fix this here. Long double does not need this.
3813 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3816 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3818 else if (Ty->isFloatTy())
3819 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3822 V = ConstantFP::get(Context, ID.APFloatVal);
3824 if (V->getType() != Ty)
3825 return Error(ID.Loc, "floating point constant does not have type '" +
3826 getTypeString(Ty) + "'");
3830 if (!Ty->isPointerTy())
3831 return Error(ID.Loc, "null must be a pointer type");
3832 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3834 case ValID::t_Undef:
3835 // FIXME: LabelTy should not be a first-class type.
3836 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3837 return Error(ID.Loc, "invalid type for undef constant");
3838 V = UndefValue::get(Ty);
3840 case ValID::t_EmptyArray:
3841 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3842 return Error(ID.Loc, "invalid empty array initializer");
3843 V = UndefValue::get(Ty);
3846 // FIXME: LabelTy should not be a first-class type.
3847 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3848 return Error(ID.Loc, "invalid type for null constant");
3849 V = Constant::getNullValue(Ty);
3851 case ValID::t_Constant:
3852 if (ID.ConstantVal->getType() != Ty)
3853 return Error(ID.Loc, "constant expression type mismatch");
3857 case ValID::t_ConstantStruct:
3858 case ValID::t_PackedConstantStruct:
3859 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3860 if (ST->getNumElements() != ID.UIntVal)
3861 return Error(ID.Loc,
3862 "initializer with struct type has wrong # elements");
3863 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3864 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3866 // Verify that the elements are compatible with the structtype.
3867 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3868 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3869 return Error(ID.Loc, "element " + Twine(i) +
3870 " of struct initializer doesn't match struct element type");
3872 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3875 return Error(ID.Loc, "constant expression type mismatch");
3878 llvm_unreachable("Invalid ValID");
3881 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3884 return ParseValID(ID, PFS) ||
3885 ConvertValIDToValue(Ty, ID, V, PFS);
3888 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3890 return ParseType(Ty) ||
3891 ParseValue(Ty, V, PFS);
3894 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3895 PerFunctionState &PFS) {
3898 if (ParseTypeAndValue(V, PFS)) return true;
3899 if (!isa<BasicBlock>(V))
3900 return Error(Loc, "expected a basic block");
3901 BB = cast<BasicBlock>(V);
3907 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3908 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3909 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3910 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3911 // Parse the linkage.
3912 LocTy LinkageLoc = Lex.getLoc();
3915 unsigned Visibility;
3916 unsigned DLLStorageClass;
3917 AttrBuilder RetAttrs;
3919 Type *RetType = nullptr;
3920 LocTy RetTypeLoc = Lex.getLoc();
3921 if (ParseOptionalLinkage(Linkage) ||
3922 ParseOptionalVisibility(Visibility) ||
3923 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3924 ParseOptionalCallingConv(CC) ||
3925 ParseOptionalReturnAttrs(RetAttrs) ||
3926 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3929 // Verify that the linkage is ok.
3930 switch ((GlobalValue::LinkageTypes)Linkage) {
3931 case GlobalValue::ExternalLinkage:
3932 break; // always ok.
3933 case GlobalValue::ExternalWeakLinkage:
3935 return Error(LinkageLoc, "invalid linkage for function definition");
3937 case GlobalValue::PrivateLinkage:
3938 case GlobalValue::InternalLinkage:
3939 case GlobalValue::AvailableExternallyLinkage:
3940 case GlobalValue::LinkOnceAnyLinkage:
3941 case GlobalValue::LinkOnceODRLinkage:
3942 case GlobalValue::WeakAnyLinkage:
3943 case GlobalValue::WeakODRLinkage:
3945 return Error(LinkageLoc, "invalid linkage for function declaration");
3947 case GlobalValue::AppendingLinkage:
3948 case GlobalValue::CommonLinkage:
3949 return Error(LinkageLoc, "invalid function linkage type");
3952 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3953 return Error(LinkageLoc,
3954 "symbol with local linkage must have default visibility");
3956 if (!FunctionType::isValidReturnType(RetType))
3957 return Error(RetTypeLoc, "invalid function return type");
3959 LocTy NameLoc = Lex.getLoc();
3961 std::string FunctionName;
3962 if (Lex.getKind() == lltok::GlobalVar) {
3963 FunctionName = Lex.getStrVal();
3964 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3965 unsigned NameID = Lex.getUIntVal();
3967 if (NameID != NumberedVals.size())
3968 return TokError("function expected to be numbered '%" +
3969 Twine(NumberedVals.size()) + "'");
3971 return TokError("expected function name");
3976 if (Lex.getKind() != lltok::lparen)
3977 return TokError("expected '(' in function argument list");
3979 SmallVector<ArgInfo, 8> ArgList;
3981 AttrBuilder FuncAttrs;
3982 std::vector<unsigned> FwdRefAttrGrps;
3984 std::string Section;
3988 LocTy UnnamedAddrLoc;
3989 Constant *Prefix = nullptr;
3990 Constant *Prologue = nullptr;
3993 if (ParseArgumentList(ArgList, isVarArg) ||
3994 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3996 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3998 (EatIfPresent(lltok::kw_section) &&
3999 ParseStringConstant(Section)) ||
4000 parseOptionalComdat(FunctionName, C) ||
4001 ParseOptionalAlignment(Alignment) ||
4002 (EatIfPresent(lltok::kw_gc) &&
4003 ParseStringConstant(GC)) ||
4004 (EatIfPresent(lltok::kw_prefix) &&
4005 ParseGlobalTypeAndValue(Prefix)) ||
4006 (EatIfPresent(lltok::kw_prologue) &&
4007 ParseGlobalTypeAndValue(Prologue)))
4010 if (FuncAttrs.contains(Attribute::Builtin))
4011 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4013 // If the alignment was parsed as an attribute, move to the alignment field.
4014 if (FuncAttrs.hasAlignmentAttr()) {
4015 Alignment = FuncAttrs.getAlignment();
4016 FuncAttrs.removeAttribute(Attribute::Alignment);
4019 // Okay, if we got here, the function is syntactically valid. Convert types
4020 // and do semantic checks.
4021 std::vector<Type*> ParamTypeList;
4022 SmallVector<AttributeSet, 8> Attrs;
4024 if (RetAttrs.hasAttributes())
4025 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4026 AttributeSet::ReturnIndex,
4029 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4030 ParamTypeList.push_back(ArgList[i].Ty);
4031 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4032 AttrBuilder B(ArgList[i].Attrs, i + 1);
4033 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4037 if (FuncAttrs.hasAttributes())
4038 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4039 AttributeSet::FunctionIndex,
4042 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4044 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4045 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4048 FunctionType::get(RetType, ParamTypeList, isVarArg);
4049 PointerType *PFT = PointerType::getUnqual(FT);
4052 if (!FunctionName.empty()) {
4053 // If this was a definition of a forward reference, remove the definition
4054 // from the forward reference table and fill in the forward ref.
4055 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4056 ForwardRefVals.find(FunctionName);
4057 if (FRVI != ForwardRefVals.end()) {
4058 Fn = M->getFunction(FunctionName);
4060 return Error(FRVI->second.second, "invalid forward reference to "
4061 "function as global value!");
4062 if (Fn->getType() != PFT)
4063 return Error(FRVI->second.second, "invalid forward reference to "
4064 "function '" + FunctionName + "' with wrong type!");
4066 ForwardRefVals.erase(FRVI);
4067 } else if ((Fn = M->getFunction(FunctionName))) {
4068 // Reject redefinitions.
4069 return Error(NameLoc, "invalid redefinition of function '" +
4070 FunctionName + "'");
4071 } else if (M->getNamedValue(FunctionName)) {
4072 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4076 // If this is a definition of a forward referenced function, make sure the
4078 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4079 = ForwardRefValIDs.find(NumberedVals.size());
4080 if (I != ForwardRefValIDs.end()) {
4081 Fn = cast<Function>(I->second.first);
4082 if (Fn->getType() != PFT)
4083 return Error(NameLoc, "type of definition and forward reference of '@" +
4084 Twine(NumberedVals.size()) + "' disagree");
4085 ForwardRefValIDs.erase(I);
4090 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4091 else // Move the forward-reference to the correct spot in the module.
4092 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4094 if (FunctionName.empty())
4095 NumberedVals.push_back(Fn);
4097 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4098 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4099 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4100 Fn->setCallingConv(CC);
4101 Fn->setAttributes(PAL);
4102 Fn->setUnnamedAddr(UnnamedAddr);
4103 Fn->setAlignment(Alignment);
4104 Fn->setSection(Section);
4106 if (!GC.empty()) Fn->setGC(GC.c_str());
4107 Fn->setPrefixData(Prefix);
4108 Fn->setPrologueData(Prologue);
4109 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4111 // Add all of the arguments we parsed to the function.
4112 Function::arg_iterator ArgIt = Fn->arg_begin();
4113 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4114 // If the argument has a name, insert it into the argument symbol table.
4115 if (ArgList[i].Name.empty()) continue;
4117 // Set the name, if it conflicted, it will be auto-renamed.
4118 ArgIt->setName(ArgList[i].Name);
4120 if (ArgIt->getName() != ArgList[i].Name)
4121 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4122 ArgList[i].Name + "'");
4128 // Check the declaration has no block address forward references.
4130 if (FunctionName.empty()) {
4131 ID.Kind = ValID::t_GlobalID;
4132 ID.UIntVal = NumberedVals.size() - 1;
4134 ID.Kind = ValID::t_GlobalName;
4135 ID.StrVal = FunctionName;
4137 auto Blocks = ForwardRefBlockAddresses.find(ID);
4138 if (Blocks != ForwardRefBlockAddresses.end())
4139 return Error(Blocks->first.Loc,
4140 "cannot take blockaddress inside a declaration");
4144 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4146 if (FunctionNumber == -1) {
4147 ID.Kind = ValID::t_GlobalName;
4148 ID.StrVal = F.getName();
4150 ID.Kind = ValID::t_GlobalID;
4151 ID.UIntVal = FunctionNumber;
4154 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4155 if (Blocks == P.ForwardRefBlockAddresses.end())
4158 for (const auto &I : Blocks->second) {
4159 const ValID &BBID = I.first;
4160 GlobalValue *GV = I.second;
4162 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4163 "Expected local id or name");
4165 if (BBID.Kind == ValID::t_LocalName)
4166 BB = GetBB(BBID.StrVal, BBID.Loc);
4168 BB = GetBB(BBID.UIntVal, BBID.Loc);
4170 return P.Error(BBID.Loc, "referenced value is not a basic block");
4172 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4173 GV->eraseFromParent();
4176 P.ForwardRefBlockAddresses.erase(Blocks);
4180 /// ParseFunctionBody
4181 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4182 bool LLParser::ParseFunctionBody(Function &Fn) {
4183 if (Lex.getKind() != lltok::lbrace)
4184 return TokError("expected '{' in function body");
4185 Lex.Lex(); // eat the {.
4187 int FunctionNumber = -1;
4188 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4190 PerFunctionState PFS(*this, Fn, FunctionNumber);
4192 // Resolve block addresses and allow basic blocks to be forward-declared
4193 // within this function.
4194 if (PFS.resolveForwardRefBlockAddresses())
4196 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4198 // We need at least one basic block.
4199 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4200 return TokError("function body requires at least one basic block");
4202 while (Lex.getKind() != lltok::rbrace &&
4203 Lex.getKind() != lltok::kw_uselistorder)
4204 if (ParseBasicBlock(PFS)) return true;
4206 while (Lex.getKind() != lltok::rbrace)
4207 if (ParseUseListOrder(&PFS))
4213 // Verify function is ok.
4214 return PFS.FinishFunction();
4218 /// ::= LabelStr? Instruction*
4219 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4220 // If this basic block starts out with a name, remember it.
4222 LocTy NameLoc = Lex.getLoc();
4223 if (Lex.getKind() == lltok::LabelStr) {
4224 Name = Lex.getStrVal();
4228 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4229 if (!BB) return true;
4231 std::string NameStr;
4233 // Parse the instructions in this block until we get a terminator.
4236 // This instruction may have three possibilities for a name: a) none
4237 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4238 LocTy NameLoc = Lex.getLoc();
4242 if (Lex.getKind() == lltok::LocalVarID) {
4243 NameID = Lex.getUIntVal();
4245 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4247 } else if (Lex.getKind() == lltok::LocalVar) {
4248 NameStr = Lex.getStrVal();
4250 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4254 switch (ParseInstruction(Inst, BB, PFS)) {
4255 default: llvm_unreachable("Unknown ParseInstruction result!");
4256 case InstError: return true;
4258 BB->getInstList().push_back(Inst);
4260 // With a normal result, we check to see if the instruction is followed by
4261 // a comma and metadata.
4262 if (EatIfPresent(lltok::comma))
4263 if (ParseInstructionMetadata(Inst, &PFS))
4266 case InstExtraComma:
4267 BB->getInstList().push_back(Inst);
4269 // If the instruction parser ate an extra comma at the end of it, it
4270 // *must* be followed by metadata.
4271 if (ParseInstructionMetadata(Inst, &PFS))
4276 // Set the name on the instruction.
4277 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4278 } while (!isa<TerminatorInst>(Inst));
4283 //===----------------------------------------------------------------------===//
4284 // Instruction Parsing.
4285 //===----------------------------------------------------------------------===//
4287 /// ParseInstruction - Parse one of the many different instructions.
4289 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4290 PerFunctionState &PFS) {
4291 lltok::Kind Token = Lex.getKind();
4292 if (Token == lltok::Eof)
4293 return TokError("found end of file when expecting more instructions");
4294 LocTy Loc = Lex.getLoc();
4295 unsigned KeywordVal = Lex.getUIntVal();
4296 Lex.Lex(); // Eat the keyword.
4299 default: return Error(Loc, "expected instruction opcode");
4300 // Terminator Instructions.
4301 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4302 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4303 case lltok::kw_br: return ParseBr(Inst, PFS);
4304 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4305 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4306 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4307 case lltok::kw_resume: return ParseResume(Inst, PFS);
4308 // Binary Operators.
4312 case lltok::kw_shl: {
4313 bool NUW = EatIfPresent(lltok::kw_nuw);
4314 bool NSW = EatIfPresent(lltok::kw_nsw);
4315 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4317 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4319 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4320 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4323 case lltok::kw_fadd:
4324 case lltok::kw_fsub:
4325 case lltok::kw_fmul:
4326 case lltok::kw_fdiv:
4327 case lltok::kw_frem: {
4328 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4329 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4333 Inst->setFastMathFlags(FMF);
4337 case lltok::kw_sdiv:
4338 case lltok::kw_udiv:
4339 case lltok::kw_lshr:
4340 case lltok::kw_ashr: {
4341 bool Exact = EatIfPresent(lltok::kw_exact);
4343 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4344 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4348 case lltok::kw_urem:
4349 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4352 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4353 case lltok::kw_icmp:
4354 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
4356 case lltok::kw_trunc:
4357 case lltok::kw_zext:
4358 case lltok::kw_sext:
4359 case lltok::kw_fptrunc:
4360 case lltok::kw_fpext:
4361 case lltok::kw_bitcast:
4362 case lltok::kw_addrspacecast:
4363 case lltok::kw_uitofp:
4364 case lltok::kw_sitofp:
4365 case lltok::kw_fptoui:
4366 case lltok::kw_fptosi:
4367 case lltok::kw_inttoptr:
4368 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4370 case lltok::kw_select: return ParseSelect(Inst, PFS);
4371 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4372 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4373 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4374 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4375 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4376 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4378 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4379 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4380 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4382 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4383 case lltok::kw_load: return ParseLoad(Inst, PFS);
4384 case lltok::kw_store: return ParseStore(Inst, PFS);
4385 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4386 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4387 case lltok::kw_fence: return ParseFence(Inst, PFS);
4388 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4389 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4390 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4394 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4395 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4396 if (Opc == Instruction::FCmp) {
4397 switch (Lex.getKind()) {
4398 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4399 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4400 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4401 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4402 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4403 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4404 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4405 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4406 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4407 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4408 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4409 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4410 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4411 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4412 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4413 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4414 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4417 switch (Lex.getKind()) {
4418 default: return TokError("expected icmp predicate (e.g. 'eq')");
4419 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4420 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4421 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4422 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4423 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4424 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4425 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4426 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4427 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4428 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4435 //===----------------------------------------------------------------------===//
4436 // Terminator Instructions.
4437 //===----------------------------------------------------------------------===//
4439 /// ParseRet - Parse a return instruction.
4440 /// ::= 'ret' void (',' !dbg, !1)*
4441 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4442 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4443 PerFunctionState &PFS) {
4444 SMLoc TypeLoc = Lex.getLoc();
4446 if (ParseType(Ty, true /*void allowed*/)) return true;
4448 Type *ResType = PFS.getFunction().getReturnType();
4450 if (Ty->isVoidTy()) {
4451 if (!ResType->isVoidTy())
4452 return Error(TypeLoc, "value doesn't match function result type '" +
4453 getTypeString(ResType) + "'");
4455 Inst = ReturnInst::Create(Context);
4460 if (ParseValue(Ty, RV, PFS)) return true;
4462 if (ResType != RV->getType())
4463 return Error(TypeLoc, "value doesn't match function result type '" +
4464 getTypeString(ResType) + "'");
4466 Inst = ReturnInst::Create(Context, RV);
4472 /// ::= 'br' TypeAndValue
4473 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4474 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4477 BasicBlock *Op1, *Op2;
4478 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4480 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4481 Inst = BranchInst::Create(BB);
4485 if (Op0->getType() != Type::getInt1Ty(Context))
4486 return Error(Loc, "branch condition must have 'i1' type");
4488 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4489 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4490 ParseToken(lltok::comma, "expected ',' after true destination") ||
4491 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4494 Inst = BranchInst::Create(Op1, Op2, Op0);
4500 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4502 /// ::= (TypeAndValue ',' TypeAndValue)*
4503 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4504 LocTy CondLoc, BBLoc;
4506 BasicBlock *DefaultBB;
4507 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4508 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4509 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4510 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4513 if (!Cond->getType()->isIntegerTy())
4514 return Error(CondLoc, "switch condition must have integer type");
4516 // Parse the jump table pairs.
4517 SmallPtrSet<Value*, 32> SeenCases;
4518 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4519 while (Lex.getKind() != lltok::rsquare) {
4523 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4524 ParseToken(lltok::comma, "expected ',' after case value") ||
4525 ParseTypeAndBasicBlock(DestBB, PFS))
4528 if (!SeenCases.insert(Constant).second)
4529 return Error(CondLoc, "duplicate case value in switch");
4530 if (!isa<ConstantInt>(Constant))
4531 return Error(CondLoc, "case value is not a constant integer");
4533 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4536 Lex.Lex(); // Eat the ']'.
4538 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4539 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4540 SI->addCase(Table[i].first, Table[i].second);
4547 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4548 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4551 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4552 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4553 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4556 if (!Address->getType()->isPointerTy())
4557 return Error(AddrLoc, "indirectbr address must have pointer type");
4559 // Parse the destination list.
4560 SmallVector<BasicBlock*, 16> DestList;
4562 if (Lex.getKind() != lltok::rsquare) {
4564 if (ParseTypeAndBasicBlock(DestBB, PFS))
4566 DestList.push_back(DestBB);
4568 while (EatIfPresent(lltok::comma)) {
4569 if (ParseTypeAndBasicBlock(DestBB, PFS))
4571 DestList.push_back(DestBB);
4575 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4578 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4579 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4580 IBI->addDestination(DestList[i]);
4587 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4588 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4589 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4590 LocTy CallLoc = Lex.getLoc();
4591 AttrBuilder RetAttrs, FnAttrs;
4592 std::vector<unsigned> FwdRefAttrGrps;
4595 Type *RetType = nullptr;
4598 SmallVector<ParamInfo, 16> ArgList;
4600 BasicBlock *NormalBB, *UnwindBB;
4601 if (ParseOptionalCallingConv(CC) ||
4602 ParseOptionalReturnAttrs(RetAttrs) ||
4603 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4604 ParseValID(CalleeID) ||
4605 ParseParameterList(ArgList, PFS) ||
4606 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4608 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4609 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4610 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4611 ParseTypeAndBasicBlock(UnwindBB, PFS))
4614 // If RetType is a non-function pointer type, then this is the short syntax
4615 // for the call, which means that RetType is just the return type. Infer the
4616 // rest of the function argument types from the arguments that are present.
4617 PointerType *PFTy = nullptr;
4618 FunctionType *Ty = nullptr;
4619 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4620 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4621 // Pull out the types of all of the arguments...
4622 std::vector<Type*> ParamTypes;
4623 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4624 ParamTypes.push_back(ArgList[i].V->getType());
4626 if (!FunctionType::isValidReturnType(RetType))
4627 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4629 Ty = FunctionType::get(RetType, ParamTypes, false);
4630 PFTy = PointerType::getUnqual(Ty);
4633 // Look up the callee.
4635 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4637 // Set up the Attribute for the function.
4638 SmallVector<AttributeSet, 8> Attrs;
4639 if (RetAttrs.hasAttributes())
4640 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4641 AttributeSet::ReturnIndex,
4644 SmallVector<Value*, 8> Args;
4646 // Loop through FunctionType's arguments and ensure they are specified
4647 // correctly. Also, gather any parameter attributes.
4648 FunctionType::param_iterator I = Ty->param_begin();
4649 FunctionType::param_iterator E = Ty->param_end();
4650 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4651 Type *ExpectedTy = nullptr;
4654 } else if (!Ty->isVarArg()) {
4655 return Error(ArgList[i].Loc, "too many arguments specified");
4658 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4659 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4660 getTypeString(ExpectedTy) + "'");
4661 Args.push_back(ArgList[i].V);
4662 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4663 AttrBuilder B(ArgList[i].Attrs, i + 1);
4664 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4669 return Error(CallLoc, "not enough parameters specified for call");
4671 if (FnAttrs.hasAttributes())
4672 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4673 AttributeSet::FunctionIndex,
4676 // Finish off the Attribute and check them
4677 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4679 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4680 II->setCallingConv(CC);
4681 II->setAttributes(PAL);
4682 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4688 /// ::= 'resume' TypeAndValue
4689 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4690 Value *Exn; LocTy ExnLoc;
4691 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4694 ResumeInst *RI = ResumeInst::Create(Exn);
4699 //===----------------------------------------------------------------------===//
4700 // Binary Operators.
4701 //===----------------------------------------------------------------------===//
4704 /// ::= ArithmeticOps TypeAndValue ',' Value
4706 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4707 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4708 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4709 unsigned Opc, unsigned OperandType) {
4710 LocTy Loc; Value *LHS, *RHS;
4711 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4712 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4713 ParseValue(LHS->getType(), RHS, PFS))
4717 switch (OperandType) {
4718 default: llvm_unreachable("Unknown operand type!");
4719 case 0: // int or FP.
4720 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4721 LHS->getType()->isFPOrFPVectorTy();
4723 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4724 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4728 return Error(Loc, "invalid operand type for instruction");
4730 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4735 /// ::= ArithmeticOps TypeAndValue ',' Value {
4736 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4738 LocTy Loc; Value *LHS, *RHS;
4739 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4740 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4741 ParseValue(LHS->getType(), RHS, PFS))
4744 if (!LHS->getType()->isIntOrIntVectorTy())
4745 return Error(Loc,"instruction requires integer or integer vector operands");
4747 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4753 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4754 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4755 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4757 // Parse the integer/fp comparison predicate.
4761 if (ParseCmpPredicate(Pred, Opc) ||
4762 ParseTypeAndValue(LHS, Loc, PFS) ||
4763 ParseToken(lltok::comma, "expected ',' after compare value") ||
4764 ParseValue(LHS->getType(), RHS, PFS))
4767 if (Opc == Instruction::FCmp) {
4768 if (!LHS->getType()->isFPOrFPVectorTy())
4769 return Error(Loc, "fcmp requires floating point operands");
4770 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4772 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4773 if (!LHS->getType()->isIntOrIntVectorTy() &&
4774 !LHS->getType()->getScalarType()->isPointerTy())
4775 return Error(Loc, "icmp requires integer operands");
4776 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4781 //===----------------------------------------------------------------------===//
4782 // Other Instructions.
4783 //===----------------------------------------------------------------------===//
4787 /// ::= CastOpc TypeAndValue 'to' Type
4788 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4792 Type *DestTy = nullptr;
4793 if (ParseTypeAndValue(Op, Loc, PFS) ||
4794 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4798 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4799 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4800 return Error(Loc, "invalid cast opcode for cast from '" +
4801 getTypeString(Op->getType()) + "' to '" +
4802 getTypeString(DestTy) + "'");
4804 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4809 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4810 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4812 Value *Op0, *Op1, *Op2;
4813 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4814 ParseToken(lltok::comma, "expected ',' after select condition") ||
4815 ParseTypeAndValue(Op1, PFS) ||
4816 ParseToken(lltok::comma, "expected ',' after select value") ||
4817 ParseTypeAndValue(Op2, PFS))
4820 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4821 return Error(Loc, Reason);
4823 Inst = SelectInst::Create(Op0, Op1, Op2);
4828 /// ::= 'va_arg' TypeAndValue ',' Type
4829 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4831 Type *EltTy = nullptr;
4833 if (ParseTypeAndValue(Op, PFS) ||
4834 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4835 ParseType(EltTy, TypeLoc))
4838 if (!EltTy->isFirstClassType())
4839 return Error(TypeLoc, "va_arg requires operand with first class type");
4841 Inst = new VAArgInst(Op, EltTy);
4845 /// ParseExtractElement
4846 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4847 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4850 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4851 ParseToken(lltok::comma, "expected ',' after extract value") ||
4852 ParseTypeAndValue(Op1, PFS))
4855 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4856 return Error(Loc, "invalid extractelement operands");
4858 Inst = ExtractElementInst::Create(Op0, Op1);
4862 /// ParseInsertElement
4863 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4864 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4866 Value *Op0, *Op1, *Op2;
4867 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4868 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4869 ParseTypeAndValue(Op1, PFS) ||
4870 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4871 ParseTypeAndValue(Op2, PFS))
4874 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4875 return Error(Loc, "invalid insertelement operands");
4877 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4881 /// ParseShuffleVector
4882 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4883 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4885 Value *Op0, *Op1, *Op2;
4886 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4887 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4888 ParseTypeAndValue(Op1, PFS) ||
4889 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4890 ParseTypeAndValue(Op2, PFS))
4893 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4894 return Error(Loc, "invalid shufflevector operands");
4896 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4901 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4902 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4903 Type *Ty = nullptr; LocTy TypeLoc;
4906 if (ParseType(Ty, TypeLoc) ||
4907 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4908 ParseValue(Ty, Op0, PFS) ||
4909 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4910 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4911 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4914 bool AteExtraComma = false;
4915 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4917 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4919 if (!EatIfPresent(lltok::comma))
4922 if (Lex.getKind() == lltok::MetadataVar) {
4923 AteExtraComma = true;
4927 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4928 ParseValue(Ty, Op0, PFS) ||
4929 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4930 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4931 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4935 if (!Ty->isFirstClassType())
4936 return Error(TypeLoc, "phi node must have first class type");
4938 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4939 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4940 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4942 return AteExtraComma ? InstExtraComma : InstNormal;
4946 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4948 /// ::= 'catch' TypeAndValue
4950 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4951 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4952 Type *Ty = nullptr; LocTy TyLoc;
4953 Value *PersFn; LocTy PersFnLoc;
4955 if (ParseType(Ty, TyLoc) ||
4956 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4957 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4960 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4961 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4963 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4964 LandingPadInst::ClauseType CT;
4965 if (EatIfPresent(lltok::kw_catch))
4966 CT = LandingPadInst::Catch;
4967 else if (EatIfPresent(lltok::kw_filter))
4968 CT = LandingPadInst::Filter;
4970 return TokError("expected 'catch' or 'filter' clause type");
4974 if (ParseTypeAndValue(V, VLoc, PFS)) {
4979 // A 'catch' type expects a non-array constant. A filter clause expects an
4981 if (CT == LandingPadInst::Catch) {
4982 if (isa<ArrayType>(V->getType()))
4983 Error(VLoc, "'catch' clause has an invalid type");
4985 if (!isa<ArrayType>(V->getType()))
4986 Error(VLoc, "'filter' clause has an invalid type");
4989 LP->addClause(cast<Constant>(V));
4997 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4998 /// ParameterList OptionalAttrs
4999 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5000 /// ParameterList OptionalAttrs
5001 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5002 /// ParameterList OptionalAttrs
5003 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5004 CallInst::TailCallKind TCK) {
5005 AttrBuilder RetAttrs, FnAttrs;
5006 std::vector<unsigned> FwdRefAttrGrps;
5009 Type *RetType = nullptr;
5012 SmallVector<ParamInfo, 16> ArgList;
5013 LocTy CallLoc = Lex.getLoc();
5015 if ((TCK != CallInst::TCK_None &&
5016 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5017 ParseOptionalCallingConv(CC) ||
5018 ParseOptionalReturnAttrs(RetAttrs) ||
5019 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5020 ParseValID(CalleeID) ||
5021 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5022 PFS.getFunction().isVarArg()) ||
5023 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5027 // If RetType is a non-function pointer type, then this is the short syntax
5028 // for the call, which means that RetType is just the return type. Infer the
5029 // rest of the function argument types from the arguments that are present.
5030 PointerType *PFTy = nullptr;
5031 FunctionType *Ty = nullptr;
5032 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
5033 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
5034 // Pull out the types of all of the arguments...
5035 std::vector<Type*> ParamTypes;
5036 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5037 ParamTypes.push_back(ArgList[i].V->getType());
5039 if (!FunctionType::isValidReturnType(RetType))
5040 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5042 Ty = FunctionType::get(RetType, ParamTypes, false);
5043 PFTy = PointerType::getUnqual(Ty);
5046 // Look up the callee.
5048 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
5050 // Set up the Attribute for the function.
5051 SmallVector<AttributeSet, 8> Attrs;
5052 if (RetAttrs.hasAttributes())
5053 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5054 AttributeSet::ReturnIndex,
5057 SmallVector<Value*, 8> Args;
5059 // Loop through FunctionType's arguments and ensure they are specified
5060 // correctly. Also, gather any parameter attributes.
5061 FunctionType::param_iterator I = Ty->param_begin();
5062 FunctionType::param_iterator E = Ty->param_end();
5063 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5064 Type *ExpectedTy = nullptr;
5067 } else if (!Ty->isVarArg()) {
5068 return Error(ArgList[i].Loc, "too many arguments specified");
5071 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5072 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5073 getTypeString(ExpectedTy) + "'");
5074 Args.push_back(ArgList[i].V);
5075 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5076 AttrBuilder B(ArgList[i].Attrs, i + 1);
5077 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5082 return Error(CallLoc, "not enough parameters specified for call");
5084 if (FnAttrs.hasAttributes())
5085 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5086 AttributeSet::FunctionIndex,
5089 // Finish off the Attribute and check them
5090 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5092 CallInst *CI = CallInst::Create(Callee, Args);
5093 CI->setTailCallKind(TCK);
5094 CI->setCallingConv(CC);
5095 CI->setAttributes(PAL);
5096 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5101 //===----------------------------------------------------------------------===//
5102 // Memory Instructions.
5103 //===----------------------------------------------------------------------===//
5106 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5107 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5108 Value *Size = nullptr;
5109 LocTy SizeLoc, TyLoc;
5110 unsigned Alignment = 0;
5113 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5115 if (ParseType(Ty, TyLoc)) return true;
5117 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5118 return Error(TyLoc, "invalid type for alloca");
5120 bool AteExtraComma = false;
5121 if (EatIfPresent(lltok::comma)) {
5122 if (Lex.getKind() == lltok::kw_align) {
5123 if (ParseOptionalAlignment(Alignment)) return true;
5124 } else if (Lex.getKind() == lltok::MetadataVar) {
5125 AteExtraComma = true;
5127 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5128 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5133 if (Size && !Size->getType()->isIntegerTy())
5134 return Error(SizeLoc, "element count must have integer type");
5136 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5137 AI->setUsedWithInAlloca(IsInAlloca);
5139 return AteExtraComma ? InstExtraComma : InstNormal;
5143 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5144 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5145 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5146 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5147 Value *Val; LocTy Loc;
5148 unsigned Alignment = 0;
5149 bool AteExtraComma = false;
5150 bool isAtomic = false;
5151 AtomicOrdering Ordering = NotAtomic;
5152 SynchronizationScope Scope = CrossThread;
5154 if (Lex.getKind() == lltok::kw_atomic) {
5159 bool isVolatile = false;
5160 if (Lex.getKind() == lltok::kw_volatile) {
5165 if (ParseTypeAndValue(Val, Loc, PFS) ||
5166 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5167 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5170 if (!Val->getType()->isPointerTy() ||
5171 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
5172 return Error(Loc, "load operand must be a pointer to a first class type");
5173 if (isAtomic && !Alignment)
5174 return Error(Loc, "atomic load must have explicit non-zero alignment");
5175 if (Ordering == Release || Ordering == AcquireRelease)
5176 return Error(Loc, "atomic load cannot use Release ordering");
5178 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
5179 return AteExtraComma ? InstExtraComma : InstNormal;
5184 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5185 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5186 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5187 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5188 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5189 unsigned Alignment = 0;
5190 bool AteExtraComma = false;
5191 bool isAtomic = false;
5192 AtomicOrdering Ordering = NotAtomic;
5193 SynchronizationScope Scope = CrossThread;
5195 if (Lex.getKind() == lltok::kw_atomic) {
5200 bool isVolatile = false;
5201 if (Lex.getKind() == lltok::kw_volatile) {
5206 if (ParseTypeAndValue(Val, Loc, PFS) ||
5207 ParseToken(lltok::comma, "expected ',' after store operand") ||
5208 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5209 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5210 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5213 if (!Ptr->getType()->isPointerTy())
5214 return Error(PtrLoc, "store operand must be a pointer");
5215 if (!Val->getType()->isFirstClassType())
5216 return Error(Loc, "store operand must be a first class value");
5217 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5218 return Error(Loc, "stored value and pointer type do not match");
5219 if (isAtomic && !Alignment)
5220 return Error(Loc, "atomic store must have explicit non-zero alignment");
5221 if (Ordering == Acquire || Ordering == AcquireRelease)
5222 return Error(Loc, "atomic store cannot use Acquire ordering");
5224 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5225 return AteExtraComma ? InstExtraComma : InstNormal;
5229 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5230 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5231 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5232 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5233 bool AteExtraComma = false;
5234 AtomicOrdering SuccessOrdering = NotAtomic;
5235 AtomicOrdering FailureOrdering = NotAtomic;
5236 SynchronizationScope Scope = CrossThread;
5237 bool isVolatile = false;
5238 bool isWeak = false;
5240 if (EatIfPresent(lltok::kw_weak))
5243 if (EatIfPresent(lltok::kw_volatile))
5246 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5247 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5248 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5249 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5250 ParseTypeAndValue(New, NewLoc, PFS) ||
5251 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5252 ParseOrdering(FailureOrdering))
5255 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5256 return TokError("cmpxchg cannot be unordered");
5257 if (SuccessOrdering < FailureOrdering)
5258 return TokError("cmpxchg must be at least as ordered on success as failure");
5259 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5260 return TokError("cmpxchg failure ordering cannot include release semantics");
5261 if (!Ptr->getType()->isPointerTy())
5262 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5263 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5264 return Error(CmpLoc, "compare value and pointer type do not match");
5265 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5266 return Error(NewLoc, "new value and pointer type do not match");
5267 if (!New->getType()->isIntegerTy())
5268 return Error(NewLoc, "cmpxchg operand must be an integer");
5269 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5270 if (Size < 8 || (Size & (Size - 1)))
5271 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5274 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5275 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5276 CXI->setVolatile(isVolatile);
5277 CXI->setWeak(isWeak);
5279 return AteExtraComma ? InstExtraComma : InstNormal;
5283 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5284 /// 'singlethread'? AtomicOrdering
5285 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5286 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5287 bool AteExtraComma = false;
5288 AtomicOrdering Ordering = NotAtomic;
5289 SynchronizationScope Scope = CrossThread;
5290 bool isVolatile = false;
5291 AtomicRMWInst::BinOp Operation;
5293 if (EatIfPresent(lltok::kw_volatile))
5296 switch (Lex.getKind()) {
5297 default: return TokError("expected binary operation in atomicrmw");
5298 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5299 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5300 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5301 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5302 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5303 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5304 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5305 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5306 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5307 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5308 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5310 Lex.Lex(); // Eat the operation.
5312 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5313 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5314 ParseTypeAndValue(Val, ValLoc, PFS) ||
5315 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5318 if (Ordering == Unordered)
5319 return TokError("atomicrmw cannot be unordered");
5320 if (!Ptr->getType()->isPointerTy())
5321 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5322 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5323 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5324 if (!Val->getType()->isIntegerTy())
5325 return Error(ValLoc, "atomicrmw operand must be an integer");
5326 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5327 if (Size < 8 || (Size & (Size - 1)))
5328 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5331 AtomicRMWInst *RMWI =
5332 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5333 RMWI->setVolatile(isVolatile);
5335 return AteExtraComma ? InstExtraComma : InstNormal;
5339 /// ::= 'fence' 'singlethread'? AtomicOrdering
5340 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5341 AtomicOrdering Ordering = NotAtomic;
5342 SynchronizationScope Scope = CrossThread;
5343 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5346 if (Ordering == Unordered)
5347 return TokError("fence cannot be unordered");
5348 if (Ordering == Monotonic)
5349 return TokError("fence cannot be monotonic");
5351 Inst = new FenceInst(Context, Ordering, Scope);
5355 /// ParseGetElementPtr
5356 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5357 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5358 Value *Ptr = nullptr;
5359 Value *Val = nullptr;
5362 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5364 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
5366 Type *BaseType = Ptr->getType();
5367 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5368 if (!BasePointerType)
5369 return Error(Loc, "base of getelementptr must be a pointer");
5371 SmallVector<Value*, 16> Indices;
5372 bool AteExtraComma = false;
5373 while (EatIfPresent(lltok::comma)) {
5374 if (Lex.getKind() == lltok::MetadataVar) {
5375 AteExtraComma = true;
5378 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5379 if (!Val->getType()->getScalarType()->isIntegerTy())
5380 return Error(EltLoc, "getelementptr index must be an integer");
5381 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5382 return Error(EltLoc, "getelementptr index type missmatch");
5383 if (Val->getType()->isVectorTy()) {
5384 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5385 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5386 if (ValNumEl != PtrNumEl)
5387 return Error(EltLoc,
5388 "getelementptr vector index has a wrong number of elements");
5390 Indices.push_back(Val);
5393 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
5394 return Error(Loc, "base element of getelementptr must be sized");
5396 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
5397 return Error(Loc, "invalid getelementptr indices");
5398 Inst = GetElementPtrInst::Create(Ptr, Indices);
5400 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5401 return AteExtraComma ? InstExtraComma : InstNormal;
5404 /// ParseExtractValue
5405 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5406 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5407 Value *Val; LocTy Loc;
5408 SmallVector<unsigned, 4> Indices;
5410 if (ParseTypeAndValue(Val, Loc, PFS) ||
5411 ParseIndexList(Indices, AteExtraComma))
5414 if (!Val->getType()->isAggregateType())
5415 return Error(Loc, "extractvalue operand must be aggregate type");
5417 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5418 return Error(Loc, "invalid indices for extractvalue");
5419 Inst = ExtractValueInst::Create(Val, Indices);
5420 return AteExtraComma ? InstExtraComma : InstNormal;
5423 /// ParseInsertValue
5424 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5425 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5426 Value *Val0, *Val1; LocTy Loc0, Loc1;
5427 SmallVector<unsigned, 4> Indices;
5429 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5430 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5431 ParseTypeAndValue(Val1, Loc1, PFS) ||
5432 ParseIndexList(Indices, AteExtraComma))
5435 if (!Val0->getType()->isAggregateType())
5436 return Error(Loc0, "insertvalue operand must be aggregate type");
5438 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5440 return Error(Loc0, "invalid indices for insertvalue");
5441 if (IndexedType != Val1->getType())
5442 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5443 getTypeString(Val1->getType()) + "' instead of '" +
5444 getTypeString(IndexedType) + "'");
5445 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5446 return AteExtraComma ? InstExtraComma : InstNormal;
5449 //===----------------------------------------------------------------------===//
5450 // Embedded metadata.
5451 //===----------------------------------------------------------------------===//
5453 /// ParseMDNodeVector
5454 /// ::= { Element (',' Element)* }
5456 /// ::= 'null' | TypeAndValue
5457 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5458 if (ParseToken(lltok::lbrace, "expected '{' here"))
5461 // Check for an empty list.
5462 if (EatIfPresent(lltok::rbrace))
5466 // Null is a special case since it is typeless.
5467 if (EatIfPresent(lltok::kw_null)) {
5468 Elts.push_back(nullptr);
5473 if (ParseMetadata(MD, nullptr))
5476 } while (EatIfPresent(lltok::comma));
5478 return ParseToken(lltok::rbrace, "expected end of metadata node");
5481 //===----------------------------------------------------------------------===//
5482 // Use-list order directives.
5483 //===----------------------------------------------------------------------===//
5484 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5487 return Error(Loc, "value has no uses");
5489 unsigned NumUses = 0;
5490 SmallDenseMap<const Use *, unsigned, 16> Order;
5491 for (const Use &U : V->uses()) {
5492 if (++NumUses > Indexes.size())
5494 Order[&U] = Indexes[NumUses - 1];
5497 return Error(Loc, "value only has one use");
5498 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5499 return Error(Loc, "wrong number of indexes, expected " +
5500 Twine(std::distance(V->use_begin(), V->use_end())));
5502 V->sortUseList([&](const Use &L, const Use &R) {
5503 return Order.lookup(&L) < Order.lookup(&R);
5508 /// ParseUseListOrderIndexes
5509 /// ::= '{' uint32 (',' uint32)+ '}'
5510 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5511 SMLoc Loc = Lex.getLoc();
5512 if (ParseToken(lltok::lbrace, "expected '{' here"))
5514 if (Lex.getKind() == lltok::rbrace)
5515 return Lex.Error("expected non-empty list of uselistorder indexes");
5517 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5518 // indexes should be distinct numbers in the range [0, size-1], and should
5520 unsigned Offset = 0;
5522 bool IsOrdered = true;
5523 assert(Indexes.empty() && "Expected empty order vector");
5526 if (ParseUInt32(Index))
5529 // Update consistency checks.
5530 Offset += Index - Indexes.size();
5531 Max = std::max(Max, Index);
5532 IsOrdered &= Index == Indexes.size();
5534 Indexes.push_back(Index);
5535 } while (EatIfPresent(lltok::comma));
5537 if (ParseToken(lltok::rbrace, "expected '}' here"))
5540 if (Indexes.size() < 2)
5541 return Error(Loc, "expected >= 2 uselistorder indexes");
5542 if (Offset != 0 || Max >= Indexes.size())
5543 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5545 return Error(Loc, "expected uselistorder indexes to change the order");
5550 /// ParseUseListOrder
5551 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5552 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5553 SMLoc Loc = Lex.getLoc();
5554 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5558 SmallVector<unsigned, 16> Indexes;
5559 if (ParseTypeAndValue(V, PFS) ||
5560 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5561 ParseUseListOrderIndexes(Indexes))
5564 return sortUseListOrder(V, Indexes, Loc);
5567 /// ParseUseListOrderBB
5568 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5569 bool LLParser::ParseUseListOrderBB() {
5570 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5571 SMLoc Loc = Lex.getLoc();
5575 SmallVector<unsigned, 16> Indexes;
5576 if (ParseValID(Fn) ||
5577 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5578 ParseValID(Label) ||
5579 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5580 ParseUseListOrderIndexes(Indexes))
5583 // Check the function.
5585 if (Fn.Kind == ValID::t_GlobalName)
5586 GV = M->getNamedValue(Fn.StrVal);
5587 else if (Fn.Kind == ValID::t_GlobalID)
5588 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5590 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5592 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5593 auto *F = dyn_cast<Function>(GV);
5595 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5596 if (F->isDeclaration())
5597 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5599 // Check the basic block.
5600 if (Label.Kind == ValID::t_LocalID)
5601 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5602 if (Label.Kind != ValID::t_LocalName)
5603 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5604 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5606 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5607 if (!isa<BasicBlock>(V))
5608 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5610 return sortUseListOrder(V, Indexes, Loc);