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/ADT/STLExtras.h"
17 #include "llvm/AsmParser/SlotMapping.h"
18 #include "llvm/IR/AutoUpgrade.h"
19 #include "llvm/IR/CallingConv.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/SaveAndRestore.h"
33 #include "llvm/Support/raw_ostream.h"
36 static std::string getTypeString(Type *T) {
38 raw_string_ostream Tmp(Result);
43 /// Run: module ::= toplevelentity*
44 bool LLParser::Run() {
48 return ParseTopLevelEntities() ||
49 ValidateEndOfModule();
52 bool LLParser::parseStandaloneConstantValue(Constant *&C) {
56 if (ParseType(Ty) || parseConstantValue(Ty, C))
58 if (Lex.getKind() != lltok::Eof)
59 return Error(Lex.getLoc(), "expected end of string");
63 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65 bool LLParser::ValidateEndOfModule() {
66 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
67 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
69 // Handle any function attribute group forward references.
70 for (std::map<Value*, std::vector<unsigned> >::iterator
71 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
74 std::vector<unsigned> &Vec = I->second;
77 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
79 B.merge(NumberedAttrBuilders[*VI]);
81 if (Function *Fn = dyn_cast<Function>(V)) {
82 AttributeSet AS = Fn->getAttributes();
83 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
84 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
85 AS.getFnAttributes());
89 // If the alignment was parsed as an attribute, move to the alignment
91 if (FnAttrs.hasAlignmentAttr()) {
92 Fn->setAlignment(FnAttrs.getAlignment());
93 FnAttrs.removeAttribute(Attribute::Alignment);
96 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
97 AttributeSet::get(Context,
98 AttributeSet::FunctionIndex,
100 Fn->setAttributes(AS);
101 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
102 AttributeSet AS = CI->getAttributes();
103 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
104 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
105 AS.getFnAttributes());
107 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
108 AttributeSet::get(Context,
109 AttributeSet::FunctionIndex,
111 CI->setAttributes(AS);
112 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
113 AttributeSet AS = II->getAttributes();
114 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
115 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
116 AS.getFnAttributes());
118 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
119 AttributeSet::get(Context,
120 AttributeSet::FunctionIndex,
122 II->setAttributes(AS);
124 llvm_unreachable("invalid object with forward attribute group reference");
128 // If there are entries in ForwardRefBlockAddresses at this point, the
129 // function was never defined.
130 if (!ForwardRefBlockAddresses.empty())
131 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
132 "expected function name in blockaddress");
134 for (const auto &NT : NumberedTypes)
135 if (NT.second.second.isValid())
136 return Error(NT.second.second,
137 "use of undefined type '%" + Twine(NT.first) + "'");
139 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
140 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
141 if (I->second.second.isValid())
142 return Error(I->second.second,
143 "use of undefined type named '" + I->getKey() + "'");
145 if (!ForwardRefComdats.empty())
146 return Error(ForwardRefComdats.begin()->second,
147 "use of undefined comdat '$" +
148 ForwardRefComdats.begin()->first + "'");
150 if (!ForwardRefVals.empty())
151 return Error(ForwardRefVals.begin()->second.second,
152 "use of undefined value '@" + ForwardRefVals.begin()->first +
155 if (!ForwardRefValIDs.empty())
156 return Error(ForwardRefValIDs.begin()->second.second,
157 "use of undefined value '@" +
158 Twine(ForwardRefValIDs.begin()->first) + "'");
160 if (!ForwardRefMDNodes.empty())
161 return Error(ForwardRefMDNodes.begin()->second.second,
162 "use of undefined metadata '!" +
163 Twine(ForwardRefMDNodes.begin()->first) + "'");
165 // Resolve metadata cycles.
166 for (auto &N : NumberedMetadata) {
167 if (N.second && !N.second->isResolved())
168 N.second->resolveCycles();
171 // Look for intrinsic functions and CallInst that need to be upgraded
172 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
173 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
175 UpgradeDebugInfo(*M);
179 // Initialize the slot mapping.
180 // Because by this point we've parsed and validated everything, we can "steal"
181 // the mapping from LLParser as it doesn't need it anymore.
182 Slots->GlobalValues = std::move(NumberedVals);
183 Slots->MetadataNodes = std::move(NumberedMetadata);
188 //===----------------------------------------------------------------------===//
189 // Top-Level Entities
190 //===----------------------------------------------------------------------===//
192 bool LLParser::ParseTopLevelEntities() {
194 switch (Lex.getKind()) {
195 default: return TokError("expected top-level entity");
196 case lltok::Eof: return false;
197 case lltok::kw_declare: if (ParseDeclare()) return true; break;
198 case lltok::kw_define: if (ParseDefine()) return true; break;
199 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
200 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
201 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
202 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
203 case lltok::LocalVar: if (ParseNamedType()) return true; break;
204 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
205 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
206 case lltok::ComdatVar: if (parseComdat()) return true; break;
207 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
208 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
210 // The Global variable production with no name can have many different
211 // optional leading prefixes, the production is:
212 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
213 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
214 // ('constant'|'global') ...
215 case lltok::kw_private: // OptionalLinkage
216 case lltok::kw_internal: // OptionalLinkage
217 case lltok::kw_weak: // OptionalLinkage
218 case lltok::kw_weak_odr: // OptionalLinkage
219 case lltok::kw_linkonce: // OptionalLinkage
220 case lltok::kw_linkonce_odr: // OptionalLinkage
221 case lltok::kw_appending: // OptionalLinkage
222 case lltok::kw_common: // OptionalLinkage
223 case lltok::kw_extern_weak: // OptionalLinkage
224 case lltok::kw_external: // OptionalLinkage
225 case lltok::kw_default: // OptionalVisibility
226 case lltok::kw_hidden: // OptionalVisibility
227 case lltok::kw_protected: // OptionalVisibility
228 case lltok::kw_dllimport: // OptionalDLLStorageClass
229 case lltok::kw_dllexport: // OptionalDLLStorageClass
230 case lltok::kw_thread_local: // OptionalThreadLocal
231 case lltok::kw_addrspace: // OptionalAddrSpace
232 case lltok::kw_constant: // GlobalType
233 case lltok::kw_global: { // GlobalType
234 unsigned Linkage, Visibility, DLLStorageClass;
236 GlobalVariable::ThreadLocalMode TLM;
238 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
239 ParseOptionalVisibility(Visibility) ||
240 ParseOptionalDLLStorageClass(DLLStorageClass) ||
241 ParseOptionalThreadLocal(TLM) ||
242 parseOptionalUnnamedAddr(UnnamedAddr) ||
243 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
244 DLLStorageClass, TLM, UnnamedAddr))
249 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
250 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
251 case lltok::kw_uselistorder_bb:
252 if (ParseUseListOrderBB()) return true; break;
259 /// ::= 'module' 'asm' STRINGCONSTANT
260 bool LLParser::ParseModuleAsm() {
261 assert(Lex.getKind() == lltok::kw_module);
265 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
266 ParseStringConstant(AsmStr)) return true;
268 M->appendModuleInlineAsm(AsmStr);
273 /// ::= 'target' 'triple' '=' STRINGCONSTANT
274 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
275 bool LLParser::ParseTargetDefinition() {
276 assert(Lex.getKind() == lltok::kw_target);
279 default: return TokError("unknown target property");
280 case lltok::kw_triple:
282 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
283 ParseStringConstant(Str))
285 M->setTargetTriple(Str);
287 case lltok::kw_datalayout:
289 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
290 ParseStringConstant(Str))
292 M->setDataLayout(Str);
298 /// ::= 'deplibs' '=' '[' ']'
299 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
300 /// FIXME: Remove in 4.0. Currently parse, but ignore.
301 bool LLParser::ParseDepLibs() {
302 assert(Lex.getKind() == lltok::kw_deplibs);
304 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
305 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
308 if (EatIfPresent(lltok::rsquare))
313 if (ParseStringConstant(Str)) return true;
314 } while (EatIfPresent(lltok::comma));
316 return ParseToken(lltok::rsquare, "expected ']' at end of list");
319 /// ParseUnnamedType:
320 /// ::= LocalVarID '=' 'type' type
321 bool LLParser::ParseUnnamedType() {
322 LocTy TypeLoc = Lex.getLoc();
323 unsigned TypeID = Lex.getUIntVal();
324 Lex.Lex(); // eat LocalVarID;
326 if (ParseToken(lltok::equal, "expected '=' after name") ||
327 ParseToken(lltok::kw_type, "expected 'type' after '='"))
330 Type *Result = nullptr;
331 if (ParseStructDefinition(TypeLoc, "",
332 NumberedTypes[TypeID], Result)) return true;
334 if (!isa<StructType>(Result)) {
335 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
337 return Error(TypeLoc, "non-struct types may not be recursive");
338 Entry.first = Result;
339 Entry.second = SMLoc();
347 /// ::= LocalVar '=' 'type' type
348 bool LLParser::ParseNamedType() {
349 std::string Name = Lex.getStrVal();
350 LocTy NameLoc = Lex.getLoc();
351 Lex.Lex(); // eat LocalVar.
353 if (ParseToken(lltok::equal, "expected '=' after name") ||
354 ParseToken(lltok::kw_type, "expected 'type' after name"))
357 Type *Result = nullptr;
358 if (ParseStructDefinition(NameLoc, Name,
359 NamedTypes[Name], Result)) return true;
361 if (!isa<StructType>(Result)) {
362 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
364 return Error(NameLoc, "non-struct types may not be recursive");
365 Entry.first = Result;
366 Entry.second = SMLoc();
374 /// ::= 'declare' FunctionHeader
375 bool LLParser::ParseDeclare() {
376 assert(Lex.getKind() == lltok::kw_declare);
380 return ParseFunctionHeader(F, false);
384 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
385 bool LLParser::ParseDefine() {
386 assert(Lex.getKind() == lltok::kw_define);
390 return ParseFunctionHeader(F, true) ||
391 ParseOptionalFunctionMetadata(*F) ||
392 ParseFunctionBody(*F);
398 bool LLParser::ParseGlobalType(bool &IsConstant) {
399 if (Lex.getKind() == lltok::kw_constant)
401 else if (Lex.getKind() == lltok::kw_global)
405 return TokError("expected 'global' or 'constant'");
411 /// ParseUnnamedGlobal:
412 /// OptionalVisibility ALIAS ...
413 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
414 /// ... -> global variable
415 /// GlobalID '=' OptionalVisibility ALIAS ...
416 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
417 /// ... -> global variable
418 bool LLParser::ParseUnnamedGlobal() {
419 unsigned VarID = NumberedVals.size();
421 LocTy NameLoc = Lex.getLoc();
423 // Handle the GlobalID form.
424 if (Lex.getKind() == lltok::GlobalID) {
425 if (Lex.getUIntVal() != VarID)
426 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
428 Lex.Lex(); // eat GlobalID;
430 if (ParseToken(lltok::equal, "expected '=' after name"))
435 unsigned Linkage, Visibility, DLLStorageClass;
436 GlobalVariable::ThreadLocalMode TLM;
438 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
439 ParseOptionalVisibility(Visibility) ||
440 ParseOptionalDLLStorageClass(DLLStorageClass) ||
441 ParseOptionalThreadLocal(TLM) ||
442 parseOptionalUnnamedAddr(UnnamedAddr))
445 if (Lex.getKind() != lltok::kw_alias)
446 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
447 DLLStorageClass, TLM, UnnamedAddr);
448 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
452 /// ParseNamedGlobal:
453 /// GlobalVar '=' OptionalVisibility ALIAS ...
454 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
455 /// ... -> global variable
456 bool LLParser::ParseNamedGlobal() {
457 assert(Lex.getKind() == lltok::GlobalVar);
458 LocTy NameLoc = Lex.getLoc();
459 std::string Name = Lex.getStrVal();
463 unsigned Linkage, Visibility, DLLStorageClass;
464 GlobalVariable::ThreadLocalMode TLM;
466 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
467 ParseOptionalLinkage(Linkage, HasLinkage) ||
468 ParseOptionalVisibility(Visibility) ||
469 ParseOptionalDLLStorageClass(DLLStorageClass) ||
470 ParseOptionalThreadLocal(TLM) ||
471 parseOptionalUnnamedAddr(UnnamedAddr))
474 if (Lex.getKind() != lltok::kw_alias)
475 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
476 DLLStorageClass, TLM, UnnamedAddr);
478 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
482 bool LLParser::parseComdat() {
483 assert(Lex.getKind() == lltok::ComdatVar);
484 std::string Name = Lex.getStrVal();
485 LocTy NameLoc = Lex.getLoc();
488 if (ParseToken(lltok::equal, "expected '=' here"))
491 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
492 return TokError("expected comdat type");
494 Comdat::SelectionKind SK;
495 switch (Lex.getKind()) {
497 return TokError("unknown selection kind");
501 case lltok::kw_exactmatch:
502 SK = Comdat::ExactMatch;
504 case lltok::kw_largest:
505 SK = Comdat::Largest;
507 case lltok::kw_noduplicates:
508 SK = Comdat::NoDuplicates;
510 case lltok::kw_samesize:
511 SK = Comdat::SameSize;
516 // See if the comdat was forward referenced, if so, use the comdat.
517 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
518 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
519 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
520 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
523 if (I != ComdatSymTab.end())
526 C = M->getOrInsertComdat(Name);
527 C->setSelectionKind(SK);
533 // ::= '!' STRINGCONSTANT
534 bool LLParser::ParseMDString(MDString *&Result) {
536 if (ParseStringConstant(Str)) return true;
537 llvm::UpgradeMDStringConstant(Str);
538 Result = MDString::get(Context, Str);
543 // ::= '!' MDNodeNumber
544 bool LLParser::ParseMDNodeID(MDNode *&Result) {
545 // !{ ..., !42, ... }
547 if (ParseUInt32(MID))
550 // If not a forward reference, just return it now.
551 if (NumberedMetadata.count(MID)) {
552 Result = NumberedMetadata[MID];
556 // Otherwise, create MDNode forward reference.
557 auto &FwdRef = ForwardRefMDNodes[MID];
558 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
560 Result = FwdRef.first.get();
561 NumberedMetadata[MID].reset(Result);
565 /// ParseNamedMetadata:
566 /// !foo = !{ !1, !2 }
567 bool LLParser::ParseNamedMetadata() {
568 assert(Lex.getKind() == lltok::MetadataVar);
569 std::string Name = Lex.getStrVal();
572 if (ParseToken(lltok::equal, "expected '=' here") ||
573 ParseToken(lltok::exclaim, "Expected '!' here") ||
574 ParseToken(lltok::lbrace, "Expected '{' here"))
577 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
578 if (Lex.getKind() != lltok::rbrace)
580 if (ParseToken(lltok::exclaim, "Expected '!' here"))
584 if (ParseMDNodeID(N)) return true;
586 } while (EatIfPresent(lltok::comma));
588 return ParseToken(lltok::rbrace, "expected end of metadata node");
591 /// ParseStandaloneMetadata:
593 bool LLParser::ParseStandaloneMetadata() {
594 assert(Lex.getKind() == lltok::exclaim);
596 unsigned MetadataID = 0;
599 if (ParseUInt32(MetadataID) ||
600 ParseToken(lltok::equal, "expected '=' here"))
603 // Detect common error, from old metadata syntax.
604 if (Lex.getKind() == lltok::Type)
605 return TokError("unexpected type in metadata definition");
607 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
608 if (Lex.getKind() == lltok::MetadataVar) {
609 if (ParseSpecializedMDNode(Init, IsDistinct))
611 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
612 ParseMDTuple(Init, IsDistinct))
615 // See if this was forward referenced, if so, handle it.
616 auto FI = ForwardRefMDNodes.find(MetadataID);
617 if (FI != ForwardRefMDNodes.end()) {
618 FI->second.first->replaceAllUsesWith(Init);
619 ForwardRefMDNodes.erase(FI);
621 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
623 if (NumberedMetadata.count(MetadataID))
624 return TokError("Metadata id is already used");
625 NumberedMetadata[MetadataID].reset(Init);
631 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
632 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
633 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
637 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
638 /// OptionalDLLStorageClass OptionalThreadLocal
639 /// OptionalUnnamedAddr 'alias' Aliasee
644 /// Everything through OptionalUnnamedAddr has already been parsed.
646 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
647 unsigned Visibility, unsigned DLLStorageClass,
648 GlobalVariable::ThreadLocalMode TLM,
650 assert(Lex.getKind() == lltok::kw_alias);
653 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
655 if(!GlobalAlias::isValidLinkage(Linkage))
656 return Error(NameLoc, "invalid linkage type for alias");
658 if (!isValidVisibilityForLinkage(Visibility, L))
659 return Error(NameLoc,
660 "symbol with local linkage must have default visibility");
663 LocTy AliaseeLoc = Lex.getLoc();
664 if (Lex.getKind() != lltok::kw_bitcast &&
665 Lex.getKind() != lltok::kw_getelementptr &&
666 Lex.getKind() != lltok::kw_addrspacecast &&
667 Lex.getKind() != lltok::kw_inttoptr) {
668 if (ParseGlobalTypeAndValue(Aliasee))
671 // The bitcast dest type is not present, it is implied by the dest type.
675 if (ID.Kind != ValID::t_Constant)
676 return Error(AliaseeLoc, "invalid aliasee");
677 Aliasee = ID.ConstantVal;
680 Type *AliaseeType = Aliasee->getType();
681 auto *PTy = dyn_cast<PointerType>(AliaseeType);
683 return Error(AliaseeLoc, "An alias must have pointer type");
685 // Okay, create the alias but do not insert it into the module yet.
686 std::unique_ptr<GlobalAlias> GA(
687 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
688 Aliasee, /*Parent*/ nullptr));
689 GA->setThreadLocalMode(TLM);
690 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
691 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
692 GA->setUnnamedAddr(UnnamedAddr);
695 NumberedVals.push_back(GA.get());
697 // See if this value already exists in the symbol table. If so, it is either
698 // a redefinition or a definition of a forward reference.
699 if (GlobalValue *Val = M->getNamedValue(Name)) {
700 // See if this was a redefinition. If so, there is no entry in
702 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
703 I = ForwardRefVals.find(Name);
704 if (I == ForwardRefVals.end())
705 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
707 // Otherwise, this was a definition of forward ref. Verify that types
709 if (Val->getType() != GA->getType())
710 return Error(NameLoc,
711 "forward reference and definition of alias have different types");
713 // If they agree, just RAUW the old value with the alias and remove the
715 Val->replaceAllUsesWith(GA.get());
716 Val->eraseFromParent();
717 ForwardRefVals.erase(I);
720 // Insert into the module, we know its name won't collide now.
721 M->getAliasList().push_back(GA.get());
722 assert(GA->getName() == Name && "Should not be a name conflict!");
724 // The module owns this now
731 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
732 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
733 /// OptionalExternallyInitialized GlobalType Type Const
734 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
735 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
736 /// OptionalExternallyInitialized GlobalType Type Const
738 /// Everything up to and including OptionalUnnamedAddr has been parsed
741 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
742 unsigned Linkage, bool HasLinkage,
743 unsigned Visibility, unsigned DLLStorageClass,
744 GlobalVariable::ThreadLocalMode TLM,
746 if (!isValidVisibilityForLinkage(Visibility, Linkage))
747 return Error(NameLoc,
748 "symbol with local linkage must have default visibility");
751 bool IsConstant, IsExternallyInitialized;
752 LocTy IsExternallyInitializedLoc;
756 if (ParseOptionalAddrSpace(AddrSpace) ||
757 ParseOptionalToken(lltok::kw_externally_initialized,
758 IsExternallyInitialized,
759 &IsExternallyInitializedLoc) ||
760 ParseGlobalType(IsConstant) ||
761 ParseType(Ty, TyLoc))
764 // If the linkage is specified and is external, then no initializer is
766 Constant *Init = nullptr;
767 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
768 Linkage != GlobalValue::ExternalLinkage)) {
769 if (ParseGlobalValue(Ty, Init))
773 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
774 return Error(TyLoc, "invalid type for global variable");
776 GlobalValue *GVal = nullptr;
778 // See if the global was forward referenced, if so, use the global.
780 GVal = M->getNamedValue(Name);
782 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
783 return Error(NameLoc, "redefinition of global '@" + Name + "'");
786 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
787 I = ForwardRefValIDs.find(NumberedVals.size());
788 if (I != ForwardRefValIDs.end()) {
789 GVal = I->second.first;
790 ForwardRefValIDs.erase(I);
796 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
797 Name, nullptr, GlobalVariable::NotThreadLocal,
800 if (GVal->getValueType() != Ty)
802 "forward reference and definition of global have different types");
804 GV = cast<GlobalVariable>(GVal);
806 // Move the forward-reference to the correct spot in the module.
807 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
811 NumberedVals.push_back(GV);
813 // Set the parsed properties on the global.
815 GV->setInitializer(Init);
816 GV->setConstant(IsConstant);
817 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
818 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
819 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
820 GV->setExternallyInitialized(IsExternallyInitialized);
821 GV->setThreadLocalMode(TLM);
822 GV->setUnnamedAddr(UnnamedAddr);
824 // Parse attributes on the global.
825 while (Lex.getKind() == lltok::comma) {
828 if (Lex.getKind() == lltok::kw_section) {
830 GV->setSection(Lex.getStrVal());
831 if (ParseToken(lltok::StringConstant, "expected global section string"))
833 } else if (Lex.getKind() == lltok::kw_align) {
835 if (ParseOptionalAlignment(Alignment)) return true;
836 GV->setAlignment(Alignment);
839 if (parseOptionalComdat(Name, C))
844 return TokError("unknown global variable property!");
851 /// ParseUnnamedAttrGrp
852 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
853 bool LLParser::ParseUnnamedAttrGrp() {
854 assert(Lex.getKind() == lltok::kw_attributes);
855 LocTy AttrGrpLoc = Lex.getLoc();
858 if (Lex.getKind() != lltok::AttrGrpID)
859 return TokError("expected attribute group id");
861 unsigned VarID = Lex.getUIntVal();
862 std::vector<unsigned> unused;
866 if (ParseToken(lltok::equal, "expected '=' here") ||
867 ParseToken(lltok::lbrace, "expected '{' here") ||
868 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
870 ParseToken(lltok::rbrace, "expected end of attribute group"))
873 if (!NumberedAttrBuilders[VarID].hasAttributes())
874 return Error(AttrGrpLoc, "attribute group has no attributes");
879 /// ParseFnAttributeValuePairs
880 /// ::= <attr> | <attr> '=' <value>
881 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
882 std::vector<unsigned> &FwdRefAttrGrps,
883 bool inAttrGrp, LocTy &BuiltinLoc) {
884 bool HaveError = false;
889 lltok::Kind Token = Lex.getKind();
890 if (Token == lltok::kw_builtin)
891 BuiltinLoc = Lex.getLoc();
894 if (!inAttrGrp) return HaveError;
895 return Error(Lex.getLoc(), "unterminated attribute group");
900 case lltok::AttrGrpID: {
901 // Allow a function to reference an attribute group:
903 // define void @foo() #1 { ... }
907 "cannot have an attribute group reference in an attribute group");
909 unsigned AttrGrpNum = Lex.getUIntVal();
910 if (inAttrGrp) break;
912 // Save the reference to the attribute group. We'll fill it in later.
913 FwdRefAttrGrps.push_back(AttrGrpNum);
916 // Target-dependent attributes:
917 case lltok::StringConstant: {
918 if (ParseStringAttribute(B))
923 // Target-independent attributes:
924 case lltok::kw_align: {
925 // As a hack, we allow function alignment to be initially parsed as an
926 // attribute on a function declaration/definition or added to an attribute
927 // group and later moved to the alignment field.
931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
935 if (ParseOptionalAlignment(Alignment))
938 B.addAlignmentAttr(Alignment);
941 case lltok::kw_alignstack: {
945 if (ParseToken(lltok::equal, "expected '=' here") ||
946 ParseUInt32(Alignment))
949 if (ParseOptionalStackAlignment(Alignment))
952 B.addStackAlignmentAttr(Alignment);
955 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
956 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
957 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
958 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
959 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
960 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
961 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
962 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
963 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
964 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
965 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
966 case lltok::kw_noimplicitfloat:
967 B.addAttribute(Attribute::NoImplicitFloat); break;
968 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
969 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
970 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
971 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
972 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
973 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
974 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
975 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
976 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
977 case lltok::kw_returns_twice:
978 B.addAttribute(Attribute::ReturnsTwice); break;
979 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
980 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
981 case lltok::kw_sspstrong:
982 B.addAttribute(Attribute::StackProtectStrong); break;
983 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
984 case lltok::kw_sanitize_address:
985 B.addAttribute(Attribute::SanitizeAddress); break;
986 case lltok::kw_sanitize_thread:
987 B.addAttribute(Attribute::SanitizeThread); break;
988 case lltok::kw_sanitize_memory:
989 B.addAttribute(Attribute::SanitizeMemory); break;
990 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
993 case lltok::kw_inreg:
994 case lltok::kw_signext:
995 case lltok::kw_zeroext:
998 "invalid use of attribute on a function");
1000 case lltok::kw_byval:
1001 case lltok::kw_dereferenceable:
1002 case lltok::kw_dereferenceable_or_null:
1003 case lltok::kw_inalloca:
1004 case lltok::kw_nest:
1005 case lltok::kw_noalias:
1006 case lltok::kw_nocapture:
1007 case lltok::kw_nonnull:
1008 case lltok::kw_returned:
1009 case lltok::kw_sret:
1012 "invalid use of parameter-only attribute on a function");
1020 //===----------------------------------------------------------------------===//
1021 // GlobalValue Reference/Resolution Routines.
1022 //===----------------------------------------------------------------------===//
1024 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1025 /// forward reference record if needed. This can return null if the value
1026 /// exists but does not have the right type.
1027 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1029 PointerType *PTy = dyn_cast<PointerType>(Ty);
1031 Error(Loc, "global variable reference must have pointer type");
1035 // Look this name up in the normal function symbol table.
1037 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1039 // If this is a forward reference for the value, see if we already created a
1040 // forward ref record.
1042 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1043 I = ForwardRefVals.find(Name);
1044 if (I != ForwardRefVals.end())
1045 Val = I->second.first;
1048 // If we have the value in the symbol table or fwd-ref table, return it.
1050 if (Val->getType() == Ty) return Val;
1051 Error(Loc, "'@" + Name + "' defined with type '" +
1052 getTypeString(Val->getType()) + "'");
1056 // Otherwise, create a new forward reference for this value and remember it.
1057 GlobalValue *FwdVal;
1058 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1059 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1061 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1062 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1063 nullptr, GlobalVariable::NotThreadLocal,
1064 PTy->getAddressSpace());
1066 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1070 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1071 PointerType *PTy = dyn_cast<PointerType>(Ty);
1073 Error(Loc, "global variable reference must have pointer type");
1077 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1079 // If this is a forward reference for the value, see if we already created a
1080 // forward ref record.
1082 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1083 I = ForwardRefValIDs.find(ID);
1084 if (I != ForwardRefValIDs.end())
1085 Val = I->second.first;
1088 // If we have the value in the symbol table or fwd-ref table, return it.
1090 if (Val->getType() == Ty) return Val;
1091 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1092 getTypeString(Val->getType()) + "'");
1096 // Otherwise, create a new forward reference for this value and remember it.
1097 GlobalValue *FwdVal;
1098 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1099 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1101 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1102 GlobalValue::ExternalWeakLinkage, nullptr, "");
1104 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1109 //===----------------------------------------------------------------------===//
1110 // Comdat Reference/Resolution Routines.
1111 //===----------------------------------------------------------------------===//
1113 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1114 // Look this name up in the comdat symbol table.
1115 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1116 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1117 if (I != ComdatSymTab.end())
1120 // Otherwise, create a new forward reference for this value and remember it.
1121 Comdat *C = M->getOrInsertComdat(Name);
1122 ForwardRefComdats[Name] = Loc;
1127 //===----------------------------------------------------------------------===//
1129 //===----------------------------------------------------------------------===//
1131 /// ParseToken - If the current token has the specified kind, eat it and return
1132 /// success. Otherwise, emit the specified error and return failure.
1133 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1134 if (Lex.getKind() != T)
1135 return TokError(ErrMsg);
1140 /// ParseStringConstant
1141 /// ::= StringConstant
1142 bool LLParser::ParseStringConstant(std::string &Result) {
1143 if (Lex.getKind() != lltok::StringConstant)
1144 return TokError("expected string constant");
1145 Result = Lex.getStrVal();
1152 bool LLParser::ParseUInt32(unsigned &Val) {
1153 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1154 return TokError("expected integer");
1155 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1156 if (Val64 != unsigned(Val64))
1157 return TokError("expected 32-bit integer (too large)");
1165 bool LLParser::ParseUInt64(uint64_t &Val) {
1166 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1167 return TokError("expected integer");
1168 Val = Lex.getAPSIntVal().getLimitedValue();
1174 /// := 'localdynamic'
1175 /// := 'initialexec'
1177 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1178 switch (Lex.getKind()) {
1180 return TokError("expected localdynamic, initialexec or localexec");
1181 case lltok::kw_localdynamic:
1182 TLM = GlobalVariable::LocalDynamicTLSModel;
1184 case lltok::kw_initialexec:
1185 TLM = GlobalVariable::InitialExecTLSModel;
1187 case lltok::kw_localexec:
1188 TLM = GlobalVariable::LocalExecTLSModel;
1196 /// ParseOptionalThreadLocal
1198 /// := 'thread_local'
1199 /// := 'thread_local' '(' tlsmodel ')'
1200 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1201 TLM = GlobalVariable::NotThreadLocal;
1202 if (!EatIfPresent(lltok::kw_thread_local))
1205 TLM = GlobalVariable::GeneralDynamicTLSModel;
1206 if (Lex.getKind() == lltok::lparen) {
1208 return ParseTLSModel(TLM) ||
1209 ParseToken(lltok::rparen, "expected ')' after thread local model");
1214 /// ParseOptionalAddrSpace
1216 /// := 'addrspace' '(' uint32 ')'
1217 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1219 if (!EatIfPresent(lltok::kw_addrspace))
1221 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1222 ParseUInt32(AddrSpace) ||
1223 ParseToken(lltok::rparen, "expected ')' in address space");
1226 /// ParseStringAttribute
1227 /// := StringConstant
1228 /// := StringConstant '=' StringConstant
1229 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1230 std::string Attr = Lex.getStrVal();
1233 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1235 B.addAttribute(Attr, Val);
1239 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1240 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1241 bool HaveError = false;
1246 lltok::Kind Token = Lex.getKind();
1248 default: // End of attributes.
1250 case lltok::StringConstant: {
1251 if (ParseStringAttribute(B))
1255 case lltok::kw_align: {
1257 if (ParseOptionalAlignment(Alignment))
1259 B.addAlignmentAttr(Alignment);
1262 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1263 case lltok::kw_dereferenceable: {
1265 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1267 B.addDereferenceableAttr(Bytes);
1270 case lltok::kw_dereferenceable_or_null: {
1272 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1274 B.addDereferenceableOrNullAttr(Bytes);
1277 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1278 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1279 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1280 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1281 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1282 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1283 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1284 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1285 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1286 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1287 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1288 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1290 case lltok::kw_alignstack:
1291 case lltok::kw_alwaysinline:
1292 case lltok::kw_argmemonly:
1293 case lltok::kw_builtin:
1294 case lltok::kw_inlinehint:
1295 case lltok::kw_jumptable:
1296 case lltok::kw_minsize:
1297 case lltok::kw_naked:
1298 case lltok::kw_nobuiltin:
1299 case lltok::kw_noduplicate:
1300 case lltok::kw_noimplicitfloat:
1301 case lltok::kw_noinline:
1302 case lltok::kw_nonlazybind:
1303 case lltok::kw_noredzone:
1304 case lltok::kw_noreturn:
1305 case lltok::kw_nounwind:
1306 case lltok::kw_optnone:
1307 case lltok::kw_optsize:
1308 case lltok::kw_returns_twice:
1309 case lltok::kw_sanitize_address:
1310 case lltok::kw_sanitize_memory:
1311 case lltok::kw_sanitize_thread:
1313 case lltok::kw_sspreq:
1314 case lltok::kw_sspstrong:
1315 case lltok::kw_safestack:
1316 case lltok::kw_uwtable:
1317 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1325 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1326 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1327 bool HaveError = false;
1332 lltok::Kind Token = Lex.getKind();
1334 default: // End of attributes.
1336 case lltok::StringConstant: {
1337 if (ParseStringAttribute(B))
1341 case lltok::kw_dereferenceable: {
1343 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1345 B.addDereferenceableAttr(Bytes);
1348 case lltok::kw_dereferenceable_or_null: {
1350 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1352 B.addDereferenceableOrNullAttr(Bytes);
1355 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1356 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1357 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1358 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1359 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1362 case lltok::kw_align:
1363 case lltok::kw_byval:
1364 case lltok::kw_inalloca:
1365 case lltok::kw_nest:
1366 case lltok::kw_nocapture:
1367 case lltok::kw_returned:
1368 case lltok::kw_sret:
1369 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1372 case lltok::kw_alignstack:
1373 case lltok::kw_alwaysinline:
1374 case lltok::kw_argmemonly:
1375 case lltok::kw_builtin:
1376 case lltok::kw_cold:
1377 case lltok::kw_inlinehint:
1378 case lltok::kw_jumptable:
1379 case lltok::kw_minsize:
1380 case lltok::kw_naked:
1381 case lltok::kw_nobuiltin:
1382 case lltok::kw_noduplicate:
1383 case lltok::kw_noimplicitfloat:
1384 case lltok::kw_noinline:
1385 case lltok::kw_nonlazybind:
1386 case lltok::kw_noredzone:
1387 case lltok::kw_noreturn:
1388 case lltok::kw_nounwind:
1389 case lltok::kw_optnone:
1390 case lltok::kw_optsize:
1391 case lltok::kw_returns_twice:
1392 case lltok::kw_sanitize_address:
1393 case lltok::kw_sanitize_memory:
1394 case lltok::kw_sanitize_thread:
1396 case lltok::kw_sspreq:
1397 case lltok::kw_sspstrong:
1398 case lltok::kw_safestack:
1399 case lltok::kw_uwtable:
1400 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1403 case lltok::kw_readnone:
1404 case lltok::kw_readonly:
1405 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1412 /// ParseOptionalLinkage
1419 /// ::= 'linkonce_odr'
1420 /// ::= 'available_externally'
1423 /// ::= 'extern_weak'
1425 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1427 switch (Lex.getKind()) {
1428 default: Res=GlobalValue::ExternalLinkage; return false;
1429 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1430 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1431 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1432 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1433 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1434 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1435 case lltok::kw_available_externally:
1436 Res = GlobalValue::AvailableExternallyLinkage;
1438 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1439 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1440 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1441 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1448 /// ParseOptionalVisibility
1454 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1455 switch (Lex.getKind()) {
1456 default: Res = GlobalValue::DefaultVisibility; return false;
1457 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1458 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1459 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1465 /// ParseOptionalDLLStorageClass
1470 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1471 switch (Lex.getKind()) {
1472 default: Res = GlobalValue::DefaultStorageClass; return false;
1473 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1474 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1480 /// ParseOptionalCallingConv
1484 /// ::= 'intel_ocl_bicc'
1486 /// ::= 'x86_stdcallcc'
1487 /// ::= 'x86_fastcallcc'
1488 /// ::= 'x86_thiscallcc'
1489 /// ::= 'x86_vectorcallcc'
1490 /// ::= 'arm_apcscc'
1491 /// ::= 'arm_aapcscc'
1492 /// ::= 'arm_aapcs_vfpcc'
1493 /// ::= 'msp430_intrcc'
1494 /// ::= 'ptx_kernel'
1495 /// ::= 'ptx_device'
1497 /// ::= 'spir_kernel'
1498 /// ::= 'x86_64_sysvcc'
1499 /// ::= 'x86_64_win64cc'
1500 /// ::= 'webkit_jscc'
1502 /// ::= 'preserve_mostcc'
1503 /// ::= 'preserve_allcc'
1507 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1508 switch (Lex.getKind()) {
1509 default: CC = CallingConv::C; return false;
1510 case lltok::kw_ccc: CC = CallingConv::C; break;
1511 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1512 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1513 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1514 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1515 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1516 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1517 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1518 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1519 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1520 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1521 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1522 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1523 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1524 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1525 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1526 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1527 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1528 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1529 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1530 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1531 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1532 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1533 case lltok::kw_cc: {
1535 return ParseUInt32(CC);
1543 /// ParseMetadataAttachment
1545 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1546 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1548 std::string Name = Lex.getStrVal();
1549 Kind = M->getMDKindID(Name);
1552 return ParseMDNode(MD);
1555 /// ParseInstructionMetadata
1556 /// ::= !dbg !42 (',' !dbg !57)*
1557 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1559 if (Lex.getKind() != lltok::MetadataVar)
1560 return TokError("expected metadata after comma");
1564 if (ParseMetadataAttachment(MDK, N))
1567 Inst.setMetadata(MDK, N);
1568 if (MDK == LLVMContext::MD_tbaa)
1569 InstsWithTBAATag.push_back(&Inst);
1571 // If this is the end of the list, we're done.
1572 } while (EatIfPresent(lltok::comma));
1576 /// ParseOptionalFunctionMetadata
1578 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1579 while (Lex.getKind() == lltok::MetadataVar) {
1582 if (ParseMetadataAttachment(MDK, N))
1585 F.setMetadata(MDK, N);
1590 /// ParseOptionalAlignment
1593 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1595 if (!EatIfPresent(lltok::kw_align))
1597 LocTy AlignLoc = Lex.getLoc();
1598 if (ParseUInt32(Alignment)) return true;
1599 if (!isPowerOf2_32(Alignment))
1600 return Error(AlignLoc, "alignment is not a power of two");
1601 if (Alignment > Value::MaximumAlignment)
1602 return Error(AlignLoc, "huge alignments are not supported yet");
1606 /// ParseOptionalDerefAttrBytes
1608 /// ::= AttrKind '(' 4 ')'
1610 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1611 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1613 assert((AttrKind == lltok::kw_dereferenceable ||
1614 AttrKind == lltok::kw_dereferenceable_or_null) &&
1618 if (!EatIfPresent(AttrKind))
1620 LocTy ParenLoc = Lex.getLoc();
1621 if (!EatIfPresent(lltok::lparen))
1622 return Error(ParenLoc, "expected '('");
1623 LocTy DerefLoc = Lex.getLoc();
1624 if (ParseUInt64(Bytes)) return true;
1625 ParenLoc = Lex.getLoc();
1626 if (!EatIfPresent(lltok::rparen))
1627 return Error(ParenLoc, "expected ')'");
1629 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1633 /// ParseOptionalCommaAlign
1637 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1639 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1640 bool &AteExtraComma) {
1641 AteExtraComma = false;
1642 while (EatIfPresent(lltok::comma)) {
1643 // Metadata at the end is an early exit.
1644 if (Lex.getKind() == lltok::MetadataVar) {
1645 AteExtraComma = true;
1649 if (Lex.getKind() != lltok::kw_align)
1650 return Error(Lex.getLoc(), "expected metadata or 'align'");
1652 if (ParseOptionalAlignment(Alignment)) return true;
1658 /// ParseScopeAndOrdering
1659 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1662 /// This sets Scope and Ordering to the parsed values.
1663 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1664 AtomicOrdering &Ordering) {
1668 Scope = CrossThread;
1669 if (EatIfPresent(lltok::kw_singlethread))
1670 Scope = SingleThread;
1672 return ParseOrdering(Ordering);
1676 /// ::= AtomicOrdering
1678 /// This sets Ordering to the parsed value.
1679 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1680 switch (Lex.getKind()) {
1681 default: return TokError("Expected ordering on atomic instruction");
1682 case lltok::kw_unordered: Ordering = Unordered; break;
1683 case lltok::kw_monotonic: Ordering = Monotonic; break;
1684 case lltok::kw_acquire: Ordering = Acquire; break;
1685 case lltok::kw_release: Ordering = Release; break;
1686 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1687 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1693 /// ParseOptionalStackAlignment
1695 /// ::= 'alignstack' '(' 4 ')'
1696 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1698 if (!EatIfPresent(lltok::kw_alignstack))
1700 LocTy ParenLoc = Lex.getLoc();
1701 if (!EatIfPresent(lltok::lparen))
1702 return Error(ParenLoc, "expected '('");
1703 LocTy AlignLoc = Lex.getLoc();
1704 if (ParseUInt32(Alignment)) return true;
1705 ParenLoc = Lex.getLoc();
1706 if (!EatIfPresent(lltok::rparen))
1707 return Error(ParenLoc, "expected ')'");
1708 if (!isPowerOf2_32(Alignment))
1709 return Error(AlignLoc, "stack alignment is not a power of two");
1713 /// ParseIndexList - This parses the index list for an insert/extractvalue
1714 /// instruction. This sets AteExtraComma in the case where we eat an extra
1715 /// comma at the end of the line and find that it is followed by metadata.
1716 /// Clients that don't allow metadata can call the version of this function that
1717 /// only takes one argument.
1720 /// ::= (',' uint32)+
1722 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1723 bool &AteExtraComma) {
1724 AteExtraComma = false;
1726 if (Lex.getKind() != lltok::comma)
1727 return TokError("expected ',' as start of index list");
1729 while (EatIfPresent(lltok::comma)) {
1730 if (Lex.getKind() == lltok::MetadataVar) {
1731 if (Indices.empty()) return TokError("expected index");
1732 AteExtraComma = true;
1736 if (ParseUInt32(Idx)) return true;
1737 Indices.push_back(Idx);
1743 //===----------------------------------------------------------------------===//
1745 //===----------------------------------------------------------------------===//
1747 /// ParseType - Parse a type.
1748 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1749 SMLoc TypeLoc = Lex.getLoc();
1750 switch (Lex.getKind()) {
1752 return TokError(Msg);
1754 // Type ::= 'float' | 'void' (etc)
1755 Result = Lex.getTyVal();
1759 // Type ::= StructType
1760 if (ParseAnonStructType(Result, false))
1763 case lltok::lsquare:
1764 // Type ::= '[' ... ']'
1765 Lex.Lex(); // eat the lsquare.
1766 if (ParseArrayVectorType(Result, false))
1769 case lltok::less: // Either vector or packed struct.
1770 // Type ::= '<' ... '>'
1772 if (Lex.getKind() == lltok::lbrace) {
1773 if (ParseAnonStructType(Result, true) ||
1774 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1776 } else if (ParseArrayVectorType(Result, true))
1779 case lltok::LocalVar: {
1781 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1783 // If the type hasn't been defined yet, create a forward definition and
1784 // remember where that forward def'n was seen (in case it never is defined).
1786 Entry.first = StructType::create(Context, Lex.getStrVal());
1787 Entry.second = Lex.getLoc();
1789 Result = Entry.first;
1794 case lltok::LocalVarID: {
1796 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1798 // If the type hasn't been defined yet, create a forward definition and
1799 // remember where that forward def'n was seen (in case it never is defined).
1801 Entry.first = StructType::create(Context);
1802 Entry.second = Lex.getLoc();
1804 Result = Entry.first;
1810 // Parse the type suffixes.
1812 switch (Lex.getKind()) {
1815 if (!AllowVoid && Result->isVoidTy())
1816 return Error(TypeLoc, "void type only allowed for function results");
1819 // Type ::= Type '*'
1821 if (Result->isLabelTy())
1822 return TokError("basic block pointers are invalid");
1823 if (Result->isVoidTy())
1824 return TokError("pointers to void are invalid - use i8* instead");
1825 if (!PointerType::isValidElementType(Result))
1826 return TokError("pointer to this type is invalid");
1827 Result = PointerType::getUnqual(Result);
1831 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1832 case lltok::kw_addrspace: {
1833 if (Result->isLabelTy())
1834 return TokError("basic block pointers are invalid");
1835 if (Result->isVoidTy())
1836 return TokError("pointers to void are invalid; use i8* instead");
1837 if (!PointerType::isValidElementType(Result))
1838 return TokError("pointer to this type is invalid");
1840 if (ParseOptionalAddrSpace(AddrSpace) ||
1841 ParseToken(lltok::star, "expected '*' in address space"))
1844 Result = PointerType::get(Result, AddrSpace);
1848 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1850 if (ParseFunctionType(Result))
1857 /// ParseParameterList
1859 /// ::= '(' Arg (',' Arg)* ')'
1861 /// ::= Type OptionalAttributes Value OptionalAttributes
1862 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1863 PerFunctionState &PFS, bool IsMustTailCall,
1864 bool InVarArgsFunc) {
1865 if (ParseToken(lltok::lparen, "expected '(' in call"))
1868 unsigned AttrIndex = 1;
1869 while (Lex.getKind() != lltok::rparen) {
1870 // If this isn't the first argument, we need a comma.
1871 if (!ArgList.empty() &&
1872 ParseToken(lltok::comma, "expected ',' in argument list"))
1875 // Parse an ellipsis if this is a musttail call in a variadic function.
1876 if (Lex.getKind() == lltok::dotdotdot) {
1877 const char *Msg = "unexpected ellipsis in argument list for ";
1878 if (!IsMustTailCall)
1879 return TokError(Twine(Msg) + "non-musttail call");
1881 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1882 Lex.Lex(); // Lex the '...', it is purely for readability.
1883 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1886 // Parse the argument.
1888 Type *ArgTy = nullptr;
1889 AttrBuilder ArgAttrs;
1891 if (ParseType(ArgTy, ArgLoc))
1894 if (ArgTy->isMetadataTy()) {
1895 if (ParseMetadataAsValue(V, PFS))
1898 // Otherwise, handle normal operands.
1899 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1902 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1907 if (IsMustTailCall && InVarArgsFunc)
1908 return TokError("expected '...' at end of argument list for musttail call "
1909 "in varargs function");
1911 Lex.Lex(); // Lex the ')'.
1917 /// ParseArgumentList - Parse the argument list for a function type or function
1919 /// ::= '(' ArgTypeListI ')'
1923 /// ::= ArgTypeList ',' '...'
1924 /// ::= ArgType (',' ArgType)*
1926 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1929 assert(Lex.getKind() == lltok::lparen);
1930 Lex.Lex(); // eat the (.
1932 if (Lex.getKind() == lltok::rparen) {
1934 } else if (Lex.getKind() == lltok::dotdotdot) {
1938 LocTy TypeLoc = Lex.getLoc();
1939 Type *ArgTy = nullptr;
1943 if (ParseType(ArgTy) ||
1944 ParseOptionalParamAttrs(Attrs)) return true;
1946 if (ArgTy->isVoidTy())
1947 return Error(TypeLoc, "argument can not have void type");
1949 if (Lex.getKind() == lltok::LocalVar) {
1950 Name = Lex.getStrVal();
1954 if (!FunctionType::isValidArgumentType(ArgTy))
1955 return Error(TypeLoc, "invalid type for function argument");
1957 unsigned AttrIndex = 1;
1958 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1959 AttrIndex++, Attrs),
1962 while (EatIfPresent(lltok::comma)) {
1963 // Handle ... at end of arg list.
1964 if (EatIfPresent(lltok::dotdotdot)) {
1969 // Otherwise must be an argument type.
1970 TypeLoc = Lex.getLoc();
1971 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1973 if (ArgTy->isVoidTy())
1974 return Error(TypeLoc, "argument can not have void type");
1976 if (Lex.getKind() == lltok::LocalVar) {
1977 Name = Lex.getStrVal();
1983 if (!ArgTy->isFirstClassType())
1984 return Error(TypeLoc, "invalid type for function argument");
1986 ArgList.emplace_back(
1988 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1993 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1996 /// ParseFunctionType
1997 /// ::= Type ArgumentList OptionalAttrs
1998 bool LLParser::ParseFunctionType(Type *&Result) {
1999 assert(Lex.getKind() == lltok::lparen);
2001 if (!FunctionType::isValidReturnType(Result))
2002 return TokError("invalid function return type");
2004 SmallVector<ArgInfo, 8> ArgList;
2006 if (ParseArgumentList(ArgList, isVarArg))
2009 // Reject names on the arguments lists.
2010 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2011 if (!ArgList[i].Name.empty())
2012 return Error(ArgList[i].Loc, "argument name invalid in function type");
2013 if (ArgList[i].Attrs.hasAttributes(i + 1))
2014 return Error(ArgList[i].Loc,
2015 "argument attributes invalid in function type");
2018 SmallVector<Type*, 16> ArgListTy;
2019 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2020 ArgListTy.push_back(ArgList[i].Ty);
2022 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2026 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2028 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2029 SmallVector<Type*, 8> Elts;
2030 if (ParseStructBody(Elts)) return true;
2032 Result = StructType::get(Context, Elts, Packed);
2036 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2037 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2038 std::pair<Type*, LocTy> &Entry,
2040 // If the type was already defined, diagnose the redefinition.
2041 if (Entry.first && !Entry.second.isValid())
2042 return Error(TypeLoc, "redefinition of type");
2044 // If we have opaque, just return without filling in the definition for the
2045 // struct. This counts as a definition as far as the .ll file goes.
2046 if (EatIfPresent(lltok::kw_opaque)) {
2047 // This type is being defined, so clear the location to indicate this.
2048 Entry.second = SMLoc();
2050 // If this type number has never been uttered, create it.
2052 Entry.first = StructType::create(Context, Name);
2053 ResultTy = Entry.first;
2057 // If the type starts with '<', then it is either a packed struct or a vector.
2058 bool isPacked = EatIfPresent(lltok::less);
2060 // If we don't have a struct, then we have a random type alias, which we
2061 // accept for compatibility with old files. These types are not allowed to be
2062 // forward referenced and not allowed to be recursive.
2063 if (Lex.getKind() != lltok::lbrace) {
2065 return Error(TypeLoc, "forward references to non-struct type");
2069 return ParseArrayVectorType(ResultTy, true);
2070 return ParseType(ResultTy);
2073 // This type is being defined, so clear the location to indicate this.
2074 Entry.second = SMLoc();
2076 // If this type number has never been uttered, create it.
2078 Entry.first = StructType::create(Context, Name);
2080 StructType *STy = cast<StructType>(Entry.first);
2082 SmallVector<Type*, 8> Body;
2083 if (ParseStructBody(Body) ||
2084 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2087 STy->setBody(Body, isPacked);
2093 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2096 /// ::= '{' Type (',' Type)* '}'
2097 /// ::= '<' '{' '}' '>'
2098 /// ::= '<' '{' Type (',' Type)* '}' '>'
2099 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2100 assert(Lex.getKind() == lltok::lbrace);
2101 Lex.Lex(); // Consume the '{'
2103 // Handle the empty struct.
2104 if (EatIfPresent(lltok::rbrace))
2107 LocTy EltTyLoc = Lex.getLoc();
2109 if (ParseType(Ty)) return true;
2112 if (!StructType::isValidElementType(Ty))
2113 return Error(EltTyLoc, "invalid element type for struct");
2115 while (EatIfPresent(lltok::comma)) {
2116 EltTyLoc = Lex.getLoc();
2117 if (ParseType(Ty)) return true;
2119 if (!StructType::isValidElementType(Ty))
2120 return Error(EltTyLoc, "invalid element type for struct");
2125 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2128 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2129 /// token has already been consumed.
2131 /// ::= '[' APSINTVAL 'x' Types ']'
2132 /// ::= '<' APSINTVAL 'x' Types '>'
2133 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2134 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2135 Lex.getAPSIntVal().getBitWidth() > 64)
2136 return TokError("expected number in address space");
2138 LocTy SizeLoc = Lex.getLoc();
2139 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2142 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2145 LocTy TypeLoc = Lex.getLoc();
2146 Type *EltTy = nullptr;
2147 if (ParseType(EltTy)) return true;
2149 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2150 "expected end of sequential type"))
2155 return Error(SizeLoc, "zero element vector is illegal");
2156 if ((unsigned)Size != Size)
2157 return Error(SizeLoc, "size too large for vector");
2158 if (!VectorType::isValidElementType(EltTy))
2159 return Error(TypeLoc, "invalid vector element type");
2160 Result = VectorType::get(EltTy, unsigned(Size));
2162 if (!ArrayType::isValidElementType(EltTy))
2163 return Error(TypeLoc, "invalid array element type");
2164 Result = ArrayType::get(EltTy, Size);
2169 //===----------------------------------------------------------------------===//
2170 // Function Semantic Analysis.
2171 //===----------------------------------------------------------------------===//
2173 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2175 : P(p), F(f), FunctionNumber(functionNumber) {
2177 // Insert unnamed arguments into the NumberedVals list.
2178 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2181 NumberedVals.push_back(AI);
2184 LLParser::PerFunctionState::~PerFunctionState() {
2185 // If there were any forward referenced non-basicblock values, delete them.
2186 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2187 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2188 if (!isa<BasicBlock>(I->second.first)) {
2189 I->second.first->replaceAllUsesWith(
2190 UndefValue::get(I->second.first->getType()));
2191 delete I->second.first;
2192 I->second.first = nullptr;
2195 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2196 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2197 if (!isa<BasicBlock>(I->second.first)) {
2198 I->second.first->replaceAllUsesWith(
2199 UndefValue::get(I->second.first->getType()));
2200 delete I->second.first;
2201 I->second.first = nullptr;
2205 bool LLParser::PerFunctionState::FinishFunction() {
2206 if (!ForwardRefVals.empty())
2207 return P.Error(ForwardRefVals.begin()->second.second,
2208 "use of undefined value '%" + ForwardRefVals.begin()->first +
2210 if (!ForwardRefValIDs.empty())
2211 return P.Error(ForwardRefValIDs.begin()->second.second,
2212 "use of undefined value '%" +
2213 Twine(ForwardRefValIDs.begin()->first) + "'");
2218 /// GetVal - Get a value with the specified name or ID, creating a
2219 /// forward reference record if needed. This can return null if the value
2220 /// exists but does not have the right type.
2221 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2222 Type *Ty, LocTy Loc) {
2223 // Look this name up in the normal function symbol table.
2224 Value *Val = F.getValueSymbolTable().lookup(Name);
2226 // If this is a forward reference for the value, see if we already created a
2227 // forward ref record.
2229 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2230 I = ForwardRefVals.find(Name);
2231 if (I != ForwardRefVals.end())
2232 Val = I->second.first;
2235 // If we have the value in the symbol table or fwd-ref table, return it.
2237 if (Val->getType() == Ty) return Val;
2238 if (Ty->isLabelTy())
2239 P.Error(Loc, "'%" + Name + "' is not a basic block");
2241 P.Error(Loc, "'%" + Name + "' defined with type '" +
2242 getTypeString(Val->getType()) + "'");
2246 // Don't make placeholders with invalid type.
2247 if (!Ty->isFirstClassType()) {
2248 P.Error(Loc, "invalid use of a non-first-class type");
2252 // Otherwise, create a new forward reference for this value and remember it.
2254 if (Ty->isLabelTy())
2255 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2257 FwdVal = new Argument(Ty, Name);
2259 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2263 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2265 // Look this name up in the normal function symbol table.
2266 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2268 // If this is a forward reference for the value, see if we already created a
2269 // forward ref record.
2271 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2272 I = ForwardRefValIDs.find(ID);
2273 if (I != ForwardRefValIDs.end())
2274 Val = I->second.first;
2277 // If we have the value in the symbol table or fwd-ref table, return it.
2279 if (Val->getType() == Ty) return Val;
2280 if (Ty->isLabelTy())
2281 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2283 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2284 getTypeString(Val->getType()) + "'");
2288 if (!Ty->isFirstClassType()) {
2289 P.Error(Loc, "invalid use of a non-first-class type");
2293 // Otherwise, create a new forward reference for this value and remember it.
2295 if (Ty->isLabelTy())
2296 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2298 FwdVal = new Argument(Ty);
2300 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2304 /// SetInstName - After an instruction is parsed and inserted into its
2305 /// basic block, this installs its name.
2306 bool LLParser::PerFunctionState::SetInstName(int NameID,
2307 const std::string &NameStr,
2308 LocTy NameLoc, Instruction *Inst) {
2309 // If this instruction has void type, it cannot have a name or ID specified.
2310 if (Inst->getType()->isVoidTy()) {
2311 if (NameID != -1 || !NameStr.empty())
2312 return P.Error(NameLoc, "instructions returning void cannot have a name");
2316 // If this was a numbered instruction, verify that the instruction is the
2317 // expected value and resolve any forward references.
2318 if (NameStr.empty()) {
2319 // If neither a name nor an ID was specified, just use the next ID.
2321 NameID = NumberedVals.size();
2323 if (unsigned(NameID) != NumberedVals.size())
2324 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2325 Twine(NumberedVals.size()) + "'");
2327 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2328 ForwardRefValIDs.find(NameID);
2329 if (FI != ForwardRefValIDs.end()) {
2330 if (FI->second.first->getType() != Inst->getType())
2331 return P.Error(NameLoc, "instruction forward referenced with type '" +
2332 getTypeString(FI->second.first->getType()) + "'");
2333 FI->second.first->replaceAllUsesWith(Inst);
2334 delete FI->second.first;
2335 ForwardRefValIDs.erase(FI);
2338 NumberedVals.push_back(Inst);
2342 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2343 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2344 FI = ForwardRefVals.find(NameStr);
2345 if (FI != ForwardRefVals.end()) {
2346 if (FI->second.first->getType() != Inst->getType())
2347 return P.Error(NameLoc, "instruction forward referenced with type '" +
2348 getTypeString(FI->second.first->getType()) + "'");
2349 FI->second.first->replaceAllUsesWith(Inst);
2350 delete FI->second.first;
2351 ForwardRefVals.erase(FI);
2354 // Set the name on the instruction.
2355 Inst->setName(NameStr);
2357 if (Inst->getName() != NameStr)
2358 return P.Error(NameLoc, "multiple definition of local value named '" +
2363 /// GetBB - Get a basic block with the specified name or ID, creating a
2364 /// forward reference record if needed.
2365 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2367 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2368 Type::getLabelTy(F.getContext()), Loc));
2371 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2372 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2373 Type::getLabelTy(F.getContext()), Loc));
2376 /// DefineBB - Define the specified basic block, which is either named or
2377 /// unnamed. If there is an error, this returns null otherwise it returns
2378 /// the block being defined.
2379 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2383 BB = GetBB(NumberedVals.size(), Loc);
2385 BB = GetBB(Name, Loc);
2386 if (!BB) return nullptr; // Already diagnosed error.
2388 // Move the block to the end of the function. Forward ref'd blocks are
2389 // inserted wherever they happen to be referenced.
2390 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2392 // Remove the block from forward ref sets.
2394 ForwardRefValIDs.erase(NumberedVals.size());
2395 NumberedVals.push_back(BB);
2397 // BB forward references are already in the function symbol table.
2398 ForwardRefVals.erase(Name);
2404 //===----------------------------------------------------------------------===//
2406 //===----------------------------------------------------------------------===//
2408 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2409 /// type implied. For example, if we parse "4" we don't know what integer type
2410 /// it has. The value will later be combined with its type and checked for
2411 /// sanity. PFS is used to convert function-local operands of metadata (since
2412 /// metadata operands are not just parsed here but also converted to values).
2413 /// PFS can be null when we are not parsing metadata values inside a function.
2414 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2415 ID.Loc = Lex.getLoc();
2416 switch (Lex.getKind()) {
2417 default: return TokError("expected value token");
2418 case lltok::GlobalID: // @42
2419 ID.UIntVal = Lex.getUIntVal();
2420 ID.Kind = ValID::t_GlobalID;
2422 case lltok::GlobalVar: // @foo
2423 ID.StrVal = Lex.getStrVal();
2424 ID.Kind = ValID::t_GlobalName;
2426 case lltok::LocalVarID: // %42
2427 ID.UIntVal = Lex.getUIntVal();
2428 ID.Kind = ValID::t_LocalID;
2430 case lltok::LocalVar: // %foo
2431 ID.StrVal = Lex.getStrVal();
2432 ID.Kind = ValID::t_LocalName;
2435 ID.APSIntVal = Lex.getAPSIntVal();
2436 ID.Kind = ValID::t_APSInt;
2438 case lltok::APFloat:
2439 ID.APFloatVal = Lex.getAPFloatVal();
2440 ID.Kind = ValID::t_APFloat;
2442 case lltok::kw_true:
2443 ID.ConstantVal = ConstantInt::getTrue(Context);
2444 ID.Kind = ValID::t_Constant;
2446 case lltok::kw_false:
2447 ID.ConstantVal = ConstantInt::getFalse(Context);
2448 ID.Kind = ValID::t_Constant;
2450 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2451 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2452 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2454 case lltok::lbrace: {
2455 // ValID ::= '{' ConstVector '}'
2457 SmallVector<Constant*, 16> Elts;
2458 if (ParseGlobalValueVector(Elts) ||
2459 ParseToken(lltok::rbrace, "expected end of struct constant"))
2462 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2463 ID.UIntVal = Elts.size();
2464 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2465 Elts.size() * sizeof(Elts[0]));
2466 ID.Kind = ValID::t_ConstantStruct;
2470 // ValID ::= '<' ConstVector '>' --> Vector.
2471 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2473 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2475 SmallVector<Constant*, 16> Elts;
2476 LocTy FirstEltLoc = Lex.getLoc();
2477 if (ParseGlobalValueVector(Elts) ||
2479 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2480 ParseToken(lltok::greater, "expected end of constant"))
2483 if (isPackedStruct) {
2484 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2485 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2486 Elts.size() * sizeof(Elts[0]));
2487 ID.UIntVal = Elts.size();
2488 ID.Kind = ValID::t_PackedConstantStruct;
2493 return Error(ID.Loc, "constant vector must not be empty");
2495 if (!Elts[0]->getType()->isIntegerTy() &&
2496 !Elts[0]->getType()->isFloatingPointTy() &&
2497 !Elts[0]->getType()->isPointerTy())
2498 return Error(FirstEltLoc,
2499 "vector elements must have integer, pointer or floating point type");
2501 // Verify that all the vector elements have the same type.
2502 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2503 if (Elts[i]->getType() != Elts[0]->getType())
2504 return Error(FirstEltLoc,
2505 "vector element #" + Twine(i) +
2506 " is not of type '" + getTypeString(Elts[0]->getType()));
2508 ID.ConstantVal = ConstantVector::get(Elts);
2509 ID.Kind = ValID::t_Constant;
2512 case lltok::lsquare: { // Array Constant
2514 SmallVector<Constant*, 16> Elts;
2515 LocTy FirstEltLoc = Lex.getLoc();
2516 if (ParseGlobalValueVector(Elts) ||
2517 ParseToken(lltok::rsquare, "expected end of array constant"))
2520 // Handle empty element.
2522 // Use undef instead of an array because it's inconvenient to determine
2523 // the element type at this point, there being no elements to examine.
2524 ID.Kind = ValID::t_EmptyArray;
2528 if (!Elts[0]->getType()->isFirstClassType())
2529 return Error(FirstEltLoc, "invalid array element type: " +
2530 getTypeString(Elts[0]->getType()));
2532 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2534 // Verify all elements are correct type!
2535 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2536 if (Elts[i]->getType() != Elts[0]->getType())
2537 return Error(FirstEltLoc,
2538 "array element #" + Twine(i) +
2539 " is not of type '" + getTypeString(Elts[0]->getType()));
2542 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2543 ID.Kind = ValID::t_Constant;
2546 case lltok::kw_c: // c "foo"
2548 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2550 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2551 ID.Kind = ValID::t_Constant;
2554 case lltok::kw_asm: {
2555 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2557 bool HasSideEffect, AlignStack, AsmDialect;
2559 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2560 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2561 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2562 ParseStringConstant(ID.StrVal) ||
2563 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2564 ParseToken(lltok::StringConstant, "expected constraint string"))
2566 ID.StrVal2 = Lex.getStrVal();
2567 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2568 (unsigned(AsmDialect)<<2);
2569 ID.Kind = ValID::t_InlineAsm;
2573 case lltok::kw_blockaddress: {
2574 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2579 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2581 ParseToken(lltok::comma, "expected comma in block address expression")||
2582 ParseValID(Label) ||
2583 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2586 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2587 return Error(Fn.Loc, "expected function name in blockaddress");
2588 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2589 return Error(Label.Loc, "expected basic block name in blockaddress");
2591 // Try to find the function (but skip it if it's forward-referenced).
2592 GlobalValue *GV = nullptr;
2593 if (Fn.Kind == ValID::t_GlobalID) {
2594 if (Fn.UIntVal < NumberedVals.size())
2595 GV = NumberedVals[Fn.UIntVal];
2596 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2597 GV = M->getNamedValue(Fn.StrVal);
2599 Function *F = nullptr;
2601 // Confirm that it's actually a function with a definition.
2602 if (!isa<Function>(GV))
2603 return Error(Fn.Loc, "expected function name in blockaddress");
2604 F = cast<Function>(GV);
2605 if (F->isDeclaration())
2606 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2610 // Make a global variable as a placeholder for this reference.
2611 GlobalValue *&FwdRef =
2612 ForwardRefBlockAddresses.insert(std::make_pair(
2614 std::map<ValID, GlobalValue *>()))
2615 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2618 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2619 GlobalValue::InternalLinkage, nullptr, "");
2620 ID.ConstantVal = FwdRef;
2621 ID.Kind = ValID::t_Constant;
2625 // We found the function; now find the basic block. Don't use PFS, since we
2626 // might be inside a constant expression.
2628 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2629 if (Label.Kind == ValID::t_LocalID)
2630 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2632 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2634 return Error(Label.Loc, "referenced value is not a basic block");
2636 if (Label.Kind == ValID::t_LocalID)
2637 return Error(Label.Loc, "cannot take address of numeric label after "
2638 "the function is defined");
2639 BB = dyn_cast_or_null<BasicBlock>(
2640 F->getValueSymbolTable().lookup(Label.StrVal));
2642 return Error(Label.Loc, "referenced value is not a basic block");
2645 ID.ConstantVal = BlockAddress::get(F, BB);
2646 ID.Kind = ValID::t_Constant;
2650 case lltok::kw_trunc:
2651 case lltok::kw_zext:
2652 case lltok::kw_sext:
2653 case lltok::kw_fptrunc:
2654 case lltok::kw_fpext:
2655 case lltok::kw_bitcast:
2656 case lltok::kw_addrspacecast:
2657 case lltok::kw_uitofp:
2658 case lltok::kw_sitofp:
2659 case lltok::kw_fptoui:
2660 case lltok::kw_fptosi:
2661 case lltok::kw_inttoptr:
2662 case lltok::kw_ptrtoint: {
2663 unsigned Opc = Lex.getUIntVal();
2664 Type *DestTy = nullptr;
2667 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2668 ParseGlobalTypeAndValue(SrcVal) ||
2669 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2670 ParseType(DestTy) ||
2671 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2673 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2674 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2675 getTypeString(SrcVal->getType()) + "' to '" +
2676 getTypeString(DestTy) + "'");
2677 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2679 ID.Kind = ValID::t_Constant;
2682 case lltok::kw_extractvalue: {
2685 SmallVector<unsigned, 4> Indices;
2686 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2687 ParseGlobalTypeAndValue(Val) ||
2688 ParseIndexList(Indices) ||
2689 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2692 if (!Val->getType()->isAggregateType())
2693 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2694 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2695 return Error(ID.Loc, "invalid indices for extractvalue");
2696 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2697 ID.Kind = ValID::t_Constant;
2700 case lltok::kw_insertvalue: {
2702 Constant *Val0, *Val1;
2703 SmallVector<unsigned, 4> Indices;
2704 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2705 ParseGlobalTypeAndValue(Val0) ||
2706 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2707 ParseGlobalTypeAndValue(Val1) ||
2708 ParseIndexList(Indices) ||
2709 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2711 if (!Val0->getType()->isAggregateType())
2712 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2714 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2716 return Error(ID.Loc, "invalid indices for insertvalue");
2717 if (IndexedType != Val1->getType())
2718 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2719 getTypeString(Val1->getType()) +
2720 "' instead of '" + getTypeString(IndexedType) +
2722 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2723 ID.Kind = ValID::t_Constant;
2726 case lltok::kw_icmp:
2727 case lltok::kw_fcmp: {
2728 unsigned PredVal, Opc = Lex.getUIntVal();
2729 Constant *Val0, *Val1;
2731 if (ParseCmpPredicate(PredVal, Opc) ||
2732 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2733 ParseGlobalTypeAndValue(Val0) ||
2734 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2735 ParseGlobalTypeAndValue(Val1) ||
2736 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2739 if (Val0->getType() != Val1->getType())
2740 return Error(ID.Loc, "compare operands must have the same type");
2742 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2744 if (Opc == Instruction::FCmp) {
2745 if (!Val0->getType()->isFPOrFPVectorTy())
2746 return Error(ID.Loc, "fcmp requires floating point operands");
2747 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2749 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2750 if (!Val0->getType()->isIntOrIntVectorTy() &&
2751 !Val0->getType()->getScalarType()->isPointerTy())
2752 return Error(ID.Loc, "icmp requires pointer or integer operands");
2753 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2755 ID.Kind = ValID::t_Constant;
2759 // Binary Operators.
2761 case lltok::kw_fadd:
2763 case lltok::kw_fsub:
2765 case lltok::kw_fmul:
2766 case lltok::kw_udiv:
2767 case lltok::kw_sdiv:
2768 case lltok::kw_fdiv:
2769 case lltok::kw_urem:
2770 case lltok::kw_srem:
2771 case lltok::kw_frem:
2773 case lltok::kw_lshr:
2774 case lltok::kw_ashr: {
2778 unsigned Opc = Lex.getUIntVal();
2779 Constant *Val0, *Val1;
2781 LocTy ModifierLoc = Lex.getLoc();
2782 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2783 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2784 if (EatIfPresent(lltok::kw_nuw))
2786 if (EatIfPresent(lltok::kw_nsw)) {
2788 if (EatIfPresent(lltok::kw_nuw))
2791 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2792 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2793 if (EatIfPresent(lltok::kw_exact))
2796 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2797 ParseGlobalTypeAndValue(Val0) ||
2798 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2799 ParseGlobalTypeAndValue(Val1) ||
2800 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2802 if (Val0->getType() != Val1->getType())
2803 return Error(ID.Loc, "operands of constexpr must have same type");
2804 if (!Val0->getType()->isIntOrIntVectorTy()) {
2806 return Error(ModifierLoc, "nuw only applies to integer operations");
2808 return Error(ModifierLoc, "nsw only applies to integer operations");
2810 // Check that the type is valid for the operator.
2812 case Instruction::Add:
2813 case Instruction::Sub:
2814 case Instruction::Mul:
2815 case Instruction::UDiv:
2816 case Instruction::SDiv:
2817 case Instruction::URem:
2818 case Instruction::SRem:
2819 case Instruction::Shl:
2820 case Instruction::AShr:
2821 case Instruction::LShr:
2822 if (!Val0->getType()->isIntOrIntVectorTy())
2823 return Error(ID.Loc, "constexpr requires integer operands");
2825 case Instruction::FAdd:
2826 case Instruction::FSub:
2827 case Instruction::FMul:
2828 case Instruction::FDiv:
2829 case Instruction::FRem:
2830 if (!Val0->getType()->isFPOrFPVectorTy())
2831 return Error(ID.Loc, "constexpr requires fp operands");
2833 default: llvm_unreachable("Unknown binary operator!");
2836 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2837 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2838 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2839 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2841 ID.Kind = ValID::t_Constant;
2845 // Logical Operations
2848 case lltok::kw_xor: {
2849 unsigned Opc = Lex.getUIntVal();
2850 Constant *Val0, *Val1;
2852 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2853 ParseGlobalTypeAndValue(Val0) ||
2854 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2855 ParseGlobalTypeAndValue(Val1) ||
2856 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2858 if (Val0->getType() != Val1->getType())
2859 return Error(ID.Loc, "operands of constexpr must have same type");
2860 if (!Val0->getType()->isIntOrIntVectorTy())
2861 return Error(ID.Loc,
2862 "constexpr requires integer or integer vector operands");
2863 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2864 ID.Kind = ValID::t_Constant;
2868 case lltok::kw_getelementptr:
2869 case lltok::kw_shufflevector:
2870 case lltok::kw_insertelement:
2871 case lltok::kw_extractelement:
2872 case lltok::kw_select: {
2873 unsigned Opc = Lex.getUIntVal();
2874 SmallVector<Constant*, 16> Elts;
2875 bool InBounds = false;
2879 if (Opc == Instruction::GetElementPtr)
2880 InBounds = EatIfPresent(lltok::kw_inbounds);
2882 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2885 LocTy ExplicitTypeLoc = Lex.getLoc();
2886 if (Opc == Instruction::GetElementPtr) {
2887 if (ParseType(Ty) ||
2888 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2892 if (ParseGlobalValueVector(Elts) ||
2893 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2896 if (Opc == Instruction::GetElementPtr) {
2897 if (Elts.size() == 0 ||
2898 !Elts[0]->getType()->getScalarType()->isPointerTy())
2899 return Error(ID.Loc, "base of getelementptr must be a pointer");
2901 Type *BaseType = Elts[0]->getType();
2902 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2903 if (Ty != BasePointerType->getElementType())
2906 "explicit pointee type doesn't match operand's pointee type");
2908 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2909 for (Constant *Val : Indices) {
2910 Type *ValTy = Val->getType();
2911 if (!ValTy->getScalarType()->isIntegerTy())
2912 return Error(ID.Loc, "getelementptr index must be an integer");
2913 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2914 return Error(ID.Loc, "getelementptr index type missmatch");
2915 if (ValTy->isVectorTy()) {
2916 unsigned ValNumEl = ValTy->getVectorNumElements();
2917 unsigned PtrNumEl = BaseType->getVectorNumElements();
2918 if (ValNumEl != PtrNumEl)
2921 "getelementptr vector index has a wrong number of elements");
2925 SmallPtrSet<Type*, 4> Visited;
2926 if (!Indices.empty() && !Ty->isSized(&Visited))
2927 return Error(ID.Loc, "base element of getelementptr must be sized");
2929 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2930 return Error(ID.Loc, "invalid getelementptr indices");
2932 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2933 } else if (Opc == Instruction::Select) {
2934 if (Elts.size() != 3)
2935 return Error(ID.Loc, "expected three operands to select");
2936 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2938 return Error(ID.Loc, Reason);
2939 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2940 } else if (Opc == Instruction::ShuffleVector) {
2941 if (Elts.size() != 3)
2942 return Error(ID.Loc, "expected three operands to shufflevector");
2943 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2944 return Error(ID.Loc, "invalid operands to shufflevector");
2946 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2947 } else if (Opc == Instruction::ExtractElement) {
2948 if (Elts.size() != 2)
2949 return Error(ID.Loc, "expected two operands to extractelement");
2950 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2951 return Error(ID.Loc, "invalid extractelement operands");
2952 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2954 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2955 if (Elts.size() != 3)
2956 return Error(ID.Loc, "expected three operands to insertelement");
2957 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2958 return Error(ID.Loc, "invalid insertelement operands");
2960 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2963 ID.Kind = ValID::t_Constant;
2972 /// ParseGlobalValue - Parse a global value with the specified type.
2973 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2977 bool Parsed = ParseValID(ID) ||
2978 ConvertValIDToValue(Ty, ID, V, nullptr);
2979 if (V && !(C = dyn_cast<Constant>(V)))
2980 return Error(ID.Loc, "global values must be constants");
2984 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2986 return ParseType(Ty) ||
2987 ParseGlobalValue(Ty, V);
2990 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2993 LocTy KwLoc = Lex.getLoc();
2994 if (!EatIfPresent(lltok::kw_comdat))
2997 if (EatIfPresent(lltok::lparen)) {
2998 if (Lex.getKind() != lltok::ComdatVar)
2999 return TokError("expected comdat variable");
3000 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3002 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3005 if (GlobalName.empty())
3006 return TokError("comdat cannot be unnamed");
3007 C = getComdat(GlobalName, KwLoc);
3013 /// ParseGlobalValueVector
3015 /// ::= TypeAndValue (',' TypeAndValue)*
3016 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3018 if (Lex.getKind() == lltok::rbrace ||
3019 Lex.getKind() == lltok::rsquare ||
3020 Lex.getKind() == lltok::greater ||
3021 Lex.getKind() == lltok::rparen)
3025 if (ParseGlobalTypeAndValue(C)) return true;
3028 while (EatIfPresent(lltok::comma)) {
3029 if (ParseGlobalTypeAndValue(C)) return true;
3036 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3037 SmallVector<Metadata *, 16> Elts;
3038 if (ParseMDNodeVector(Elts))
3041 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3048 /// ::= !DILocation(...)
3049 bool LLParser::ParseMDNode(MDNode *&N) {
3050 if (Lex.getKind() == lltok::MetadataVar)
3051 return ParseSpecializedMDNode(N);
3053 return ParseToken(lltok::exclaim, "expected '!' here") ||
3057 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3059 if (Lex.getKind() == lltok::lbrace)
3060 return ParseMDTuple(N);
3063 return ParseMDNodeID(N);
3068 /// Structure to represent an optional metadata field.
3069 template <class FieldTy> struct MDFieldImpl {
3070 typedef MDFieldImpl ImplTy;
3074 void assign(FieldTy Val) {
3076 this->Val = std::move(Val);
3079 explicit MDFieldImpl(FieldTy Default)
3080 : Val(std::move(Default)), Seen(false) {}
3083 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3086 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3087 : ImplTy(Default), Max(Max) {}
3089 struct LineField : public MDUnsignedField {
3090 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3092 struct ColumnField : public MDUnsignedField {
3093 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3095 struct DwarfTagField : public MDUnsignedField {
3096 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3097 DwarfTagField(dwarf::Tag DefaultTag)
3098 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3100 struct DwarfAttEncodingField : public MDUnsignedField {
3101 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3103 struct DwarfVirtualityField : public MDUnsignedField {
3104 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3106 struct DwarfLangField : public MDUnsignedField {
3107 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3110 struct DIFlagField : public MDUnsignedField {
3111 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3114 struct MDSignedField : public MDFieldImpl<int64_t> {
3118 MDSignedField(int64_t Default = 0)
3119 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3120 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3121 : ImplTy(Default), Min(Min), Max(Max) {}
3124 struct MDBoolField : public MDFieldImpl<bool> {
3125 MDBoolField(bool Default = false) : ImplTy(Default) {}
3127 struct MDField : public MDFieldImpl<Metadata *> {
3130 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3132 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3133 MDConstant() : ImplTy(nullptr) {}
3135 struct MDStringField : public MDFieldImpl<MDString *> {
3137 MDStringField(bool AllowEmpty = true)
3138 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3140 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3141 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3149 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3150 MDUnsignedField &Result) {
3151 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3152 return TokError("expected unsigned integer");
3154 auto &U = Lex.getAPSIntVal();
3155 if (U.ugt(Result.Max))
3156 return TokError("value for '" + Name + "' too large, limit is " +
3158 Result.assign(U.getZExtValue());
3159 assert(Result.Val <= Result.Max && "Expected value in range");
3165 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3166 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3169 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3170 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3174 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3175 if (Lex.getKind() == lltok::APSInt)
3176 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3178 if (Lex.getKind() != lltok::DwarfTag)
3179 return TokError("expected DWARF tag");
3181 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3182 if (Tag == dwarf::DW_TAG_invalid)
3183 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3184 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3192 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3193 DwarfVirtualityField &Result) {
3194 if (Lex.getKind() == lltok::APSInt)
3195 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3197 if (Lex.getKind() != lltok::DwarfVirtuality)
3198 return TokError("expected DWARF virtuality code");
3200 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3202 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3203 Lex.getStrVal() + "'");
3204 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3205 Result.assign(Virtuality);
3211 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3212 if (Lex.getKind() == lltok::APSInt)
3213 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3215 if (Lex.getKind() != lltok::DwarfLang)
3216 return TokError("expected DWARF language");
3218 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3220 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3222 assert(Lang <= Result.Max && "Expected valid DWARF language");
3223 Result.assign(Lang);
3229 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3230 DwarfAttEncodingField &Result) {
3231 if (Lex.getKind() == lltok::APSInt)
3232 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3234 if (Lex.getKind() != lltok::DwarfAttEncoding)
3235 return TokError("expected DWARF type attribute encoding");
3237 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3239 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3240 Lex.getStrVal() + "'");
3241 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3242 Result.assign(Encoding);
3249 /// ::= DIFlagVector
3250 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3252 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3253 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3255 // Parser for a single flag.
3256 auto parseFlag = [&](unsigned &Val) {
3257 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3258 return ParseUInt32(Val);
3260 if (Lex.getKind() != lltok::DIFlag)
3261 return TokError("expected debug info flag");
3263 Val = DINode::getFlag(Lex.getStrVal());
3265 return TokError(Twine("invalid debug info flag flag '") +
3266 Lex.getStrVal() + "'");
3271 // Parse the flags and combine them together.
3272 unsigned Combined = 0;
3278 } while (EatIfPresent(lltok::bar));
3280 Result.assign(Combined);
3285 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3286 MDSignedField &Result) {
3287 if (Lex.getKind() != lltok::APSInt)
3288 return TokError("expected signed integer");
3290 auto &S = Lex.getAPSIntVal();
3292 return TokError("value for '" + Name + "' too small, limit is " +
3295 return TokError("value for '" + Name + "' too large, limit is " +
3297 Result.assign(S.getExtValue());
3298 assert(Result.Val >= Result.Min && "Expected value in range");
3299 assert(Result.Val <= Result.Max && "Expected value in range");
3305 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3306 switch (Lex.getKind()) {
3308 return TokError("expected 'true' or 'false'");
3309 case lltok::kw_true:
3310 Result.assign(true);
3312 case lltok::kw_false:
3313 Result.assign(false);
3321 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3322 if (Lex.getKind() == lltok::kw_null) {
3323 if (!Result.AllowNull)
3324 return TokError("'" + Name + "' cannot be null");
3326 Result.assign(nullptr);
3331 if (ParseMetadata(MD, nullptr))
3339 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3341 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3344 Result.assign(cast<ConstantAsMetadata>(MD));
3349 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3350 LocTy ValueLoc = Lex.getLoc();
3352 if (ParseStringConstant(S))
3355 if (!Result.AllowEmpty && S.empty())
3356 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3358 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3363 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3364 SmallVector<Metadata *, 4> MDs;
3365 if (ParseMDNodeVector(MDs))
3368 Result.assign(std::move(MDs));
3372 } // end namespace llvm
3374 template <class ParserTy>
3375 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3377 if (Lex.getKind() != lltok::LabelStr)
3378 return TokError("expected field label here");
3382 } while (EatIfPresent(lltok::comma));
3387 template <class ParserTy>
3388 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3389 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3392 if (ParseToken(lltok::lparen, "expected '(' here"))
3394 if (Lex.getKind() != lltok::rparen)
3395 if (ParseMDFieldsImplBody(parseField))
3398 ClosingLoc = Lex.getLoc();
3399 return ParseToken(lltok::rparen, "expected ')' here");
3402 template <class FieldTy>
3403 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3405 return TokError("field '" + Name + "' cannot be specified more than once");
3407 LocTy Loc = Lex.getLoc();
3409 return ParseMDField(Loc, Name, Result);
3412 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3413 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3415 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3416 if (Lex.getStrVal() == #CLASS) \
3417 return Parse##CLASS(N, IsDistinct);
3418 #include "llvm/IR/Metadata.def"
3420 return TokError("expected metadata type");
3423 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3424 #define NOP_FIELD(NAME, TYPE, INIT)
3425 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3427 return Error(ClosingLoc, "missing required field '" #NAME "'");
3428 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3429 if (Lex.getStrVal() == #NAME) \
3430 return ParseMDField(#NAME, NAME);
3431 #define PARSE_MD_FIELDS() \
3432 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3435 if (ParseMDFieldsImpl([&]() -> bool { \
3436 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3437 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3440 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3442 #define GET_OR_DISTINCT(CLASS, ARGS) \
3443 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3445 /// ParseDILocationFields:
3446 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3447 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3448 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3449 OPTIONAL(line, LineField, ); \
3450 OPTIONAL(column, ColumnField, ); \
3451 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3452 OPTIONAL(inlinedAt, MDField, );
3454 #undef VISIT_MD_FIELDS
3456 Result = GET_OR_DISTINCT(
3457 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3461 /// ParseGenericDINode:
3462 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3463 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3464 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3465 REQUIRED(tag, DwarfTagField, ); \
3466 OPTIONAL(header, MDStringField, ); \
3467 OPTIONAL(operands, MDFieldList, );
3469 #undef VISIT_MD_FIELDS
3471 Result = GET_OR_DISTINCT(GenericDINode,
3472 (Context, tag.Val, header.Val, operands.Val));
3476 /// ParseDISubrange:
3477 /// ::= !DISubrange(count: 30, lowerBound: 2)
3478 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3479 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3480 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3481 OPTIONAL(lowerBound, MDSignedField, );
3483 #undef VISIT_MD_FIELDS
3485 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3489 /// ParseDIEnumerator:
3490 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3491 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3492 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3493 REQUIRED(name, MDStringField, ); \
3494 REQUIRED(value, MDSignedField, );
3496 #undef VISIT_MD_FIELDS
3498 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3502 /// ParseDIBasicType:
3503 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3504 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3505 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3506 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3507 OPTIONAL(name, MDStringField, ); \
3508 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3509 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3510 OPTIONAL(encoding, DwarfAttEncodingField, );
3512 #undef VISIT_MD_FIELDS
3514 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3515 align.Val, encoding.Val));
3519 /// ParseDIDerivedType:
3520 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3521 /// line: 7, scope: !1, baseType: !2, size: 32,
3522 /// align: 32, offset: 0, flags: 0, extraData: !3)
3523 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3524 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3525 REQUIRED(tag, DwarfTagField, ); \
3526 OPTIONAL(name, MDStringField, ); \
3527 OPTIONAL(file, MDField, ); \
3528 OPTIONAL(line, LineField, ); \
3529 OPTIONAL(scope, MDField, ); \
3530 REQUIRED(baseType, MDField, ); \
3531 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3532 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3533 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3534 OPTIONAL(flags, DIFlagField, ); \
3535 OPTIONAL(extraData, MDField, );
3537 #undef VISIT_MD_FIELDS
3539 Result = GET_OR_DISTINCT(DIDerivedType,
3540 (Context, tag.Val, name.Val, file.Val, line.Val,
3541 scope.Val, baseType.Val, size.Val, align.Val,
3542 offset.Val, flags.Val, extraData.Val));
3546 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3547 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3548 REQUIRED(tag, DwarfTagField, ); \
3549 OPTIONAL(name, MDStringField, ); \
3550 OPTIONAL(file, MDField, ); \
3551 OPTIONAL(line, LineField, ); \
3552 OPTIONAL(scope, MDField, ); \
3553 OPTIONAL(baseType, MDField, ); \
3554 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3555 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3556 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3557 OPTIONAL(flags, DIFlagField, ); \
3558 OPTIONAL(elements, MDField, ); \
3559 OPTIONAL(runtimeLang, DwarfLangField, ); \
3560 OPTIONAL(vtableHolder, MDField, ); \
3561 OPTIONAL(templateParams, MDField, ); \
3562 OPTIONAL(identifier, MDStringField, );
3564 #undef VISIT_MD_FIELDS
3566 Result = GET_OR_DISTINCT(
3568 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3569 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3570 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3574 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3575 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3576 OPTIONAL(flags, DIFlagField, ); \
3577 REQUIRED(types, MDField, );
3579 #undef VISIT_MD_FIELDS
3581 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3585 /// ParseDIFileType:
3586 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3587 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3588 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3589 REQUIRED(filename, MDStringField, ); \
3590 REQUIRED(directory, MDStringField, );
3592 #undef VISIT_MD_FIELDS
3594 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3598 /// ParseDICompileUnit:
3599 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3600 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3601 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3602 /// enums: !1, retainedTypes: !2, subprograms: !3,
3603 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3604 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3605 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3606 REQUIRED(language, DwarfLangField, ); \
3607 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3608 OPTIONAL(producer, MDStringField, ); \
3609 OPTIONAL(isOptimized, MDBoolField, ); \
3610 OPTIONAL(flags, MDStringField, ); \
3611 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3612 OPTIONAL(splitDebugFilename, MDStringField, ); \
3613 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3614 OPTIONAL(enums, MDField, ); \
3615 OPTIONAL(retainedTypes, MDField, ); \
3616 OPTIONAL(subprograms, MDField, ); \
3617 OPTIONAL(globals, MDField, ); \
3618 OPTIONAL(imports, MDField, ); \
3619 OPTIONAL(dwoId, MDUnsignedField, );
3621 #undef VISIT_MD_FIELDS
3623 Result = GET_OR_DISTINCT(DICompileUnit,
3624 (Context, language.Val, file.Val, producer.Val,
3625 isOptimized.Val, flags.Val, runtimeVersion.Val,
3626 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3627 retainedTypes.Val, subprograms.Val, globals.Val,
3628 imports.Val, dwoId.Val));
3632 /// ParseDISubprogram:
3633 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3634 /// file: !1, line: 7, type: !2, isLocal: false,
3635 /// isDefinition: true, scopeLine: 8, containingType: !3,
3636 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3637 /// virtualIndex: 10, flags: 11,
3638 /// isOptimized: false, function: void ()* @_Z3foov,
3639 /// templateParams: !4, declaration: !5, variables: !6)
3640 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3641 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3642 OPTIONAL(scope, MDField, ); \
3643 OPTIONAL(name, MDStringField, ); \
3644 OPTIONAL(linkageName, MDStringField, ); \
3645 OPTIONAL(file, MDField, ); \
3646 OPTIONAL(line, LineField, ); \
3647 OPTIONAL(type, MDField, ); \
3648 OPTIONAL(isLocal, MDBoolField, ); \
3649 OPTIONAL(isDefinition, MDBoolField, (true)); \
3650 OPTIONAL(scopeLine, LineField, ); \
3651 OPTIONAL(containingType, MDField, ); \
3652 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3653 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3654 OPTIONAL(flags, DIFlagField, ); \
3655 OPTIONAL(isOptimized, MDBoolField, ); \
3656 OPTIONAL(function, MDConstant, ); \
3657 OPTIONAL(templateParams, MDField, ); \
3658 OPTIONAL(declaration, MDField, ); \
3659 OPTIONAL(variables, MDField, );
3661 #undef VISIT_MD_FIELDS
3663 Result = GET_OR_DISTINCT(
3664 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3665 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3666 scopeLine.Val, containingType.Val, virtuality.Val,
3667 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3668 templateParams.Val, declaration.Val, variables.Val));
3672 /// ParseDILexicalBlock:
3673 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3674 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3675 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3676 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3677 OPTIONAL(file, MDField, ); \
3678 OPTIONAL(line, LineField, ); \
3679 OPTIONAL(column, ColumnField, );
3681 #undef VISIT_MD_FIELDS
3683 Result = GET_OR_DISTINCT(
3684 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3688 /// ParseDILexicalBlockFile:
3689 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3690 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3691 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3692 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3693 OPTIONAL(file, MDField, ); \
3694 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3696 #undef VISIT_MD_FIELDS
3698 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3699 (Context, scope.Val, file.Val, discriminator.Val));
3703 /// ParseDINamespace:
3704 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3705 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3706 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3707 REQUIRED(scope, MDField, ); \
3708 OPTIONAL(file, MDField, ); \
3709 OPTIONAL(name, MDStringField, ); \
3710 OPTIONAL(line, LineField, );
3712 #undef VISIT_MD_FIELDS
3714 Result = GET_OR_DISTINCT(DINamespace,
3715 (Context, scope.Val, file.Val, name.Val, line.Val));
3720 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3721 /// includePath: "/usr/include", isysroot: "/")
3722 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3723 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3724 REQUIRED(scope, MDField, ); \
3725 REQUIRED(name, MDStringField, ); \
3726 OPTIONAL(configMacros, MDStringField, ); \
3727 OPTIONAL(includePath, MDStringField, ); \
3728 OPTIONAL(isysroot, MDStringField, );
3730 #undef VISIT_MD_FIELDS
3732 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3733 configMacros.Val, includePath.Val, isysroot.Val));
3737 /// ParseDITemplateTypeParameter:
3738 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3739 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3740 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3741 OPTIONAL(name, MDStringField, ); \
3742 REQUIRED(type, MDField, );
3744 #undef VISIT_MD_FIELDS
3747 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3751 /// ParseDITemplateValueParameter:
3752 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3753 /// name: "V", type: !1, value: i32 7)
3754 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3755 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3756 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3757 OPTIONAL(name, MDStringField, ); \
3758 OPTIONAL(type, MDField, ); \
3759 REQUIRED(value, MDField, );
3761 #undef VISIT_MD_FIELDS
3763 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3764 (Context, tag.Val, name.Val, type.Val, value.Val));
3768 /// ParseDIGlobalVariable:
3769 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3770 /// file: !1, line: 7, type: !2, isLocal: false,
3771 /// isDefinition: true, variable: i32* @foo,
3772 /// declaration: !3)
3773 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3774 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3775 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3776 OPTIONAL(scope, MDField, ); \
3777 OPTIONAL(linkageName, MDStringField, ); \
3778 OPTIONAL(file, MDField, ); \
3779 OPTIONAL(line, LineField, ); \
3780 OPTIONAL(type, MDField, ); \
3781 OPTIONAL(isLocal, MDBoolField, ); \
3782 OPTIONAL(isDefinition, MDBoolField, (true)); \
3783 OPTIONAL(variable, MDConstant, ); \
3784 OPTIONAL(declaration, MDField, );
3786 #undef VISIT_MD_FIELDS
3788 Result = GET_OR_DISTINCT(DIGlobalVariable,
3789 (Context, scope.Val, name.Val, linkageName.Val,
3790 file.Val, line.Val, type.Val, isLocal.Val,
3791 isDefinition.Val, variable.Val, declaration.Val));
3795 /// ParseDILocalVariable:
3796 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3797 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3798 /// ::= !DILocalVariable(scope: !0, name: "foo",
3799 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3800 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3801 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3802 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3803 OPTIONAL(name, MDStringField, ); \
3804 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3805 OPTIONAL(file, MDField, ); \
3806 OPTIONAL(line, LineField, ); \
3807 OPTIONAL(type, MDField, ); \
3808 OPTIONAL(flags, DIFlagField, );
3810 #undef VISIT_MD_FIELDS
3812 Result = GET_OR_DISTINCT(DILocalVariable,
3813 (Context, scope.Val, name.Val, file.Val, line.Val,
3814 type.Val, arg.Val, flags.Val));
3818 /// ParseDIExpression:
3819 /// ::= !DIExpression(0, 7, -1)
3820 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3821 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3824 if (ParseToken(lltok::lparen, "expected '(' here"))
3827 SmallVector<uint64_t, 8> Elements;
3828 if (Lex.getKind() != lltok::rparen)
3830 if (Lex.getKind() == lltok::DwarfOp) {
3831 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3833 Elements.push_back(Op);
3836 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3839 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3840 return TokError("expected unsigned integer");
3842 auto &U = Lex.getAPSIntVal();
3843 if (U.ugt(UINT64_MAX))
3844 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3845 Elements.push_back(U.getZExtValue());
3847 } while (EatIfPresent(lltok::comma));
3849 if (ParseToken(lltok::rparen, "expected ')' here"))
3852 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3856 /// ParseDIObjCProperty:
3857 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3858 /// getter: "getFoo", attributes: 7, type: !2)
3859 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3860 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3861 OPTIONAL(name, MDStringField, ); \
3862 OPTIONAL(file, MDField, ); \
3863 OPTIONAL(line, LineField, ); \
3864 OPTIONAL(setter, MDStringField, ); \
3865 OPTIONAL(getter, MDStringField, ); \
3866 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3867 OPTIONAL(type, MDField, );
3869 #undef VISIT_MD_FIELDS
3871 Result = GET_OR_DISTINCT(DIObjCProperty,
3872 (Context, name.Val, file.Val, line.Val, setter.Val,
3873 getter.Val, attributes.Val, type.Val));
3877 /// ParseDIImportedEntity:
3878 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3879 /// line: 7, name: "foo")
3880 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3881 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3882 REQUIRED(tag, DwarfTagField, ); \
3883 REQUIRED(scope, MDField, ); \
3884 OPTIONAL(entity, MDField, ); \
3885 OPTIONAL(line, LineField, ); \
3886 OPTIONAL(name, MDStringField, );
3888 #undef VISIT_MD_FIELDS
3890 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3891 entity.Val, line.Val, name.Val));
3895 #undef PARSE_MD_FIELD
3897 #undef REQUIRE_FIELD
3898 #undef DECLARE_FIELD
3900 /// ParseMetadataAsValue
3901 /// ::= metadata i32 %local
3902 /// ::= metadata i32 @global
3903 /// ::= metadata i32 7
3905 /// ::= metadata !{...}
3906 /// ::= metadata !"string"
3907 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3908 // Note: the type 'metadata' has already been parsed.
3910 if (ParseMetadata(MD, &PFS))
3913 V = MetadataAsValue::get(Context, MD);
3917 /// ParseValueAsMetadata
3921 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3922 PerFunctionState *PFS) {
3925 if (ParseType(Ty, TypeMsg, Loc))
3927 if (Ty->isMetadataTy())
3928 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3931 if (ParseValue(Ty, V, PFS))
3934 MD = ValueAsMetadata::get(V);
3945 /// ::= !DILocation(...)
3946 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3947 if (Lex.getKind() == lltok::MetadataVar) {
3949 if (ParseSpecializedMDNode(N))
3957 if (Lex.getKind() != lltok::exclaim)
3958 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3961 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3965 // ::= '!' STRINGCONSTANT
3966 if (Lex.getKind() == lltok::StringConstant) {
3968 if (ParseMDString(S))
3978 if (ParseMDNodeTail(N))
3985 //===----------------------------------------------------------------------===//
3986 // Function Parsing.
3987 //===----------------------------------------------------------------------===//
3989 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3990 PerFunctionState *PFS) {
3991 if (Ty->isFunctionTy())
3992 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3995 case ValID::t_LocalID:
3996 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3997 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3998 return V == nullptr;
3999 case ValID::t_LocalName:
4000 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4001 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4002 return V == nullptr;
4003 case ValID::t_InlineAsm: {
4005 if (!InlineAsm::Verify(ID.FTy, ID.StrVal2))
4006 return Error(ID.Loc, "invalid type for inline asm constraint string");
4007 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4008 (ID.UIntVal >> 1) & 1,
4009 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4012 case ValID::t_GlobalName:
4013 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4014 return V == nullptr;
4015 case ValID::t_GlobalID:
4016 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4017 return V == nullptr;
4018 case ValID::t_APSInt:
4019 if (!Ty->isIntegerTy())
4020 return Error(ID.Loc, "integer constant must have integer type");
4021 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4022 V = ConstantInt::get(Context, ID.APSIntVal);
4024 case ValID::t_APFloat:
4025 if (!Ty->isFloatingPointTy() ||
4026 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4027 return Error(ID.Loc, "floating point constant invalid for type");
4029 // The lexer has no type info, so builds all half, float, and double FP
4030 // constants as double. Fix this here. Long double does not need this.
4031 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4034 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4036 else if (Ty->isFloatTy())
4037 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4040 V = ConstantFP::get(Context, ID.APFloatVal);
4042 if (V->getType() != Ty)
4043 return Error(ID.Loc, "floating point constant does not have type '" +
4044 getTypeString(Ty) + "'");
4048 if (!Ty->isPointerTy())
4049 return Error(ID.Loc, "null must be a pointer type");
4050 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4052 case ValID::t_Undef:
4053 // FIXME: LabelTy should not be a first-class type.
4054 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4055 return Error(ID.Loc, "invalid type for undef constant");
4056 V = UndefValue::get(Ty);
4058 case ValID::t_EmptyArray:
4059 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4060 return Error(ID.Loc, "invalid empty array initializer");
4061 V = UndefValue::get(Ty);
4064 // FIXME: LabelTy should not be a first-class type.
4065 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4066 return Error(ID.Loc, "invalid type for null constant");
4067 V = Constant::getNullValue(Ty);
4069 case ValID::t_Constant:
4070 if (ID.ConstantVal->getType() != Ty)
4071 return Error(ID.Loc, "constant expression type mismatch");
4075 case ValID::t_ConstantStruct:
4076 case ValID::t_PackedConstantStruct:
4077 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4078 if (ST->getNumElements() != ID.UIntVal)
4079 return Error(ID.Loc,
4080 "initializer with struct type has wrong # elements");
4081 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4082 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4084 // Verify that the elements are compatible with the structtype.
4085 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4086 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4087 return Error(ID.Loc, "element " + Twine(i) +
4088 " of struct initializer doesn't match struct element type");
4090 V = ConstantStruct::get(
4091 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4093 return Error(ID.Loc, "constant expression type mismatch");
4096 llvm_unreachable("Invalid ValID");
4099 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4102 auto Loc = Lex.getLoc();
4103 if (ParseValID(ID, /*PFS=*/nullptr))
4106 case ValID::t_APSInt:
4107 case ValID::t_APFloat:
4108 case ValID::t_Constant:
4109 case ValID::t_ConstantStruct:
4110 case ValID::t_PackedConstantStruct: {
4112 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4114 assert(isa<Constant>(V) && "Expected a constant value");
4115 C = cast<Constant>(V);
4119 return Error(Loc, "expected a constant value");
4123 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4126 return ParseValID(ID, PFS) ||
4127 ConvertValIDToValue(Ty, ID, V, PFS);
4130 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4132 return ParseType(Ty) ||
4133 ParseValue(Ty, V, PFS);
4136 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4137 PerFunctionState &PFS) {
4140 if (ParseTypeAndValue(V, PFS)) return true;
4141 if (!isa<BasicBlock>(V))
4142 return Error(Loc, "expected a basic block");
4143 BB = cast<BasicBlock>(V);
4149 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4150 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4151 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4152 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4153 // Parse the linkage.
4154 LocTy LinkageLoc = Lex.getLoc();
4157 unsigned Visibility;
4158 unsigned DLLStorageClass;
4159 AttrBuilder RetAttrs;
4161 Type *RetType = nullptr;
4162 LocTy RetTypeLoc = Lex.getLoc();
4163 if (ParseOptionalLinkage(Linkage) ||
4164 ParseOptionalVisibility(Visibility) ||
4165 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4166 ParseOptionalCallingConv(CC) ||
4167 ParseOptionalReturnAttrs(RetAttrs) ||
4168 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4171 // Verify that the linkage is ok.
4172 switch ((GlobalValue::LinkageTypes)Linkage) {
4173 case GlobalValue::ExternalLinkage:
4174 break; // always ok.
4175 case GlobalValue::ExternalWeakLinkage:
4177 return Error(LinkageLoc, "invalid linkage for function definition");
4179 case GlobalValue::PrivateLinkage:
4180 case GlobalValue::InternalLinkage:
4181 case GlobalValue::AvailableExternallyLinkage:
4182 case GlobalValue::LinkOnceAnyLinkage:
4183 case GlobalValue::LinkOnceODRLinkage:
4184 case GlobalValue::WeakAnyLinkage:
4185 case GlobalValue::WeakODRLinkage:
4187 return Error(LinkageLoc, "invalid linkage for function declaration");
4189 case GlobalValue::AppendingLinkage:
4190 case GlobalValue::CommonLinkage:
4191 return Error(LinkageLoc, "invalid function linkage type");
4194 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4195 return Error(LinkageLoc,
4196 "symbol with local linkage must have default visibility");
4198 if (!FunctionType::isValidReturnType(RetType))
4199 return Error(RetTypeLoc, "invalid function return type");
4201 LocTy NameLoc = Lex.getLoc();
4203 std::string FunctionName;
4204 if (Lex.getKind() == lltok::GlobalVar) {
4205 FunctionName = Lex.getStrVal();
4206 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4207 unsigned NameID = Lex.getUIntVal();
4209 if (NameID != NumberedVals.size())
4210 return TokError("function expected to be numbered '%" +
4211 Twine(NumberedVals.size()) + "'");
4213 return TokError("expected function name");
4218 if (Lex.getKind() != lltok::lparen)
4219 return TokError("expected '(' in function argument list");
4221 SmallVector<ArgInfo, 8> ArgList;
4223 AttrBuilder FuncAttrs;
4224 std::vector<unsigned> FwdRefAttrGrps;
4226 std::string Section;
4230 LocTy UnnamedAddrLoc;
4231 Constant *Prefix = nullptr;
4232 Constant *Prologue = nullptr;
4233 Constant *PersonalityFn = nullptr;
4236 if (ParseArgumentList(ArgList, isVarArg) ||
4237 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4239 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4241 (EatIfPresent(lltok::kw_section) &&
4242 ParseStringConstant(Section)) ||
4243 parseOptionalComdat(FunctionName, C) ||
4244 ParseOptionalAlignment(Alignment) ||
4245 (EatIfPresent(lltok::kw_gc) &&
4246 ParseStringConstant(GC)) ||
4247 (EatIfPresent(lltok::kw_prefix) &&
4248 ParseGlobalTypeAndValue(Prefix)) ||
4249 (EatIfPresent(lltok::kw_prologue) &&
4250 ParseGlobalTypeAndValue(Prologue)) ||
4251 (EatIfPresent(lltok::kw_personality) &&
4252 ParseGlobalTypeAndValue(PersonalityFn)))
4255 if (FuncAttrs.contains(Attribute::Builtin))
4256 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4258 // If the alignment was parsed as an attribute, move to the alignment field.
4259 if (FuncAttrs.hasAlignmentAttr()) {
4260 Alignment = FuncAttrs.getAlignment();
4261 FuncAttrs.removeAttribute(Attribute::Alignment);
4264 // Okay, if we got here, the function is syntactically valid. Convert types
4265 // and do semantic checks.
4266 std::vector<Type*> ParamTypeList;
4267 SmallVector<AttributeSet, 8> Attrs;
4269 if (RetAttrs.hasAttributes())
4270 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4271 AttributeSet::ReturnIndex,
4274 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4275 ParamTypeList.push_back(ArgList[i].Ty);
4276 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4277 AttrBuilder B(ArgList[i].Attrs, i + 1);
4278 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4282 if (FuncAttrs.hasAttributes())
4283 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4284 AttributeSet::FunctionIndex,
4287 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4289 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4290 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4293 FunctionType::get(RetType, ParamTypeList, isVarArg);
4294 PointerType *PFT = PointerType::getUnqual(FT);
4297 if (!FunctionName.empty()) {
4298 // If this was a definition of a forward reference, remove the definition
4299 // from the forward reference table and fill in the forward ref.
4300 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4301 ForwardRefVals.find(FunctionName);
4302 if (FRVI != ForwardRefVals.end()) {
4303 Fn = M->getFunction(FunctionName);
4305 return Error(FRVI->second.second, "invalid forward reference to "
4306 "function as global value!");
4307 if (Fn->getType() != PFT)
4308 return Error(FRVI->second.second, "invalid forward reference to "
4309 "function '" + FunctionName + "' with wrong type!");
4311 ForwardRefVals.erase(FRVI);
4312 } else if ((Fn = M->getFunction(FunctionName))) {
4313 // Reject redefinitions.
4314 return Error(NameLoc, "invalid redefinition of function '" +
4315 FunctionName + "'");
4316 } else if (M->getNamedValue(FunctionName)) {
4317 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4321 // If this is a definition of a forward referenced function, make sure the
4323 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4324 = ForwardRefValIDs.find(NumberedVals.size());
4325 if (I != ForwardRefValIDs.end()) {
4326 Fn = cast<Function>(I->second.first);
4327 if (Fn->getType() != PFT)
4328 return Error(NameLoc, "type of definition and forward reference of '@" +
4329 Twine(NumberedVals.size()) + "' disagree");
4330 ForwardRefValIDs.erase(I);
4335 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4336 else // Move the forward-reference to the correct spot in the module.
4337 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4339 if (FunctionName.empty())
4340 NumberedVals.push_back(Fn);
4342 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4343 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4344 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4345 Fn->setCallingConv(CC);
4346 Fn->setAttributes(PAL);
4347 Fn->setUnnamedAddr(UnnamedAddr);
4348 Fn->setAlignment(Alignment);
4349 Fn->setSection(Section);
4351 Fn->setPersonalityFn(PersonalityFn);
4352 if (!GC.empty()) Fn->setGC(GC.c_str());
4353 Fn->setPrefixData(Prefix);
4354 Fn->setPrologueData(Prologue);
4355 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4357 // Add all of the arguments we parsed to the function.
4358 Function::arg_iterator ArgIt = Fn->arg_begin();
4359 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4360 // If the argument has a name, insert it into the argument symbol table.
4361 if (ArgList[i].Name.empty()) continue;
4363 // Set the name, if it conflicted, it will be auto-renamed.
4364 ArgIt->setName(ArgList[i].Name);
4366 if (ArgIt->getName() != ArgList[i].Name)
4367 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4368 ArgList[i].Name + "'");
4374 // Check the declaration has no block address forward references.
4376 if (FunctionName.empty()) {
4377 ID.Kind = ValID::t_GlobalID;
4378 ID.UIntVal = NumberedVals.size() - 1;
4380 ID.Kind = ValID::t_GlobalName;
4381 ID.StrVal = FunctionName;
4383 auto Blocks = ForwardRefBlockAddresses.find(ID);
4384 if (Blocks != ForwardRefBlockAddresses.end())
4385 return Error(Blocks->first.Loc,
4386 "cannot take blockaddress inside a declaration");
4390 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4392 if (FunctionNumber == -1) {
4393 ID.Kind = ValID::t_GlobalName;
4394 ID.StrVal = F.getName();
4396 ID.Kind = ValID::t_GlobalID;
4397 ID.UIntVal = FunctionNumber;
4400 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4401 if (Blocks == P.ForwardRefBlockAddresses.end())
4404 for (const auto &I : Blocks->second) {
4405 const ValID &BBID = I.first;
4406 GlobalValue *GV = I.second;
4408 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4409 "Expected local id or name");
4411 if (BBID.Kind == ValID::t_LocalName)
4412 BB = GetBB(BBID.StrVal, BBID.Loc);
4414 BB = GetBB(BBID.UIntVal, BBID.Loc);
4416 return P.Error(BBID.Loc, "referenced value is not a basic block");
4418 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4419 GV->eraseFromParent();
4422 P.ForwardRefBlockAddresses.erase(Blocks);
4426 /// ParseFunctionBody
4427 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4428 bool LLParser::ParseFunctionBody(Function &Fn) {
4429 if (Lex.getKind() != lltok::lbrace)
4430 return TokError("expected '{' in function body");
4431 Lex.Lex(); // eat the {.
4433 int FunctionNumber = -1;
4434 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4436 PerFunctionState PFS(*this, Fn, FunctionNumber);
4438 // Resolve block addresses and allow basic blocks to be forward-declared
4439 // within this function.
4440 if (PFS.resolveForwardRefBlockAddresses())
4442 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4444 // We need at least one basic block.
4445 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4446 return TokError("function body requires at least one basic block");
4448 while (Lex.getKind() != lltok::rbrace &&
4449 Lex.getKind() != lltok::kw_uselistorder)
4450 if (ParseBasicBlock(PFS)) return true;
4452 while (Lex.getKind() != lltok::rbrace)
4453 if (ParseUseListOrder(&PFS))
4459 // Verify function is ok.
4460 return PFS.FinishFunction();
4464 /// ::= LabelStr? Instruction*
4465 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4466 // If this basic block starts out with a name, remember it.
4468 LocTy NameLoc = Lex.getLoc();
4469 if (Lex.getKind() == lltok::LabelStr) {
4470 Name = Lex.getStrVal();
4474 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4476 return Error(NameLoc,
4477 "unable to create block named '" + Name + "'");
4479 std::string NameStr;
4481 // Parse the instructions in this block until we get a terminator.
4484 // This instruction may have three possibilities for a name: a) none
4485 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4486 LocTy NameLoc = Lex.getLoc();
4490 if (Lex.getKind() == lltok::LocalVarID) {
4491 NameID = Lex.getUIntVal();
4493 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4495 } else if (Lex.getKind() == lltok::LocalVar) {
4496 NameStr = Lex.getStrVal();
4498 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4502 switch (ParseInstruction(Inst, BB, PFS)) {
4503 default: llvm_unreachable("Unknown ParseInstruction result!");
4504 case InstError: return true;
4506 BB->getInstList().push_back(Inst);
4508 // With a normal result, we check to see if the instruction is followed by
4509 // a comma and metadata.
4510 if (EatIfPresent(lltok::comma))
4511 if (ParseInstructionMetadata(*Inst))
4514 case InstExtraComma:
4515 BB->getInstList().push_back(Inst);
4517 // If the instruction parser ate an extra comma at the end of it, it
4518 // *must* be followed by metadata.
4519 if (ParseInstructionMetadata(*Inst))
4524 // Set the name on the instruction.
4525 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4526 } while (!isa<TerminatorInst>(Inst));
4531 //===----------------------------------------------------------------------===//
4532 // Instruction Parsing.
4533 //===----------------------------------------------------------------------===//
4535 /// ParseInstruction - Parse one of the many different instructions.
4537 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4538 PerFunctionState &PFS) {
4539 lltok::Kind Token = Lex.getKind();
4540 if (Token == lltok::Eof)
4541 return TokError("found end of file when expecting more instructions");
4542 LocTy Loc = Lex.getLoc();
4543 unsigned KeywordVal = Lex.getUIntVal();
4544 Lex.Lex(); // Eat the keyword.
4547 default: return Error(Loc, "expected instruction opcode");
4548 // Terminator Instructions.
4549 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4550 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4551 case lltok::kw_br: return ParseBr(Inst, PFS);
4552 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4553 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4554 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4555 case lltok::kw_resume: return ParseResume(Inst, PFS);
4556 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4557 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4558 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4559 case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4560 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4561 case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
4562 // Binary Operators.
4566 case lltok::kw_shl: {
4567 bool NUW = EatIfPresent(lltok::kw_nuw);
4568 bool NSW = EatIfPresent(lltok::kw_nsw);
4569 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4571 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4573 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4574 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4577 case lltok::kw_fadd:
4578 case lltok::kw_fsub:
4579 case lltok::kw_fmul:
4580 case lltok::kw_fdiv:
4581 case lltok::kw_frem: {
4582 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4583 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4587 Inst->setFastMathFlags(FMF);
4591 case lltok::kw_sdiv:
4592 case lltok::kw_udiv:
4593 case lltok::kw_lshr:
4594 case lltok::kw_ashr: {
4595 bool Exact = EatIfPresent(lltok::kw_exact);
4597 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4598 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4602 case lltok::kw_urem:
4603 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4606 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4607 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4608 case lltok::kw_fcmp: {
4609 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4610 int Res = ParseCompare(Inst, PFS, KeywordVal);
4614 Inst->setFastMathFlags(FMF);
4619 case lltok::kw_trunc:
4620 case lltok::kw_zext:
4621 case lltok::kw_sext:
4622 case lltok::kw_fptrunc:
4623 case lltok::kw_fpext:
4624 case lltok::kw_bitcast:
4625 case lltok::kw_addrspacecast:
4626 case lltok::kw_uitofp:
4627 case lltok::kw_sitofp:
4628 case lltok::kw_fptoui:
4629 case lltok::kw_fptosi:
4630 case lltok::kw_inttoptr:
4631 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4633 case lltok::kw_select: return ParseSelect(Inst, PFS);
4634 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4635 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4636 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4637 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4638 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4639 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4641 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4642 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4643 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4645 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4646 case lltok::kw_load: return ParseLoad(Inst, PFS);
4647 case lltok::kw_store: return ParseStore(Inst, PFS);
4648 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4649 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4650 case lltok::kw_fence: return ParseFence(Inst, PFS);
4651 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4652 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4653 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4657 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4658 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4659 if (Opc == Instruction::FCmp) {
4660 switch (Lex.getKind()) {
4661 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4662 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4663 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4664 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4665 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4666 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4667 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4668 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4669 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4670 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4671 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4672 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4673 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4674 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4675 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4676 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4677 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4680 switch (Lex.getKind()) {
4681 default: return TokError("expected icmp predicate (e.g. 'eq')");
4682 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4683 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4684 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4685 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4686 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4687 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4688 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4689 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4690 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4691 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4698 //===----------------------------------------------------------------------===//
4699 // Terminator Instructions.
4700 //===----------------------------------------------------------------------===//
4702 /// ParseRet - Parse a return instruction.
4703 /// ::= 'ret' void (',' !dbg, !1)*
4704 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4705 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4706 PerFunctionState &PFS) {
4707 SMLoc TypeLoc = Lex.getLoc();
4709 if (ParseType(Ty, true /*void allowed*/)) return true;
4711 Type *ResType = PFS.getFunction().getReturnType();
4713 if (Ty->isVoidTy()) {
4714 if (!ResType->isVoidTy())
4715 return Error(TypeLoc, "value doesn't match function result type '" +
4716 getTypeString(ResType) + "'");
4718 Inst = ReturnInst::Create(Context);
4723 if (ParseValue(Ty, RV, PFS)) return true;
4725 if (ResType != RV->getType())
4726 return Error(TypeLoc, "value doesn't match function result type '" +
4727 getTypeString(ResType) + "'");
4729 Inst = ReturnInst::Create(Context, RV);
4735 /// ::= 'br' TypeAndValue
4736 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4737 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4740 BasicBlock *Op1, *Op2;
4741 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4743 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4744 Inst = BranchInst::Create(BB);
4748 if (Op0->getType() != Type::getInt1Ty(Context))
4749 return Error(Loc, "branch condition must have 'i1' type");
4751 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4752 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4753 ParseToken(lltok::comma, "expected ',' after true destination") ||
4754 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4757 Inst = BranchInst::Create(Op1, Op2, Op0);
4763 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4765 /// ::= (TypeAndValue ',' TypeAndValue)*
4766 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4767 LocTy CondLoc, BBLoc;
4769 BasicBlock *DefaultBB;
4770 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4771 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4772 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4773 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4776 if (!Cond->getType()->isIntegerTy())
4777 return Error(CondLoc, "switch condition must have integer type");
4779 // Parse the jump table pairs.
4780 SmallPtrSet<Value*, 32> SeenCases;
4781 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4782 while (Lex.getKind() != lltok::rsquare) {
4786 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4787 ParseToken(lltok::comma, "expected ',' after case value") ||
4788 ParseTypeAndBasicBlock(DestBB, PFS))
4791 if (!SeenCases.insert(Constant).second)
4792 return Error(CondLoc, "duplicate case value in switch");
4793 if (!isa<ConstantInt>(Constant))
4794 return Error(CondLoc, "case value is not a constant integer");
4796 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4799 Lex.Lex(); // Eat the ']'.
4801 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4802 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4803 SI->addCase(Table[i].first, Table[i].second);
4810 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4811 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4814 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4815 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4816 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4819 if (!Address->getType()->isPointerTy())
4820 return Error(AddrLoc, "indirectbr address must have pointer type");
4822 // Parse the destination list.
4823 SmallVector<BasicBlock*, 16> DestList;
4825 if (Lex.getKind() != lltok::rsquare) {
4827 if (ParseTypeAndBasicBlock(DestBB, PFS))
4829 DestList.push_back(DestBB);
4831 while (EatIfPresent(lltok::comma)) {
4832 if (ParseTypeAndBasicBlock(DestBB, PFS))
4834 DestList.push_back(DestBB);
4838 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4841 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4842 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4843 IBI->addDestination(DestList[i]);
4850 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4851 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4852 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4853 LocTy CallLoc = Lex.getLoc();
4854 AttrBuilder RetAttrs, FnAttrs;
4855 std::vector<unsigned> FwdRefAttrGrps;
4858 Type *RetType = nullptr;
4861 SmallVector<ParamInfo, 16> ArgList;
4863 BasicBlock *NormalBB, *UnwindBB;
4864 if (ParseOptionalCallingConv(CC) ||
4865 ParseOptionalReturnAttrs(RetAttrs) ||
4866 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4867 ParseValID(CalleeID) ||
4868 ParseParameterList(ArgList, PFS) ||
4869 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4871 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4872 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4873 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4874 ParseTypeAndBasicBlock(UnwindBB, PFS))
4877 // If RetType is a non-function pointer type, then this is the short syntax
4878 // for the call, which means that RetType is just the return type. Infer the
4879 // rest of the function argument types from the arguments that are present.
4880 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4882 // Pull out the types of all of the arguments...
4883 std::vector<Type*> ParamTypes;
4884 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4885 ParamTypes.push_back(ArgList[i].V->getType());
4887 if (!FunctionType::isValidReturnType(RetType))
4888 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4890 Ty = FunctionType::get(RetType, ParamTypes, false);
4895 // Look up the callee.
4897 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4900 // Set up the Attribute for the function.
4901 SmallVector<AttributeSet, 8> Attrs;
4902 if (RetAttrs.hasAttributes())
4903 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4904 AttributeSet::ReturnIndex,
4907 SmallVector<Value*, 8> Args;
4909 // Loop through FunctionType's arguments and ensure they are specified
4910 // correctly. Also, gather any parameter attributes.
4911 FunctionType::param_iterator I = Ty->param_begin();
4912 FunctionType::param_iterator E = Ty->param_end();
4913 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4914 Type *ExpectedTy = nullptr;
4917 } else if (!Ty->isVarArg()) {
4918 return Error(ArgList[i].Loc, "too many arguments specified");
4921 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4922 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4923 getTypeString(ExpectedTy) + "'");
4924 Args.push_back(ArgList[i].V);
4925 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4926 AttrBuilder B(ArgList[i].Attrs, i + 1);
4927 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4932 return Error(CallLoc, "not enough parameters specified for call");
4934 if (FnAttrs.hasAttributes()) {
4935 if (FnAttrs.hasAlignmentAttr())
4936 return Error(CallLoc, "invoke instructions may not have an alignment");
4938 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4939 AttributeSet::FunctionIndex,
4943 // Finish off the Attribute and check them
4944 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4946 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4947 II->setCallingConv(CC);
4948 II->setAttributes(PAL);
4949 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4955 /// ::= 'resume' TypeAndValue
4956 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4957 Value *Exn; LocTy ExnLoc;
4958 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4961 ResumeInst *RI = ResumeInst::Create(Exn);
4966 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
4967 PerFunctionState &PFS) {
4968 if (ParseToken(lltok::lsquare, "expected '[' in cleanuppad"))
4971 while (Lex.getKind() != lltok::rsquare) {
4972 // If this isn't the first argument, we need a comma.
4973 if (!Args.empty() &&
4974 ParseToken(lltok::comma, "expected ',' in argument list"))
4977 // Parse the argument.
4979 Type *ArgTy = nullptr;
4980 if (ParseType(ArgTy, ArgLoc))
4984 if (ArgTy->isMetadataTy()) {
4985 if (ParseMetadataAsValue(V, PFS))
4988 if (ParseValue(ArgTy, V, PFS))
4994 Lex.Lex(); // Lex the ']'.
4999 /// ::= 'cleanupret' ('void' | TypeAndValue) unwind ('to' 'caller' | TypeAndValue)
5000 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5001 Type *RetTy = nullptr;
5002 Value *RetVal = nullptr;
5003 if (ParseType(RetTy, /*AllowVoid=*/true))
5006 if (!RetTy->isVoidTy())
5007 if (ParseValue(RetTy, RetVal, PFS))
5010 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5013 BasicBlock *UnwindBB = nullptr;
5014 if (Lex.getKind() == lltok::kw_to) {
5016 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5019 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5024 Inst = CleanupReturnInst::Create(Context, RetVal, UnwindBB);
5029 /// ::= 'catchret' TypeAndValue
5030 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5032 if (ParseTypeAndBasicBlock(BB, PFS))
5035 Inst = CatchReturnInst::Create(BB);
5040 /// ::= 'catchpad' Type ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5041 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5042 Type *RetType = nullptr;
5044 SmallVector<Value *, 8> Args;
5045 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5048 BasicBlock *NormalBB, *UnwindBB;
5049 if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5050 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5051 ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5052 ParseTypeAndBasicBlock(UnwindBB, PFS))
5055 Inst = CatchPadInst::Create(RetType, NormalBB, UnwindBB, Args);
5059 /// ParseTerminatePad
5060 /// ::= 'terminatepad' ParamList 'to' TypeAndValue
5061 bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5062 SmallVector<Value *, 8> Args;
5063 if (ParseExceptionArgs(Args, PFS))
5066 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5069 BasicBlock *UnwindBB = nullptr;
5070 if (Lex.getKind() == lltok::kw_to) {
5072 if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5075 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5080 Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5085 /// ::= 'cleanuppad' ParamList
5086 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5087 Type *RetType = nullptr;
5089 SmallVector<Value *, 8> Args;
5090 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5093 Inst = CleanupPadInst::Create(RetType, Args);
5097 /// ParseCatchEndPad
5098 /// ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5099 bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5100 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5103 BasicBlock *UnwindBB = nullptr;
5104 if (Lex.getKind() == lltok::kw_to) {
5106 if (Lex.getKind() == lltok::kw_caller) {
5112 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5117 Inst = CatchEndPadInst::Create(Context, UnwindBB);
5121 //===----------------------------------------------------------------------===//
5122 // Binary Operators.
5123 //===----------------------------------------------------------------------===//
5126 /// ::= ArithmeticOps TypeAndValue ',' Value
5128 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5129 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5130 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5131 unsigned Opc, unsigned OperandType) {
5132 LocTy Loc; Value *LHS, *RHS;
5133 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5134 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5135 ParseValue(LHS->getType(), RHS, PFS))
5139 switch (OperandType) {
5140 default: llvm_unreachable("Unknown operand type!");
5141 case 0: // int or FP.
5142 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5143 LHS->getType()->isFPOrFPVectorTy();
5145 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5146 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5150 return Error(Loc, "invalid operand type for instruction");
5152 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5157 /// ::= ArithmeticOps TypeAndValue ',' Value {
5158 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5160 LocTy Loc; Value *LHS, *RHS;
5161 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5162 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5163 ParseValue(LHS->getType(), RHS, PFS))
5166 if (!LHS->getType()->isIntOrIntVectorTy())
5167 return Error(Loc,"instruction requires integer or integer vector operands");
5169 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5175 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5176 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5177 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5179 // Parse the integer/fp comparison predicate.
5183 if (ParseCmpPredicate(Pred, Opc) ||
5184 ParseTypeAndValue(LHS, Loc, PFS) ||
5185 ParseToken(lltok::comma, "expected ',' after compare value") ||
5186 ParseValue(LHS->getType(), RHS, PFS))
5189 if (Opc == Instruction::FCmp) {
5190 if (!LHS->getType()->isFPOrFPVectorTy())
5191 return Error(Loc, "fcmp requires floating point operands");
5192 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5194 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5195 if (!LHS->getType()->isIntOrIntVectorTy() &&
5196 !LHS->getType()->getScalarType()->isPointerTy())
5197 return Error(Loc, "icmp requires integer operands");
5198 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5203 //===----------------------------------------------------------------------===//
5204 // Other Instructions.
5205 //===----------------------------------------------------------------------===//
5209 /// ::= CastOpc TypeAndValue 'to' Type
5210 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5214 Type *DestTy = nullptr;
5215 if (ParseTypeAndValue(Op, Loc, PFS) ||
5216 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5220 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5221 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5222 return Error(Loc, "invalid cast opcode for cast from '" +
5223 getTypeString(Op->getType()) + "' to '" +
5224 getTypeString(DestTy) + "'");
5226 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5231 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5232 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5234 Value *Op0, *Op1, *Op2;
5235 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5236 ParseToken(lltok::comma, "expected ',' after select condition") ||
5237 ParseTypeAndValue(Op1, PFS) ||
5238 ParseToken(lltok::comma, "expected ',' after select value") ||
5239 ParseTypeAndValue(Op2, PFS))
5242 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5243 return Error(Loc, Reason);
5245 Inst = SelectInst::Create(Op0, Op1, Op2);
5250 /// ::= 'va_arg' TypeAndValue ',' Type
5251 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5253 Type *EltTy = nullptr;
5255 if (ParseTypeAndValue(Op, PFS) ||
5256 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5257 ParseType(EltTy, TypeLoc))
5260 if (!EltTy->isFirstClassType())
5261 return Error(TypeLoc, "va_arg requires operand with first class type");
5263 Inst = new VAArgInst(Op, EltTy);
5267 /// ParseExtractElement
5268 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5269 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5272 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5273 ParseToken(lltok::comma, "expected ',' after extract value") ||
5274 ParseTypeAndValue(Op1, PFS))
5277 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5278 return Error(Loc, "invalid extractelement operands");
5280 Inst = ExtractElementInst::Create(Op0, Op1);
5284 /// ParseInsertElement
5285 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5286 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5288 Value *Op0, *Op1, *Op2;
5289 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5290 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5291 ParseTypeAndValue(Op1, PFS) ||
5292 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5293 ParseTypeAndValue(Op2, PFS))
5296 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5297 return Error(Loc, "invalid insertelement operands");
5299 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5303 /// ParseShuffleVector
5304 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5305 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5307 Value *Op0, *Op1, *Op2;
5308 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5309 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5310 ParseTypeAndValue(Op1, PFS) ||
5311 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5312 ParseTypeAndValue(Op2, PFS))
5315 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5316 return Error(Loc, "invalid shufflevector operands");
5318 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5323 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5324 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5325 Type *Ty = nullptr; LocTy TypeLoc;
5328 if (ParseType(Ty, TypeLoc) ||
5329 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5330 ParseValue(Ty, Op0, PFS) ||
5331 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5332 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5333 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5336 bool AteExtraComma = false;
5337 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5339 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5341 if (!EatIfPresent(lltok::comma))
5344 if (Lex.getKind() == lltok::MetadataVar) {
5345 AteExtraComma = true;
5349 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5350 ParseValue(Ty, Op0, PFS) ||
5351 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5352 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5353 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5357 if (!Ty->isFirstClassType())
5358 return Error(TypeLoc, "phi node must have first class type");
5360 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5361 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5362 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5364 return AteExtraComma ? InstExtraComma : InstNormal;
5368 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5370 /// ::= 'catch' TypeAndValue
5372 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5373 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5374 Type *Ty = nullptr; LocTy TyLoc;
5376 if (ParseType(Ty, TyLoc))
5379 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5380 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5382 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5383 LandingPadInst::ClauseType CT;
5384 if (EatIfPresent(lltok::kw_catch))
5385 CT = LandingPadInst::Catch;
5386 else if (EatIfPresent(lltok::kw_filter))
5387 CT = LandingPadInst::Filter;
5389 return TokError("expected 'catch' or 'filter' clause type");
5393 if (ParseTypeAndValue(V, VLoc, PFS))
5396 // A 'catch' type expects a non-array constant. A filter clause expects an
5398 if (CT == LandingPadInst::Catch) {
5399 if (isa<ArrayType>(V->getType()))
5400 Error(VLoc, "'catch' clause has an invalid type");
5402 if (!isa<ArrayType>(V->getType()))
5403 Error(VLoc, "'filter' clause has an invalid type");
5406 Constant *CV = dyn_cast<Constant>(V);
5408 return Error(VLoc, "clause argument must be a constant");
5412 Inst = LP.release();
5417 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5418 /// ParameterList OptionalAttrs
5419 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5420 /// ParameterList OptionalAttrs
5421 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5422 /// ParameterList OptionalAttrs
5423 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5424 CallInst::TailCallKind TCK) {
5425 AttrBuilder RetAttrs, FnAttrs;
5426 std::vector<unsigned> FwdRefAttrGrps;
5429 Type *RetType = nullptr;
5432 SmallVector<ParamInfo, 16> ArgList;
5433 LocTy CallLoc = Lex.getLoc();
5435 if ((TCK != CallInst::TCK_None &&
5436 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5437 ParseOptionalCallingConv(CC) ||
5438 ParseOptionalReturnAttrs(RetAttrs) ||
5439 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5440 ParseValID(CalleeID) ||
5441 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5442 PFS.getFunction().isVarArg()) ||
5443 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5447 // If RetType is a non-function pointer type, then this is the short syntax
5448 // for the call, which means that RetType is just the return type. Infer the
5449 // rest of the function argument types from the arguments that are present.
5450 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5452 // Pull out the types of all of the arguments...
5453 std::vector<Type*> ParamTypes;
5454 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5455 ParamTypes.push_back(ArgList[i].V->getType());
5457 if (!FunctionType::isValidReturnType(RetType))
5458 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5460 Ty = FunctionType::get(RetType, ParamTypes, false);
5465 // Look up the callee.
5467 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5470 // Set up the Attribute for the function.
5471 SmallVector<AttributeSet, 8> Attrs;
5472 if (RetAttrs.hasAttributes())
5473 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5474 AttributeSet::ReturnIndex,
5477 SmallVector<Value*, 8> Args;
5479 // Loop through FunctionType's arguments and ensure they are specified
5480 // correctly. Also, gather any parameter attributes.
5481 FunctionType::param_iterator I = Ty->param_begin();
5482 FunctionType::param_iterator E = Ty->param_end();
5483 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5484 Type *ExpectedTy = nullptr;
5487 } else if (!Ty->isVarArg()) {
5488 return Error(ArgList[i].Loc, "too many arguments specified");
5491 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5492 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5493 getTypeString(ExpectedTy) + "'");
5494 Args.push_back(ArgList[i].V);
5495 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5496 AttrBuilder B(ArgList[i].Attrs, i + 1);
5497 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5502 return Error(CallLoc, "not enough parameters specified for call");
5504 if (FnAttrs.hasAttributes()) {
5505 if (FnAttrs.hasAlignmentAttr())
5506 return Error(CallLoc, "call instructions may not have an alignment");
5508 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5509 AttributeSet::FunctionIndex,
5513 // Finish off the Attribute and check them
5514 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5516 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5517 CI->setTailCallKind(TCK);
5518 CI->setCallingConv(CC);
5519 CI->setAttributes(PAL);
5520 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5525 //===----------------------------------------------------------------------===//
5526 // Memory Instructions.
5527 //===----------------------------------------------------------------------===//
5530 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5531 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5532 Value *Size = nullptr;
5533 LocTy SizeLoc, TyLoc;
5534 unsigned Alignment = 0;
5537 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5539 if (ParseType(Ty, TyLoc)) return true;
5541 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5542 return Error(TyLoc, "invalid type for alloca");
5544 bool AteExtraComma = false;
5545 if (EatIfPresent(lltok::comma)) {
5546 if (Lex.getKind() == lltok::kw_align) {
5547 if (ParseOptionalAlignment(Alignment)) return true;
5548 } else if (Lex.getKind() == lltok::MetadataVar) {
5549 AteExtraComma = true;
5551 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5552 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5557 if (Size && !Size->getType()->isIntegerTy())
5558 return Error(SizeLoc, "element count must have integer type");
5560 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5561 AI->setUsedWithInAlloca(IsInAlloca);
5563 return AteExtraComma ? InstExtraComma : InstNormal;
5567 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5568 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5569 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5570 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5571 Value *Val; LocTy Loc;
5572 unsigned Alignment = 0;
5573 bool AteExtraComma = false;
5574 bool isAtomic = false;
5575 AtomicOrdering Ordering = NotAtomic;
5576 SynchronizationScope Scope = CrossThread;
5578 if (Lex.getKind() == lltok::kw_atomic) {
5583 bool isVolatile = false;
5584 if (Lex.getKind() == lltok::kw_volatile) {
5590 LocTy ExplicitTypeLoc = Lex.getLoc();
5591 if (ParseType(Ty) ||
5592 ParseToken(lltok::comma, "expected comma after load's type") ||
5593 ParseTypeAndValue(Val, Loc, PFS) ||
5594 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5595 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5598 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5599 return Error(Loc, "load operand must be a pointer to a first class type");
5600 if (isAtomic && !Alignment)
5601 return Error(Loc, "atomic load must have explicit non-zero alignment");
5602 if (Ordering == Release || Ordering == AcquireRelease)
5603 return Error(Loc, "atomic load cannot use Release ordering");
5605 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5606 return Error(ExplicitTypeLoc,
5607 "explicit pointee type doesn't match operand's pointee type");
5609 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5610 return AteExtraComma ? InstExtraComma : InstNormal;
5615 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5616 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5617 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5618 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5619 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5620 unsigned Alignment = 0;
5621 bool AteExtraComma = false;
5622 bool isAtomic = false;
5623 AtomicOrdering Ordering = NotAtomic;
5624 SynchronizationScope Scope = CrossThread;
5626 if (Lex.getKind() == lltok::kw_atomic) {
5631 bool isVolatile = false;
5632 if (Lex.getKind() == lltok::kw_volatile) {
5637 if (ParseTypeAndValue(Val, Loc, PFS) ||
5638 ParseToken(lltok::comma, "expected ',' after store operand") ||
5639 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5640 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5641 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5644 if (!Ptr->getType()->isPointerTy())
5645 return Error(PtrLoc, "store operand must be a pointer");
5646 if (!Val->getType()->isFirstClassType())
5647 return Error(Loc, "store operand must be a first class value");
5648 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5649 return Error(Loc, "stored value and pointer type do not match");
5650 if (isAtomic && !Alignment)
5651 return Error(Loc, "atomic store must have explicit non-zero alignment");
5652 if (Ordering == Acquire || Ordering == AcquireRelease)
5653 return Error(Loc, "atomic store cannot use Acquire ordering");
5655 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5656 return AteExtraComma ? InstExtraComma : InstNormal;
5660 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5661 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5662 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5663 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5664 bool AteExtraComma = false;
5665 AtomicOrdering SuccessOrdering = NotAtomic;
5666 AtomicOrdering FailureOrdering = NotAtomic;
5667 SynchronizationScope Scope = CrossThread;
5668 bool isVolatile = false;
5669 bool isWeak = false;
5671 if (EatIfPresent(lltok::kw_weak))
5674 if (EatIfPresent(lltok::kw_volatile))
5677 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5678 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5679 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5680 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5681 ParseTypeAndValue(New, NewLoc, PFS) ||
5682 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5683 ParseOrdering(FailureOrdering))
5686 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5687 return TokError("cmpxchg cannot be unordered");
5688 if (SuccessOrdering < FailureOrdering)
5689 return TokError("cmpxchg must be at least as ordered on success as failure");
5690 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5691 return TokError("cmpxchg failure ordering cannot include release semantics");
5692 if (!Ptr->getType()->isPointerTy())
5693 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5694 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5695 return Error(CmpLoc, "compare value and pointer type do not match");
5696 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5697 return Error(NewLoc, "new value and pointer type do not match");
5698 if (!New->getType()->isIntegerTy())
5699 return Error(NewLoc, "cmpxchg operand must be an integer");
5700 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5701 if (Size < 8 || (Size & (Size - 1)))
5702 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5705 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5706 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5707 CXI->setVolatile(isVolatile);
5708 CXI->setWeak(isWeak);
5710 return AteExtraComma ? InstExtraComma : InstNormal;
5714 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5715 /// 'singlethread'? AtomicOrdering
5716 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5717 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5718 bool AteExtraComma = false;
5719 AtomicOrdering Ordering = NotAtomic;
5720 SynchronizationScope Scope = CrossThread;
5721 bool isVolatile = false;
5722 AtomicRMWInst::BinOp Operation;
5724 if (EatIfPresent(lltok::kw_volatile))
5727 switch (Lex.getKind()) {
5728 default: return TokError("expected binary operation in atomicrmw");
5729 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5730 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5731 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5732 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5733 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5734 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5735 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5736 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5737 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5738 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5739 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5741 Lex.Lex(); // Eat the operation.
5743 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5744 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5745 ParseTypeAndValue(Val, ValLoc, PFS) ||
5746 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5749 if (Ordering == Unordered)
5750 return TokError("atomicrmw cannot be unordered");
5751 if (!Ptr->getType()->isPointerTy())
5752 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5753 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5754 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5755 if (!Val->getType()->isIntegerTy())
5756 return Error(ValLoc, "atomicrmw operand must be an integer");
5757 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5758 if (Size < 8 || (Size & (Size - 1)))
5759 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5762 AtomicRMWInst *RMWI =
5763 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5764 RMWI->setVolatile(isVolatile);
5766 return AteExtraComma ? InstExtraComma : InstNormal;
5770 /// ::= 'fence' 'singlethread'? AtomicOrdering
5771 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5772 AtomicOrdering Ordering = NotAtomic;
5773 SynchronizationScope Scope = CrossThread;
5774 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5777 if (Ordering == Unordered)
5778 return TokError("fence cannot be unordered");
5779 if (Ordering == Monotonic)
5780 return TokError("fence cannot be monotonic");
5782 Inst = new FenceInst(Context, Ordering, Scope);
5786 /// ParseGetElementPtr
5787 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5788 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5789 Value *Ptr = nullptr;
5790 Value *Val = nullptr;
5793 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5796 LocTy ExplicitTypeLoc = Lex.getLoc();
5797 if (ParseType(Ty) ||
5798 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5799 ParseTypeAndValue(Ptr, Loc, PFS))
5802 Type *BaseType = Ptr->getType();
5803 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5804 if (!BasePointerType)
5805 return Error(Loc, "base of getelementptr must be a pointer");
5807 if (Ty != BasePointerType->getElementType())
5808 return Error(ExplicitTypeLoc,
5809 "explicit pointee type doesn't match operand's pointee type");
5811 SmallVector<Value*, 16> Indices;
5812 bool AteExtraComma = false;
5813 // GEP returns a vector of pointers if at least one of parameters is a vector.
5814 // All vector parameters should have the same vector width.
5815 unsigned GEPWidth = BaseType->isVectorTy() ?
5816 BaseType->getVectorNumElements() : 0;
5818 while (EatIfPresent(lltok::comma)) {
5819 if (Lex.getKind() == lltok::MetadataVar) {
5820 AteExtraComma = true;
5823 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5824 if (!Val->getType()->getScalarType()->isIntegerTy())
5825 return Error(EltLoc, "getelementptr index must be an integer");
5827 if (Val->getType()->isVectorTy()) {
5828 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5829 if (GEPWidth && GEPWidth != ValNumEl)
5830 return Error(EltLoc,
5831 "getelementptr vector index has a wrong number of elements");
5832 GEPWidth = ValNumEl;
5834 Indices.push_back(Val);
5837 SmallPtrSet<Type*, 4> Visited;
5838 if (!Indices.empty() && !Ty->isSized(&Visited))
5839 return Error(Loc, "base element of getelementptr must be sized");
5841 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5842 return Error(Loc, "invalid getelementptr indices");
5843 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5845 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5846 return AteExtraComma ? InstExtraComma : InstNormal;
5849 /// ParseExtractValue
5850 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5851 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5852 Value *Val; LocTy Loc;
5853 SmallVector<unsigned, 4> Indices;
5855 if (ParseTypeAndValue(Val, Loc, PFS) ||
5856 ParseIndexList(Indices, AteExtraComma))
5859 if (!Val->getType()->isAggregateType())
5860 return Error(Loc, "extractvalue operand must be aggregate type");
5862 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5863 return Error(Loc, "invalid indices for extractvalue");
5864 Inst = ExtractValueInst::Create(Val, Indices);
5865 return AteExtraComma ? InstExtraComma : InstNormal;
5868 /// ParseInsertValue
5869 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5870 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5871 Value *Val0, *Val1; LocTy Loc0, Loc1;
5872 SmallVector<unsigned, 4> Indices;
5874 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5875 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5876 ParseTypeAndValue(Val1, Loc1, PFS) ||
5877 ParseIndexList(Indices, AteExtraComma))
5880 if (!Val0->getType()->isAggregateType())
5881 return Error(Loc0, "insertvalue operand must be aggregate type");
5883 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5885 return Error(Loc0, "invalid indices for insertvalue");
5886 if (IndexedType != Val1->getType())
5887 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5888 getTypeString(Val1->getType()) + "' instead of '" +
5889 getTypeString(IndexedType) + "'");
5890 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5891 return AteExtraComma ? InstExtraComma : InstNormal;
5894 //===----------------------------------------------------------------------===//
5895 // Embedded metadata.
5896 //===----------------------------------------------------------------------===//
5898 /// ParseMDNodeVector
5899 /// ::= { Element (',' Element)* }
5901 /// ::= 'null' | TypeAndValue
5902 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5903 if (ParseToken(lltok::lbrace, "expected '{' here"))
5906 // Check for an empty list.
5907 if (EatIfPresent(lltok::rbrace))
5911 // Null is a special case since it is typeless.
5912 if (EatIfPresent(lltok::kw_null)) {
5913 Elts.push_back(nullptr);
5918 if (ParseMetadata(MD, nullptr))
5921 } while (EatIfPresent(lltok::comma));
5923 return ParseToken(lltok::rbrace, "expected end of metadata node");
5926 //===----------------------------------------------------------------------===//
5927 // Use-list order directives.
5928 //===----------------------------------------------------------------------===//
5929 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5932 return Error(Loc, "value has no uses");
5934 unsigned NumUses = 0;
5935 SmallDenseMap<const Use *, unsigned, 16> Order;
5936 for (const Use &U : V->uses()) {
5937 if (++NumUses > Indexes.size())
5939 Order[&U] = Indexes[NumUses - 1];
5942 return Error(Loc, "value only has one use");
5943 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5944 return Error(Loc, "wrong number of indexes, expected " +
5945 Twine(std::distance(V->use_begin(), V->use_end())));
5947 V->sortUseList([&](const Use &L, const Use &R) {
5948 return Order.lookup(&L) < Order.lookup(&R);
5953 /// ParseUseListOrderIndexes
5954 /// ::= '{' uint32 (',' uint32)+ '}'
5955 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5956 SMLoc Loc = Lex.getLoc();
5957 if (ParseToken(lltok::lbrace, "expected '{' here"))
5959 if (Lex.getKind() == lltok::rbrace)
5960 return Lex.Error("expected non-empty list of uselistorder indexes");
5962 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5963 // indexes should be distinct numbers in the range [0, size-1], and should
5965 unsigned Offset = 0;
5967 bool IsOrdered = true;
5968 assert(Indexes.empty() && "Expected empty order vector");
5971 if (ParseUInt32(Index))
5974 // Update consistency checks.
5975 Offset += Index - Indexes.size();
5976 Max = std::max(Max, Index);
5977 IsOrdered &= Index == Indexes.size();
5979 Indexes.push_back(Index);
5980 } while (EatIfPresent(lltok::comma));
5982 if (ParseToken(lltok::rbrace, "expected '}' here"))
5985 if (Indexes.size() < 2)
5986 return Error(Loc, "expected >= 2 uselistorder indexes");
5987 if (Offset != 0 || Max >= Indexes.size())
5988 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5990 return Error(Loc, "expected uselistorder indexes to change the order");
5995 /// ParseUseListOrder
5996 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5997 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5998 SMLoc Loc = Lex.getLoc();
5999 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6003 SmallVector<unsigned, 16> Indexes;
6004 if (ParseTypeAndValue(V, PFS) ||
6005 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6006 ParseUseListOrderIndexes(Indexes))
6009 return sortUseListOrder(V, Indexes, Loc);
6012 /// ParseUseListOrderBB
6013 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6014 bool LLParser::ParseUseListOrderBB() {
6015 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6016 SMLoc Loc = Lex.getLoc();
6020 SmallVector<unsigned, 16> Indexes;
6021 if (ParseValID(Fn) ||
6022 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6023 ParseValID(Label) ||
6024 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6025 ParseUseListOrderIndexes(Indexes))
6028 // Check the function.
6030 if (Fn.Kind == ValID::t_GlobalName)
6031 GV = M->getNamedValue(Fn.StrVal);
6032 else if (Fn.Kind == ValID::t_GlobalID)
6033 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6035 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6037 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6038 auto *F = dyn_cast<Function>(GV);
6040 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6041 if (F->isDeclaration())
6042 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6044 // Check the basic block.
6045 if (Label.Kind == ValID::t_LocalID)
6046 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6047 if (Label.Kind != ValID::t_LocalName)
6048 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6049 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6051 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6052 if (!isa<BasicBlock>(V))
6053 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6055 return sortUseListOrder(V, Indexes, Loc);