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 std::string Attr = Lex.getStrVal();
921 if (EatIfPresent(lltok::equal) &&
922 ParseStringConstant(Val))
925 B.addAttribute(Attr, Val);
929 // Target-independent attributes:
930 case lltok::kw_align: {
931 // As a hack, we allow function alignment to be initially parsed as an
932 // attribute on a function declaration/definition or added to an attribute
933 // group and later moved to the alignment field.
937 if (ParseToken(lltok::equal, "expected '=' here") ||
938 ParseUInt32(Alignment))
941 if (ParseOptionalAlignment(Alignment))
944 B.addAlignmentAttr(Alignment);
947 case lltok::kw_alignstack: {
951 if (ParseToken(lltok::equal, "expected '=' here") ||
952 ParseUInt32(Alignment))
955 if (ParseOptionalStackAlignment(Alignment))
958 B.addStackAlignmentAttr(Alignment);
961 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
962 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
963 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
964 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
965 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
966 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
967 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
968 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
969 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
970 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
971 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
972 case lltok::kw_noimplicitfloat:
973 B.addAttribute(Attribute::NoImplicitFloat); break;
974 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
975 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
976 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
977 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
978 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
979 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
980 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
981 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
982 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
983 case lltok::kw_returns_twice:
984 B.addAttribute(Attribute::ReturnsTwice); break;
985 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
986 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
987 case lltok::kw_sspstrong:
988 B.addAttribute(Attribute::StackProtectStrong); break;
989 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
990 case lltok::kw_sanitize_address:
991 B.addAttribute(Attribute::SanitizeAddress); break;
992 case lltok::kw_sanitize_thread:
993 B.addAttribute(Attribute::SanitizeThread); break;
994 case lltok::kw_sanitize_memory:
995 B.addAttribute(Attribute::SanitizeMemory); break;
996 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
999 case lltok::kw_inreg:
1000 case lltok::kw_signext:
1001 case lltok::kw_zeroext:
1004 "invalid use of attribute on a function");
1006 case lltok::kw_byval:
1007 case lltok::kw_dereferenceable:
1008 case lltok::kw_dereferenceable_or_null:
1009 case lltok::kw_inalloca:
1010 case lltok::kw_nest:
1011 case lltok::kw_noalias:
1012 case lltok::kw_nocapture:
1013 case lltok::kw_nonnull:
1014 case lltok::kw_returned:
1015 case lltok::kw_sret:
1018 "invalid use of parameter-only attribute on a function");
1026 //===----------------------------------------------------------------------===//
1027 // GlobalValue Reference/Resolution Routines.
1028 //===----------------------------------------------------------------------===//
1030 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1031 /// forward reference record if needed. This can return null if the value
1032 /// exists but does not have the right type.
1033 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1035 PointerType *PTy = dyn_cast<PointerType>(Ty);
1037 Error(Loc, "global variable reference must have pointer type");
1041 // Look this name up in the normal function symbol table.
1043 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1045 // If this is a forward reference for the value, see if we already created a
1046 // forward ref record.
1048 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1049 I = ForwardRefVals.find(Name);
1050 if (I != ForwardRefVals.end())
1051 Val = I->second.first;
1054 // If we have the value in the symbol table or fwd-ref table, return it.
1056 if (Val->getType() == Ty) return Val;
1057 Error(Loc, "'@" + Name + "' defined with type '" +
1058 getTypeString(Val->getType()) + "'");
1062 // Otherwise, create a new forward reference for this value and remember it.
1063 GlobalValue *FwdVal;
1064 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1065 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1067 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1068 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1069 nullptr, GlobalVariable::NotThreadLocal,
1070 PTy->getAddressSpace());
1072 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1076 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1077 PointerType *PTy = dyn_cast<PointerType>(Ty);
1079 Error(Loc, "global variable reference must have pointer type");
1083 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1085 // If this is a forward reference for the value, see if we already created a
1086 // forward ref record.
1088 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1089 I = ForwardRefValIDs.find(ID);
1090 if (I != ForwardRefValIDs.end())
1091 Val = I->second.first;
1094 // If we have the value in the symbol table or fwd-ref table, return it.
1096 if (Val->getType() == Ty) return Val;
1097 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1098 getTypeString(Val->getType()) + "'");
1102 // Otherwise, create a new forward reference for this value and remember it.
1103 GlobalValue *FwdVal;
1104 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1105 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1107 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1108 GlobalValue::ExternalWeakLinkage, nullptr, "");
1110 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1115 //===----------------------------------------------------------------------===//
1116 // Comdat Reference/Resolution Routines.
1117 //===----------------------------------------------------------------------===//
1119 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1120 // Look this name up in the comdat symbol table.
1121 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1122 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1123 if (I != ComdatSymTab.end())
1126 // Otherwise, create a new forward reference for this value and remember it.
1127 Comdat *C = M->getOrInsertComdat(Name);
1128 ForwardRefComdats[Name] = Loc;
1133 //===----------------------------------------------------------------------===//
1135 //===----------------------------------------------------------------------===//
1137 /// ParseToken - If the current token has the specified kind, eat it and return
1138 /// success. Otherwise, emit the specified error and return failure.
1139 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1140 if (Lex.getKind() != T)
1141 return TokError(ErrMsg);
1146 /// ParseStringConstant
1147 /// ::= StringConstant
1148 bool LLParser::ParseStringConstant(std::string &Result) {
1149 if (Lex.getKind() != lltok::StringConstant)
1150 return TokError("expected string constant");
1151 Result = Lex.getStrVal();
1158 bool LLParser::ParseUInt32(unsigned &Val) {
1159 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1160 return TokError("expected integer");
1161 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1162 if (Val64 != unsigned(Val64))
1163 return TokError("expected 32-bit integer (too large)");
1171 bool LLParser::ParseUInt64(uint64_t &Val) {
1172 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1173 return TokError("expected integer");
1174 Val = Lex.getAPSIntVal().getLimitedValue();
1180 /// := 'localdynamic'
1181 /// := 'initialexec'
1183 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1184 switch (Lex.getKind()) {
1186 return TokError("expected localdynamic, initialexec or localexec");
1187 case lltok::kw_localdynamic:
1188 TLM = GlobalVariable::LocalDynamicTLSModel;
1190 case lltok::kw_initialexec:
1191 TLM = GlobalVariable::InitialExecTLSModel;
1193 case lltok::kw_localexec:
1194 TLM = GlobalVariable::LocalExecTLSModel;
1202 /// ParseOptionalThreadLocal
1204 /// := 'thread_local'
1205 /// := 'thread_local' '(' tlsmodel ')'
1206 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1207 TLM = GlobalVariable::NotThreadLocal;
1208 if (!EatIfPresent(lltok::kw_thread_local))
1211 TLM = GlobalVariable::GeneralDynamicTLSModel;
1212 if (Lex.getKind() == lltok::lparen) {
1214 return ParseTLSModel(TLM) ||
1215 ParseToken(lltok::rparen, "expected ')' after thread local model");
1220 /// ParseOptionalAddrSpace
1222 /// := 'addrspace' '(' uint32 ')'
1223 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1225 if (!EatIfPresent(lltok::kw_addrspace))
1227 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1228 ParseUInt32(AddrSpace) ||
1229 ParseToken(lltok::rparen, "expected ')' in address space");
1232 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1233 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1234 bool HaveError = false;
1239 lltok::Kind Token = Lex.getKind();
1241 default: // End of attributes.
1243 case lltok::kw_align: {
1245 if (ParseOptionalAlignment(Alignment))
1247 B.addAlignmentAttr(Alignment);
1250 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1251 case lltok::kw_dereferenceable: {
1253 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1255 B.addDereferenceableAttr(Bytes);
1258 case lltok::kw_dereferenceable_or_null: {
1260 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1262 B.addDereferenceableOrNullAttr(Bytes);
1265 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1266 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1267 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1268 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1269 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1270 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1271 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1272 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1273 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1274 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1275 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1276 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1278 case lltok::kw_alignstack:
1279 case lltok::kw_alwaysinline:
1280 case lltok::kw_argmemonly:
1281 case lltok::kw_builtin:
1282 case lltok::kw_inlinehint:
1283 case lltok::kw_jumptable:
1284 case lltok::kw_minsize:
1285 case lltok::kw_naked:
1286 case lltok::kw_nobuiltin:
1287 case lltok::kw_noduplicate:
1288 case lltok::kw_noimplicitfloat:
1289 case lltok::kw_noinline:
1290 case lltok::kw_nonlazybind:
1291 case lltok::kw_noredzone:
1292 case lltok::kw_noreturn:
1293 case lltok::kw_nounwind:
1294 case lltok::kw_optnone:
1295 case lltok::kw_optsize:
1296 case lltok::kw_returns_twice:
1297 case lltok::kw_sanitize_address:
1298 case lltok::kw_sanitize_memory:
1299 case lltok::kw_sanitize_thread:
1301 case lltok::kw_sspreq:
1302 case lltok::kw_sspstrong:
1303 case lltok::kw_safestack:
1304 case lltok::kw_uwtable:
1305 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1313 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1314 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1315 bool HaveError = false;
1320 lltok::Kind Token = Lex.getKind();
1322 default: // End of attributes.
1324 case lltok::kw_dereferenceable: {
1326 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1328 B.addDereferenceableAttr(Bytes);
1331 case lltok::kw_dereferenceable_or_null: {
1333 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1335 B.addDereferenceableOrNullAttr(Bytes);
1338 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1339 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1340 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1341 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1342 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1345 case lltok::kw_align:
1346 case lltok::kw_byval:
1347 case lltok::kw_inalloca:
1348 case lltok::kw_nest:
1349 case lltok::kw_nocapture:
1350 case lltok::kw_returned:
1351 case lltok::kw_sret:
1352 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1355 case lltok::kw_alignstack:
1356 case lltok::kw_alwaysinline:
1357 case lltok::kw_argmemonly:
1358 case lltok::kw_builtin:
1359 case lltok::kw_cold:
1360 case lltok::kw_inlinehint:
1361 case lltok::kw_jumptable:
1362 case lltok::kw_minsize:
1363 case lltok::kw_naked:
1364 case lltok::kw_nobuiltin:
1365 case lltok::kw_noduplicate:
1366 case lltok::kw_noimplicitfloat:
1367 case lltok::kw_noinline:
1368 case lltok::kw_nonlazybind:
1369 case lltok::kw_noredzone:
1370 case lltok::kw_noreturn:
1371 case lltok::kw_nounwind:
1372 case lltok::kw_optnone:
1373 case lltok::kw_optsize:
1374 case lltok::kw_returns_twice:
1375 case lltok::kw_sanitize_address:
1376 case lltok::kw_sanitize_memory:
1377 case lltok::kw_sanitize_thread:
1379 case lltok::kw_sspreq:
1380 case lltok::kw_sspstrong:
1381 case lltok::kw_safestack:
1382 case lltok::kw_uwtable:
1383 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1386 case lltok::kw_readnone:
1387 case lltok::kw_readonly:
1388 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1395 /// ParseOptionalLinkage
1402 /// ::= 'linkonce_odr'
1403 /// ::= 'available_externally'
1406 /// ::= 'extern_weak'
1408 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1410 switch (Lex.getKind()) {
1411 default: Res=GlobalValue::ExternalLinkage; return false;
1412 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1413 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1414 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1415 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1416 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1417 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1418 case lltok::kw_available_externally:
1419 Res = GlobalValue::AvailableExternallyLinkage;
1421 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1422 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1423 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1424 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1431 /// ParseOptionalVisibility
1437 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1438 switch (Lex.getKind()) {
1439 default: Res = GlobalValue::DefaultVisibility; return false;
1440 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1441 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1442 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1448 /// ParseOptionalDLLStorageClass
1453 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1454 switch (Lex.getKind()) {
1455 default: Res = GlobalValue::DefaultStorageClass; return false;
1456 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1457 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1463 /// ParseOptionalCallingConv
1467 /// ::= 'intel_ocl_bicc'
1469 /// ::= 'x86_stdcallcc'
1470 /// ::= 'x86_fastcallcc'
1471 /// ::= 'x86_thiscallcc'
1472 /// ::= 'x86_vectorcallcc'
1473 /// ::= 'arm_apcscc'
1474 /// ::= 'arm_aapcscc'
1475 /// ::= 'arm_aapcs_vfpcc'
1476 /// ::= 'msp430_intrcc'
1477 /// ::= 'ptx_kernel'
1478 /// ::= 'ptx_device'
1480 /// ::= 'spir_kernel'
1481 /// ::= 'x86_64_sysvcc'
1482 /// ::= 'x86_64_win64cc'
1483 /// ::= 'webkit_jscc'
1485 /// ::= 'preserve_mostcc'
1486 /// ::= 'preserve_allcc'
1490 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1491 switch (Lex.getKind()) {
1492 default: CC = CallingConv::C; return false;
1493 case lltok::kw_ccc: CC = CallingConv::C; break;
1494 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1495 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1496 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1497 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1498 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1499 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1500 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1501 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1502 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1503 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1504 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1505 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1506 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1507 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1508 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1509 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1510 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1511 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1512 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1513 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1514 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1515 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1516 case lltok::kw_cc: {
1518 return ParseUInt32(CC);
1526 /// ParseMetadataAttachment
1528 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1529 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1531 std::string Name = Lex.getStrVal();
1532 Kind = M->getMDKindID(Name);
1535 return ParseMDNode(MD);
1538 /// ParseInstructionMetadata
1539 /// ::= !dbg !42 (',' !dbg !57)*
1540 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1542 if (Lex.getKind() != lltok::MetadataVar)
1543 return TokError("expected metadata after comma");
1547 if (ParseMetadataAttachment(MDK, N))
1550 Inst.setMetadata(MDK, N);
1551 if (MDK == LLVMContext::MD_tbaa)
1552 InstsWithTBAATag.push_back(&Inst);
1554 // If this is the end of the list, we're done.
1555 } while (EatIfPresent(lltok::comma));
1559 /// ParseOptionalFunctionMetadata
1561 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1562 while (Lex.getKind() == lltok::MetadataVar) {
1565 if (ParseMetadataAttachment(MDK, N))
1568 F.setMetadata(MDK, N);
1573 /// ParseOptionalAlignment
1576 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1578 if (!EatIfPresent(lltok::kw_align))
1580 LocTy AlignLoc = Lex.getLoc();
1581 if (ParseUInt32(Alignment)) return true;
1582 if (!isPowerOf2_32(Alignment))
1583 return Error(AlignLoc, "alignment is not a power of two");
1584 if (Alignment > Value::MaximumAlignment)
1585 return Error(AlignLoc, "huge alignments are not supported yet");
1589 /// ParseOptionalDerefAttrBytes
1591 /// ::= AttrKind '(' 4 ')'
1593 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1594 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1596 assert((AttrKind == lltok::kw_dereferenceable ||
1597 AttrKind == lltok::kw_dereferenceable_or_null) &&
1601 if (!EatIfPresent(AttrKind))
1603 LocTy ParenLoc = Lex.getLoc();
1604 if (!EatIfPresent(lltok::lparen))
1605 return Error(ParenLoc, "expected '('");
1606 LocTy DerefLoc = Lex.getLoc();
1607 if (ParseUInt64(Bytes)) return true;
1608 ParenLoc = Lex.getLoc();
1609 if (!EatIfPresent(lltok::rparen))
1610 return Error(ParenLoc, "expected ')'");
1612 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1616 /// ParseOptionalCommaAlign
1620 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1622 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1623 bool &AteExtraComma) {
1624 AteExtraComma = false;
1625 while (EatIfPresent(lltok::comma)) {
1626 // Metadata at the end is an early exit.
1627 if (Lex.getKind() == lltok::MetadataVar) {
1628 AteExtraComma = true;
1632 if (Lex.getKind() != lltok::kw_align)
1633 return Error(Lex.getLoc(), "expected metadata or 'align'");
1635 if (ParseOptionalAlignment(Alignment)) return true;
1641 /// ParseScopeAndOrdering
1642 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1645 /// This sets Scope and Ordering to the parsed values.
1646 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1647 AtomicOrdering &Ordering) {
1651 Scope = CrossThread;
1652 if (EatIfPresent(lltok::kw_singlethread))
1653 Scope = SingleThread;
1655 return ParseOrdering(Ordering);
1659 /// ::= AtomicOrdering
1661 /// This sets Ordering to the parsed value.
1662 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1663 switch (Lex.getKind()) {
1664 default: return TokError("Expected ordering on atomic instruction");
1665 case lltok::kw_unordered: Ordering = Unordered; break;
1666 case lltok::kw_monotonic: Ordering = Monotonic; break;
1667 case lltok::kw_acquire: Ordering = Acquire; break;
1668 case lltok::kw_release: Ordering = Release; break;
1669 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1670 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1676 /// ParseOptionalStackAlignment
1678 /// ::= 'alignstack' '(' 4 ')'
1679 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1681 if (!EatIfPresent(lltok::kw_alignstack))
1683 LocTy ParenLoc = Lex.getLoc();
1684 if (!EatIfPresent(lltok::lparen))
1685 return Error(ParenLoc, "expected '('");
1686 LocTy AlignLoc = Lex.getLoc();
1687 if (ParseUInt32(Alignment)) return true;
1688 ParenLoc = Lex.getLoc();
1689 if (!EatIfPresent(lltok::rparen))
1690 return Error(ParenLoc, "expected ')'");
1691 if (!isPowerOf2_32(Alignment))
1692 return Error(AlignLoc, "stack alignment is not a power of two");
1696 /// ParseIndexList - This parses the index list for an insert/extractvalue
1697 /// instruction. This sets AteExtraComma in the case where we eat an extra
1698 /// comma at the end of the line and find that it is followed by metadata.
1699 /// Clients that don't allow metadata can call the version of this function that
1700 /// only takes one argument.
1703 /// ::= (',' uint32)+
1705 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1706 bool &AteExtraComma) {
1707 AteExtraComma = false;
1709 if (Lex.getKind() != lltok::comma)
1710 return TokError("expected ',' as start of index list");
1712 while (EatIfPresent(lltok::comma)) {
1713 if (Lex.getKind() == lltok::MetadataVar) {
1714 if (Indices.empty()) return TokError("expected index");
1715 AteExtraComma = true;
1719 if (ParseUInt32(Idx)) return true;
1720 Indices.push_back(Idx);
1726 //===----------------------------------------------------------------------===//
1728 //===----------------------------------------------------------------------===//
1730 /// ParseType - Parse a type.
1731 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1732 SMLoc TypeLoc = Lex.getLoc();
1733 switch (Lex.getKind()) {
1735 return TokError(Msg);
1737 // Type ::= 'float' | 'void' (etc)
1738 Result = Lex.getTyVal();
1742 // Type ::= StructType
1743 if (ParseAnonStructType(Result, false))
1746 case lltok::lsquare:
1747 // Type ::= '[' ... ']'
1748 Lex.Lex(); // eat the lsquare.
1749 if (ParseArrayVectorType(Result, false))
1752 case lltok::less: // Either vector or packed struct.
1753 // Type ::= '<' ... '>'
1755 if (Lex.getKind() == lltok::lbrace) {
1756 if (ParseAnonStructType(Result, true) ||
1757 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1759 } else if (ParseArrayVectorType(Result, true))
1762 case lltok::LocalVar: {
1764 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1766 // If the type hasn't been defined yet, create a forward definition and
1767 // remember where that forward def'n was seen (in case it never is defined).
1769 Entry.first = StructType::create(Context, Lex.getStrVal());
1770 Entry.second = Lex.getLoc();
1772 Result = Entry.first;
1777 case lltok::LocalVarID: {
1779 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1781 // If the type hasn't been defined yet, create a forward definition and
1782 // remember where that forward def'n was seen (in case it never is defined).
1784 Entry.first = StructType::create(Context);
1785 Entry.second = Lex.getLoc();
1787 Result = Entry.first;
1793 // Parse the type suffixes.
1795 switch (Lex.getKind()) {
1798 if (!AllowVoid && Result->isVoidTy())
1799 return Error(TypeLoc, "void type only allowed for function results");
1802 // Type ::= Type '*'
1804 if (Result->isLabelTy())
1805 return TokError("basic block pointers are invalid");
1806 if (Result->isVoidTy())
1807 return TokError("pointers to void are invalid - use i8* instead");
1808 if (!PointerType::isValidElementType(Result))
1809 return TokError("pointer to this type is invalid");
1810 Result = PointerType::getUnqual(Result);
1814 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1815 case lltok::kw_addrspace: {
1816 if (Result->isLabelTy())
1817 return TokError("basic block pointers are invalid");
1818 if (Result->isVoidTy())
1819 return TokError("pointers to void are invalid; use i8* instead");
1820 if (!PointerType::isValidElementType(Result))
1821 return TokError("pointer to this type is invalid");
1823 if (ParseOptionalAddrSpace(AddrSpace) ||
1824 ParseToken(lltok::star, "expected '*' in address space"))
1827 Result = PointerType::get(Result, AddrSpace);
1831 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1833 if (ParseFunctionType(Result))
1840 /// ParseParameterList
1842 /// ::= '(' Arg (',' Arg)* ')'
1844 /// ::= Type OptionalAttributes Value OptionalAttributes
1845 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1846 PerFunctionState &PFS, bool IsMustTailCall,
1847 bool InVarArgsFunc) {
1848 if (ParseToken(lltok::lparen, "expected '(' in call"))
1851 unsigned AttrIndex = 1;
1852 while (Lex.getKind() != lltok::rparen) {
1853 // If this isn't the first argument, we need a comma.
1854 if (!ArgList.empty() &&
1855 ParseToken(lltok::comma, "expected ',' in argument list"))
1858 // Parse an ellipsis if this is a musttail call in a variadic function.
1859 if (Lex.getKind() == lltok::dotdotdot) {
1860 const char *Msg = "unexpected ellipsis in argument list for ";
1861 if (!IsMustTailCall)
1862 return TokError(Twine(Msg) + "non-musttail call");
1864 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1865 Lex.Lex(); // Lex the '...', it is purely for readability.
1866 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1869 // Parse the argument.
1871 Type *ArgTy = nullptr;
1872 AttrBuilder ArgAttrs;
1874 if (ParseType(ArgTy, ArgLoc))
1877 if (ArgTy->isMetadataTy()) {
1878 if (ParseMetadataAsValue(V, PFS))
1881 // Otherwise, handle normal operands.
1882 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1885 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1890 if (IsMustTailCall && InVarArgsFunc)
1891 return TokError("expected '...' at end of argument list for musttail call "
1892 "in varargs function");
1894 Lex.Lex(); // Lex the ')'.
1900 /// ParseArgumentList - Parse the argument list for a function type or function
1902 /// ::= '(' ArgTypeListI ')'
1906 /// ::= ArgTypeList ',' '...'
1907 /// ::= ArgType (',' ArgType)*
1909 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1912 assert(Lex.getKind() == lltok::lparen);
1913 Lex.Lex(); // eat the (.
1915 if (Lex.getKind() == lltok::rparen) {
1917 } else if (Lex.getKind() == lltok::dotdotdot) {
1921 LocTy TypeLoc = Lex.getLoc();
1922 Type *ArgTy = nullptr;
1926 if (ParseType(ArgTy) ||
1927 ParseOptionalParamAttrs(Attrs)) return true;
1929 if (ArgTy->isVoidTy())
1930 return Error(TypeLoc, "argument can not have void type");
1932 if (Lex.getKind() == lltok::LocalVar) {
1933 Name = Lex.getStrVal();
1937 if (!FunctionType::isValidArgumentType(ArgTy))
1938 return Error(TypeLoc, "invalid type for function argument");
1940 unsigned AttrIndex = 1;
1941 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1942 AttrIndex++, Attrs),
1945 while (EatIfPresent(lltok::comma)) {
1946 // Handle ... at end of arg list.
1947 if (EatIfPresent(lltok::dotdotdot)) {
1952 // Otherwise must be an argument type.
1953 TypeLoc = Lex.getLoc();
1954 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1956 if (ArgTy->isVoidTy())
1957 return Error(TypeLoc, "argument can not have void type");
1959 if (Lex.getKind() == lltok::LocalVar) {
1960 Name = Lex.getStrVal();
1966 if (!ArgTy->isFirstClassType())
1967 return Error(TypeLoc, "invalid type for function argument");
1969 ArgList.emplace_back(
1971 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1976 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1979 /// ParseFunctionType
1980 /// ::= Type ArgumentList OptionalAttrs
1981 bool LLParser::ParseFunctionType(Type *&Result) {
1982 assert(Lex.getKind() == lltok::lparen);
1984 if (!FunctionType::isValidReturnType(Result))
1985 return TokError("invalid function return type");
1987 SmallVector<ArgInfo, 8> ArgList;
1989 if (ParseArgumentList(ArgList, isVarArg))
1992 // Reject names on the arguments lists.
1993 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1994 if (!ArgList[i].Name.empty())
1995 return Error(ArgList[i].Loc, "argument name invalid in function type");
1996 if (ArgList[i].Attrs.hasAttributes(i + 1))
1997 return Error(ArgList[i].Loc,
1998 "argument attributes invalid in function type");
2001 SmallVector<Type*, 16> ArgListTy;
2002 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2003 ArgListTy.push_back(ArgList[i].Ty);
2005 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2009 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2011 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2012 SmallVector<Type*, 8> Elts;
2013 if (ParseStructBody(Elts)) return true;
2015 Result = StructType::get(Context, Elts, Packed);
2019 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2020 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2021 std::pair<Type*, LocTy> &Entry,
2023 // If the type was already defined, diagnose the redefinition.
2024 if (Entry.first && !Entry.second.isValid())
2025 return Error(TypeLoc, "redefinition of type");
2027 // If we have opaque, just return without filling in the definition for the
2028 // struct. This counts as a definition as far as the .ll file goes.
2029 if (EatIfPresent(lltok::kw_opaque)) {
2030 // This type is being defined, so clear the location to indicate this.
2031 Entry.second = SMLoc();
2033 // If this type number has never been uttered, create it.
2035 Entry.first = StructType::create(Context, Name);
2036 ResultTy = Entry.first;
2040 // If the type starts with '<', then it is either a packed struct or a vector.
2041 bool isPacked = EatIfPresent(lltok::less);
2043 // If we don't have a struct, then we have a random type alias, which we
2044 // accept for compatibility with old files. These types are not allowed to be
2045 // forward referenced and not allowed to be recursive.
2046 if (Lex.getKind() != lltok::lbrace) {
2048 return Error(TypeLoc, "forward references to non-struct type");
2052 return ParseArrayVectorType(ResultTy, true);
2053 return ParseType(ResultTy);
2056 // This type is being defined, so clear the location to indicate this.
2057 Entry.second = SMLoc();
2059 // If this type number has never been uttered, create it.
2061 Entry.first = StructType::create(Context, Name);
2063 StructType *STy = cast<StructType>(Entry.first);
2065 SmallVector<Type*, 8> Body;
2066 if (ParseStructBody(Body) ||
2067 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2070 STy->setBody(Body, isPacked);
2076 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2079 /// ::= '{' Type (',' Type)* '}'
2080 /// ::= '<' '{' '}' '>'
2081 /// ::= '<' '{' Type (',' Type)* '}' '>'
2082 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2083 assert(Lex.getKind() == lltok::lbrace);
2084 Lex.Lex(); // Consume the '{'
2086 // Handle the empty struct.
2087 if (EatIfPresent(lltok::rbrace))
2090 LocTy EltTyLoc = Lex.getLoc();
2092 if (ParseType(Ty)) return true;
2095 if (!StructType::isValidElementType(Ty))
2096 return Error(EltTyLoc, "invalid element type for struct");
2098 while (EatIfPresent(lltok::comma)) {
2099 EltTyLoc = Lex.getLoc();
2100 if (ParseType(Ty)) return true;
2102 if (!StructType::isValidElementType(Ty))
2103 return Error(EltTyLoc, "invalid element type for struct");
2108 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2111 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2112 /// token has already been consumed.
2114 /// ::= '[' APSINTVAL 'x' Types ']'
2115 /// ::= '<' APSINTVAL 'x' Types '>'
2116 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2117 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2118 Lex.getAPSIntVal().getBitWidth() > 64)
2119 return TokError("expected number in address space");
2121 LocTy SizeLoc = Lex.getLoc();
2122 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2125 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2128 LocTy TypeLoc = Lex.getLoc();
2129 Type *EltTy = nullptr;
2130 if (ParseType(EltTy)) return true;
2132 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2133 "expected end of sequential type"))
2138 return Error(SizeLoc, "zero element vector is illegal");
2139 if ((unsigned)Size != Size)
2140 return Error(SizeLoc, "size too large for vector");
2141 if (!VectorType::isValidElementType(EltTy))
2142 return Error(TypeLoc, "invalid vector element type");
2143 Result = VectorType::get(EltTy, unsigned(Size));
2145 if (!ArrayType::isValidElementType(EltTy))
2146 return Error(TypeLoc, "invalid array element type");
2147 Result = ArrayType::get(EltTy, Size);
2152 //===----------------------------------------------------------------------===//
2153 // Function Semantic Analysis.
2154 //===----------------------------------------------------------------------===//
2156 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2158 : P(p), F(f), FunctionNumber(functionNumber) {
2160 // Insert unnamed arguments into the NumberedVals list.
2161 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2164 NumberedVals.push_back(AI);
2167 LLParser::PerFunctionState::~PerFunctionState() {
2168 // If there were any forward referenced non-basicblock values, delete them.
2169 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2170 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2171 if (!isa<BasicBlock>(I->second.first)) {
2172 I->second.first->replaceAllUsesWith(
2173 UndefValue::get(I->second.first->getType()));
2174 delete I->second.first;
2175 I->second.first = nullptr;
2178 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2179 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2180 if (!isa<BasicBlock>(I->second.first)) {
2181 I->second.first->replaceAllUsesWith(
2182 UndefValue::get(I->second.first->getType()));
2183 delete I->second.first;
2184 I->second.first = nullptr;
2188 bool LLParser::PerFunctionState::FinishFunction() {
2189 if (!ForwardRefVals.empty())
2190 return P.Error(ForwardRefVals.begin()->second.second,
2191 "use of undefined value '%" + ForwardRefVals.begin()->first +
2193 if (!ForwardRefValIDs.empty())
2194 return P.Error(ForwardRefValIDs.begin()->second.second,
2195 "use of undefined value '%" +
2196 Twine(ForwardRefValIDs.begin()->first) + "'");
2201 /// GetVal - Get a value with the specified name or ID, creating a
2202 /// forward reference record if needed. This can return null if the value
2203 /// exists but does not have the right type.
2204 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2205 Type *Ty, LocTy Loc) {
2206 // Look this name up in the normal function symbol table.
2207 Value *Val = F.getValueSymbolTable().lookup(Name);
2209 // If this is a forward reference for the value, see if we already created a
2210 // forward ref record.
2212 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2213 I = ForwardRefVals.find(Name);
2214 if (I != ForwardRefVals.end())
2215 Val = I->second.first;
2218 // If we have the value in the symbol table or fwd-ref table, return it.
2220 if (Val->getType() == Ty) return Val;
2221 if (Ty->isLabelTy())
2222 P.Error(Loc, "'%" + Name + "' is not a basic block");
2224 P.Error(Loc, "'%" + Name + "' defined with type '" +
2225 getTypeString(Val->getType()) + "'");
2229 // Don't make placeholders with invalid type.
2230 if (!Ty->isFirstClassType()) {
2231 P.Error(Loc, "invalid use of a non-first-class type");
2235 // Otherwise, create a new forward reference for this value and remember it.
2237 if (Ty->isLabelTy())
2238 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2240 FwdVal = new Argument(Ty, Name);
2242 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2246 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2248 // Look this name up in the normal function symbol table.
2249 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2251 // If this is a forward reference for the value, see if we already created a
2252 // forward ref record.
2254 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2255 I = ForwardRefValIDs.find(ID);
2256 if (I != ForwardRefValIDs.end())
2257 Val = I->second.first;
2260 // If we have the value in the symbol table or fwd-ref table, return it.
2262 if (Val->getType() == Ty) return Val;
2263 if (Ty->isLabelTy())
2264 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2266 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2267 getTypeString(Val->getType()) + "'");
2271 if (!Ty->isFirstClassType()) {
2272 P.Error(Loc, "invalid use of a non-first-class type");
2276 // Otherwise, create a new forward reference for this value and remember it.
2278 if (Ty->isLabelTy())
2279 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2281 FwdVal = new Argument(Ty);
2283 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2287 /// SetInstName - After an instruction is parsed and inserted into its
2288 /// basic block, this installs its name.
2289 bool LLParser::PerFunctionState::SetInstName(int NameID,
2290 const std::string &NameStr,
2291 LocTy NameLoc, Instruction *Inst) {
2292 // If this instruction has void type, it cannot have a name or ID specified.
2293 if (Inst->getType()->isVoidTy()) {
2294 if (NameID != -1 || !NameStr.empty())
2295 return P.Error(NameLoc, "instructions returning void cannot have a name");
2299 // If this was a numbered instruction, verify that the instruction is the
2300 // expected value and resolve any forward references.
2301 if (NameStr.empty()) {
2302 // If neither a name nor an ID was specified, just use the next ID.
2304 NameID = NumberedVals.size();
2306 if (unsigned(NameID) != NumberedVals.size())
2307 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2308 Twine(NumberedVals.size()) + "'");
2310 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2311 ForwardRefValIDs.find(NameID);
2312 if (FI != ForwardRefValIDs.end()) {
2313 if (FI->second.first->getType() != Inst->getType())
2314 return P.Error(NameLoc, "instruction forward referenced with type '" +
2315 getTypeString(FI->second.first->getType()) + "'");
2316 FI->second.first->replaceAllUsesWith(Inst);
2317 delete FI->second.first;
2318 ForwardRefValIDs.erase(FI);
2321 NumberedVals.push_back(Inst);
2325 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2326 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2327 FI = ForwardRefVals.find(NameStr);
2328 if (FI != ForwardRefVals.end()) {
2329 if (FI->second.first->getType() != Inst->getType())
2330 return P.Error(NameLoc, "instruction forward referenced with type '" +
2331 getTypeString(FI->second.first->getType()) + "'");
2332 FI->second.first->replaceAllUsesWith(Inst);
2333 delete FI->second.first;
2334 ForwardRefVals.erase(FI);
2337 // Set the name on the instruction.
2338 Inst->setName(NameStr);
2340 if (Inst->getName() != NameStr)
2341 return P.Error(NameLoc, "multiple definition of local value named '" +
2346 /// GetBB - Get a basic block with the specified name or ID, creating a
2347 /// forward reference record if needed.
2348 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2350 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2351 Type::getLabelTy(F.getContext()), Loc));
2354 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2355 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2356 Type::getLabelTy(F.getContext()), Loc));
2359 /// DefineBB - Define the specified basic block, which is either named or
2360 /// unnamed. If there is an error, this returns null otherwise it returns
2361 /// the block being defined.
2362 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2366 BB = GetBB(NumberedVals.size(), Loc);
2368 BB = GetBB(Name, Loc);
2369 if (!BB) return nullptr; // Already diagnosed error.
2371 // Move the block to the end of the function. Forward ref'd blocks are
2372 // inserted wherever they happen to be referenced.
2373 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2375 // Remove the block from forward ref sets.
2377 ForwardRefValIDs.erase(NumberedVals.size());
2378 NumberedVals.push_back(BB);
2380 // BB forward references are already in the function symbol table.
2381 ForwardRefVals.erase(Name);
2387 //===----------------------------------------------------------------------===//
2389 //===----------------------------------------------------------------------===//
2391 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2392 /// type implied. For example, if we parse "4" we don't know what integer type
2393 /// it has. The value will later be combined with its type and checked for
2394 /// sanity. PFS is used to convert function-local operands of metadata (since
2395 /// metadata operands are not just parsed here but also converted to values).
2396 /// PFS can be null when we are not parsing metadata values inside a function.
2397 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2398 ID.Loc = Lex.getLoc();
2399 switch (Lex.getKind()) {
2400 default: return TokError("expected value token");
2401 case lltok::GlobalID: // @42
2402 ID.UIntVal = Lex.getUIntVal();
2403 ID.Kind = ValID::t_GlobalID;
2405 case lltok::GlobalVar: // @foo
2406 ID.StrVal = Lex.getStrVal();
2407 ID.Kind = ValID::t_GlobalName;
2409 case lltok::LocalVarID: // %42
2410 ID.UIntVal = Lex.getUIntVal();
2411 ID.Kind = ValID::t_LocalID;
2413 case lltok::LocalVar: // %foo
2414 ID.StrVal = Lex.getStrVal();
2415 ID.Kind = ValID::t_LocalName;
2418 ID.APSIntVal = Lex.getAPSIntVal();
2419 ID.Kind = ValID::t_APSInt;
2421 case lltok::APFloat:
2422 ID.APFloatVal = Lex.getAPFloatVal();
2423 ID.Kind = ValID::t_APFloat;
2425 case lltok::kw_true:
2426 ID.ConstantVal = ConstantInt::getTrue(Context);
2427 ID.Kind = ValID::t_Constant;
2429 case lltok::kw_false:
2430 ID.ConstantVal = ConstantInt::getFalse(Context);
2431 ID.Kind = ValID::t_Constant;
2433 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2434 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2435 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2437 case lltok::lbrace: {
2438 // ValID ::= '{' ConstVector '}'
2440 SmallVector<Constant*, 16> Elts;
2441 if (ParseGlobalValueVector(Elts) ||
2442 ParseToken(lltok::rbrace, "expected end of struct constant"))
2445 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2446 ID.UIntVal = Elts.size();
2447 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2448 Elts.size() * sizeof(Elts[0]));
2449 ID.Kind = ValID::t_ConstantStruct;
2453 // ValID ::= '<' ConstVector '>' --> Vector.
2454 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2456 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2458 SmallVector<Constant*, 16> Elts;
2459 LocTy FirstEltLoc = Lex.getLoc();
2460 if (ParseGlobalValueVector(Elts) ||
2462 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2463 ParseToken(lltok::greater, "expected end of constant"))
2466 if (isPackedStruct) {
2467 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2468 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2469 Elts.size() * sizeof(Elts[0]));
2470 ID.UIntVal = Elts.size();
2471 ID.Kind = ValID::t_PackedConstantStruct;
2476 return Error(ID.Loc, "constant vector must not be empty");
2478 if (!Elts[0]->getType()->isIntegerTy() &&
2479 !Elts[0]->getType()->isFloatingPointTy() &&
2480 !Elts[0]->getType()->isPointerTy())
2481 return Error(FirstEltLoc,
2482 "vector elements must have integer, pointer or floating point type");
2484 // Verify that all the vector elements have the same type.
2485 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2486 if (Elts[i]->getType() != Elts[0]->getType())
2487 return Error(FirstEltLoc,
2488 "vector element #" + Twine(i) +
2489 " is not of type '" + getTypeString(Elts[0]->getType()));
2491 ID.ConstantVal = ConstantVector::get(Elts);
2492 ID.Kind = ValID::t_Constant;
2495 case lltok::lsquare: { // Array Constant
2497 SmallVector<Constant*, 16> Elts;
2498 LocTy FirstEltLoc = Lex.getLoc();
2499 if (ParseGlobalValueVector(Elts) ||
2500 ParseToken(lltok::rsquare, "expected end of array constant"))
2503 // Handle empty element.
2505 // Use undef instead of an array because it's inconvenient to determine
2506 // the element type at this point, there being no elements to examine.
2507 ID.Kind = ValID::t_EmptyArray;
2511 if (!Elts[0]->getType()->isFirstClassType())
2512 return Error(FirstEltLoc, "invalid array element type: " +
2513 getTypeString(Elts[0]->getType()));
2515 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2517 // Verify all elements are correct type!
2518 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2519 if (Elts[i]->getType() != Elts[0]->getType())
2520 return Error(FirstEltLoc,
2521 "array element #" + Twine(i) +
2522 " is not of type '" + getTypeString(Elts[0]->getType()));
2525 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2526 ID.Kind = ValID::t_Constant;
2529 case lltok::kw_c: // c "foo"
2531 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2533 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2534 ID.Kind = ValID::t_Constant;
2537 case lltok::kw_asm: {
2538 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2540 bool HasSideEffect, AlignStack, AsmDialect;
2542 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2543 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2544 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2545 ParseStringConstant(ID.StrVal) ||
2546 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2547 ParseToken(lltok::StringConstant, "expected constraint string"))
2549 ID.StrVal2 = Lex.getStrVal();
2550 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2551 (unsigned(AsmDialect)<<2);
2552 ID.Kind = ValID::t_InlineAsm;
2556 case lltok::kw_blockaddress: {
2557 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2562 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2564 ParseToken(lltok::comma, "expected comma in block address expression")||
2565 ParseValID(Label) ||
2566 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2569 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2570 return Error(Fn.Loc, "expected function name in blockaddress");
2571 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2572 return Error(Label.Loc, "expected basic block name in blockaddress");
2574 // Try to find the function (but skip it if it's forward-referenced).
2575 GlobalValue *GV = nullptr;
2576 if (Fn.Kind == ValID::t_GlobalID) {
2577 if (Fn.UIntVal < NumberedVals.size())
2578 GV = NumberedVals[Fn.UIntVal];
2579 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2580 GV = M->getNamedValue(Fn.StrVal);
2582 Function *F = nullptr;
2584 // Confirm that it's actually a function with a definition.
2585 if (!isa<Function>(GV))
2586 return Error(Fn.Loc, "expected function name in blockaddress");
2587 F = cast<Function>(GV);
2588 if (F->isDeclaration())
2589 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2593 // Make a global variable as a placeholder for this reference.
2594 GlobalValue *&FwdRef =
2595 ForwardRefBlockAddresses.insert(std::make_pair(
2597 std::map<ValID, GlobalValue *>()))
2598 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2601 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2602 GlobalValue::InternalLinkage, nullptr, "");
2603 ID.ConstantVal = FwdRef;
2604 ID.Kind = ValID::t_Constant;
2608 // We found the function; now find the basic block. Don't use PFS, since we
2609 // might be inside a constant expression.
2611 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2612 if (Label.Kind == ValID::t_LocalID)
2613 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2615 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2617 return Error(Label.Loc, "referenced value is not a basic block");
2619 if (Label.Kind == ValID::t_LocalID)
2620 return Error(Label.Loc, "cannot take address of numeric label after "
2621 "the function is defined");
2622 BB = dyn_cast_or_null<BasicBlock>(
2623 F->getValueSymbolTable().lookup(Label.StrVal));
2625 return Error(Label.Loc, "referenced value is not a basic block");
2628 ID.ConstantVal = BlockAddress::get(F, BB);
2629 ID.Kind = ValID::t_Constant;
2633 case lltok::kw_trunc:
2634 case lltok::kw_zext:
2635 case lltok::kw_sext:
2636 case lltok::kw_fptrunc:
2637 case lltok::kw_fpext:
2638 case lltok::kw_bitcast:
2639 case lltok::kw_addrspacecast:
2640 case lltok::kw_uitofp:
2641 case lltok::kw_sitofp:
2642 case lltok::kw_fptoui:
2643 case lltok::kw_fptosi:
2644 case lltok::kw_inttoptr:
2645 case lltok::kw_ptrtoint: {
2646 unsigned Opc = Lex.getUIntVal();
2647 Type *DestTy = nullptr;
2650 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2651 ParseGlobalTypeAndValue(SrcVal) ||
2652 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2653 ParseType(DestTy) ||
2654 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2656 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2657 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2658 getTypeString(SrcVal->getType()) + "' to '" +
2659 getTypeString(DestTy) + "'");
2660 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2662 ID.Kind = ValID::t_Constant;
2665 case lltok::kw_extractvalue: {
2668 SmallVector<unsigned, 4> Indices;
2669 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2670 ParseGlobalTypeAndValue(Val) ||
2671 ParseIndexList(Indices) ||
2672 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2675 if (!Val->getType()->isAggregateType())
2676 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2677 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2678 return Error(ID.Loc, "invalid indices for extractvalue");
2679 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2680 ID.Kind = ValID::t_Constant;
2683 case lltok::kw_insertvalue: {
2685 Constant *Val0, *Val1;
2686 SmallVector<unsigned, 4> Indices;
2687 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2688 ParseGlobalTypeAndValue(Val0) ||
2689 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2690 ParseGlobalTypeAndValue(Val1) ||
2691 ParseIndexList(Indices) ||
2692 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2694 if (!Val0->getType()->isAggregateType())
2695 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2697 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2699 return Error(ID.Loc, "invalid indices for insertvalue");
2700 if (IndexedType != Val1->getType())
2701 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2702 getTypeString(Val1->getType()) +
2703 "' instead of '" + getTypeString(IndexedType) +
2705 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2706 ID.Kind = ValID::t_Constant;
2709 case lltok::kw_icmp:
2710 case lltok::kw_fcmp: {
2711 unsigned PredVal, Opc = Lex.getUIntVal();
2712 Constant *Val0, *Val1;
2714 if (ParseCmpPredicate(PredVal, Opc) ||
2715 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2716 ParseGlobalTypeAndValue(Val0) ||
2717 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2718 ParseGlobalTypeAndValue(Val1) ||
2719 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2722 if (Val0->getType() != Val1->getType())
2723 return Error(ID.Loc, "compare operands must have the same type");
2725 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2727 if (Opc == Instruction::FCmp) {
2728 if (!Val0->getType()->isFPOrFPVectorTy())
2729 return Error(ID.Loc, "fcmp requires floating point operands");
2730 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2732 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2733 if (!Val0->getType()->isIntOrIntVectorTy() &&
2734 !Val0->getType()->getScalarType()->isPointerTy())
2735 return Error(ID.Loc, "icmp requires pointer or integer operands");
2736 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2738 ID.Kind = ValID::t_Constant;
2742 // Binary Operators.
2744 case lltok::kw_fadd:
2746 case lltok::kw_fsub:
2748 case lltok::kw_fmul:
2749 case lltok::kw_udiv:
2750 case lltok::kw_sdiv:
2751 case lltok::kw_fdiv:
2752 case lltok::kw_urem:
2753 case lltok::kw_srem:
2754 case lltok::kw_frem:
2756 case lltok::kw_lshr:
2757 case lltok::kw_ashr: {
2761 unsigned Opc = Lex.getUIntVal();
2762 Constant *Val0, *Val1;
2764 LocTy ModifierLoc = Lex.getLoc();
2765 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2766 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2767 if (EatIfPresent(lltok::kw_nuw))
2769 if (EatIfPresent(lltok::kw_nsw)) {
2771 if (EatIfPresent(lltok::kw_nuw))
2774 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2775 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2776 if (EatIfPresent(lltok::kw_exact))
2779 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2780 ParseGlobalTypeAndValue(Val0) ||
2781 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2782 ParseGlobalTypeAndValue(Val1) ||
2783 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2785 if (Val0->getType() != Val1->getType())
2786 return Error(ID.Loc, "operands of constexpr must have same type");
2787 if (!Val0->getType()->isIntOrIntVectorTy()) {
2789 return Error(ModifierLoc, "nuw only applies to integer operations");
2791 return Error(ModifierLoc, "nsw only applies to integer operations");
2793 // Check that the type is valid for the operator.
2795 case Instruction::Add:
2796 case Instruction::Sub:
2797 case Instruction::Mul:
2798 case Instruction::UDiv:
2799 case Instruction::SDiv:
2800 case Instruction::URem:
2801 case Instruction::SRem:
2802 case Instruction::Shl:
2803 case Instruction::AShr:
2804 case Instruction::LShr:
2805 if (!Val0->getType()->isIntOrIntVectorTy())
2806 return Error(ID.Loc, "constexpr requires integer operands");
2808 case Instruction::FAdd:
2809 case Instruction::FSub:
2810 case Instruction::FMul:
2811 case Instruction::FDiv:
2812 case Instruction::FRem:
2813 if (!Val0->getType()->isFPOrFPVectorTy())
2814 return Error(ID.Loc, "constexpr requires fp operands");
2816 default: llvm_unreachable("Unknown binary operator!");
2819 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2820 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2821 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2822 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2824 ID.Kind = ValID::t_Constant;
2828 // Logical Operations
2831 case lltok::kw_xor: {
2832 unsigned Opc = Lex.getUIntVal();
2833 Constant *Val0, *Val1;
2835 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2836 ParseGlobalTypeAndValue(Val0) ||
2837 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2838 ParseGlobalTypeAndValue(Val1) ||
2839 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2841 if (Val0->getType() != Val1->getType())
2842 return Error(ID.Loc, "operands of constexpr must have same type");
2843 if (!Val0->getType()->isIntOrIntVectorTy())
2844 return Error(ID.Loc,
2845 "constexpr requires integer or integer vector operands");
2846 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2847 ID.Kind = ValID::t_Constant;
2851 case lltok::kw_getelementptr:
2852 case lltok::kw_shufflevector:
2853 case lltok::kw_insertelement:
2854 case lltok::kw_extractelement:
2855 case lltok::kw_select: {
2856 unsigned Opc = Lex.getUIntVal();
2857 SmallVector<Constant*, 16> Elts;
2858 bool InBounds = false;
2862 if (Opc == Instruction::GetElementPtr)
2863 InBounds = EatIfPresent(lltok::kw_inbounds);
2865 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2868 LocTy ExplicitTypeLoc = Lex.getLoc();
2869 if (Opc == Instruction::GetElementPtr) {
2870 if (ParseType(Ty) ||
2871 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2875 if (ParseGlobalValueVector(Elts) ||
2876 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2879 if (Opc == Instruction::GetElementPtr) {
2880 if (Elts.size() == 0 ||
2881 !Elts[0]->getType()->getScalarType()->isPointerTy())
2882 return Error(ID.Loc, "base of getelementptr must be a pointer");
2884 Type *BaseType = Elts[0]->getType();
2885 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2886 if (Ty != BasePointerType->getElementType())
2889 "explicit pointee type doesn't match operand's pointee type");
2891 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2892 for (Constant *Val : Indices) {
2893 Type *ValTy = Val->getType();
2894 if (!ValTy->getScalarType()->isIntegerTy())
2895 return Error(ID.Loc, "getelementptr index must be an integer");
2896 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2897 return Error(ID.Loc, "getelementptr index type missmatch");
2898 if (ValTy->isVectorTy()) {
2899 unsigned ValNumEl = ValTy->getVectorNumElements();
2900 unsigned PtrNumEl = BaseType->getVectorNumElements();
2901 if (ValNumEl != PtrNumEl)
2904 "getelementptr vector index has a wrong number of elements");
2908 SmallPtrSet<Type*, 4> Visited;
2909 if (!Indices.empty() && !Ty->isSized(&Visited))
2910 return Error(ID.Loc, "base element of getelementptr must be sized");
2912 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2913 return Error(ID.Loc, "invalid getelementptr indices");
2915 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2916 } else if (Opc == Instruction::Select) {
2917 if (Elts.size() != 3)
2918 return Error(ID.Loc, "expected three operands to select");
2919 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2921 return Error(ID.Loc, Reason);
2922 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2923 } else if (Opc == Instruction::ShuffleVector) {
2924 if (Elts.size() != 3)
2925 return Error(ID.Loc, "expected three operands to shufflevector");
2926 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2927 return Error(ID.Loc, "invalid operands to shufflevector");
2929 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2930 } else if (Opc == Instruction::ExtractElement) {
2931 if (Elts.size() != 2)
2932 return Error(ID.Loc, "expected two operands to extractelement");
2933 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2934 return Error(ID.Loc, "invalid extractelement operands");
2935 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2937 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2938 if (Elts.size() != 3)
2939 return Error(ID.Loc, "expected three operands to insertelement");
2940 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2941 return Error(ID.Loc, "invalid insertelement operands");
2943 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2946 ID.Kind = ValID::t_Constant;
2955 /// ParseGlobalValue - Parse a global value with the specified type.
2956 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2960 bool Parsed = ParseValID(ID) ||
2961 ConvertValIDToValue(Ty, ID, V, nullptr);
2962 if (V && !(C = dyn_cast<Constant>(V)))
2963 return Error(ID.Loc, "global values must be constants");
2967 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2969 return ParseType(Ty) ||
2970 ParseGlobalValue(Ty, V);
2973 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2976 LocTy KwLoc = Lex.getLoc();
2977 if (!EatIfPresent(lltok::kw_comdat))
2980 if (EatIfPresent(lltok::lparen)) {
2981 if (Lex.getKind() != lltok::ComdatVar)
2982 return TokError("expected comdat variable");
2983 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2985 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2988 if (GlobalName.empty())
2989 return TokError("comdat cannot be unnamed");
2990 C = getComdat(GlobalName, KwLoc);
2996 /// ParseGlobalValueVector
2998 /// ::= TypeAndValue (',' TypeAndValue)*
2999 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3001 if (Lex.getKind() == lltok::rbrace ||
3002 Lex.getKind() == lltok::rsquare ||
3003 Lex.getKind() == lltok::greater ||
3004 Lex.getKind() == lltok::rparen)
3008 if (ParseGlobalTypeAndValue(C)) return true;
3011 while (EatIfPresent(lltok::comma)) {
3012 if (ParseGlobalTypeAndValue(C)) return true;
3019 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3020 SmallVector<Metadata *, 16> Elts;
3021 if (ParseMDNodeVector(Elts))
3024 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3031 /// ::= !DILocation(...)
3032 bool LLParser::ParseMDNode(MDNode *&N) {
3033 if (Lex.getKind() == lltok::MetadataVar)
3034 return ParseSpecializedMDNode(N);
3036 return ParseToken(lltok::exclaim, "expected '!' here") ||
3040 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3042 if (Lex.getKind() == lltok::lbrace)
3043 return ParseMDTuple(N);
3046 return ParseMDNodeID(N);
3051 /// Structure to represent an optional metadata field.
3052 template <class FieldTy> struct MDFieldImpl {
3053 typedef MDFieldImpl ImplTy;
3057 void assign(FieldTy Val) {
3059 this->Val = std::move(Val);
3062 explicit MDFieldImpl(FieldTy Default)
3063 : Val(std::move(Default)), Seen(false) {}
3066 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3069 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3070 : ImplTy(Default), Max(Max) {}
3072 struct LineField : public MDUnsignedField {
3073 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3075 struct ColumnField : public MDUnsignedField {
3076 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3078 struct DwarfTagField : public MDUnsignedField {
3079 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3080 DwarfTagField(dwarf::Tag DefaultTag)
3081 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3083 struct DwarfAttEncodingField : public MDUnsignedField {
3084 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3086 struct DwarfVirtualityField : public MDUnsignedField {
3087 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3089 struct DwarfLangField : public MDUnsignedField {
3090 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3093 struct DIFlagField : public MDUnsignedField {
3094 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3097 struct MDSignedField : public MDFieldImpl<int64_t> {
3101 MDSignedField(int64_t Default = 0)
3102 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3103 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3104 : ImplTy(Default), Min(Min), Max(Max) {}
3107 struct MDBoolField : public MDFieldImpl<bool> {
3108 MDBoolField(bool Default = false) : ImplTy(Default) {}
3110 struct MDField : public MDFieldImpl<Metadata *> {
3113 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3115 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3116 MDConstant() : ImplTy(nullptr) {}
3118 struct MDStringField : public MDFieldImpl<MDString *> {
3120 MDStringField(bool AllowEmpty = true)
3121 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3123 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3124 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3132 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3133 MDUnsignedField &Result) {
3134 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3135 return TokError("expected unsigned integer");
3137 auto &U = Lex.getAPSIntVal();
3138 if (U.ugt(Result.Max))
3139 return TokError("value for '" + Name + "' too large, limit is " +
3141 Result.assign(U.getZExtValue());
3142 assert(Result.Val <= Result.Max && "Expected value in range");
3148 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3149 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3152 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3153 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3157 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3158 if (Lex.getKind() == lltok::APSInt)
3159 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3161 if (Lex.getKind() != lltok::DwarfTag)
3162 return TokError("expected DWARF tag");
3164 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3165 if (Tag == dwarf::DW_TAG_invalid)
3166 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3167 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3175 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3176 DwarfVirtualityField &Result) {
3177 if (Lex.getKind() == lltok::APSInt)
3178 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3180 if (Lex.getKind() != lltok::DwarfVirtuality)
3181 return TokError("expected DWARF virtuality code");
3183 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3185 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3186 Lex.getStrVal() + "'");
3187 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3188 Result.assign(Virtuality);
3194 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3195 if (Lex.getKind() == lltok::APSInt)
3196 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3198 if (Lex.getKind() != lltok::DwarfLang)
3199 return TokError("expected DWARF language");
3201 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3203 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3205 assert(Lang <= Result.Max && "Expected valid DWARF language");
3206 Result.assign(Lang);
3212 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3213 DwarfAttEncodingField &Result) {
3214 if (Lex.getKind() == lltok::APSInt)
3215 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3217 if (Lex.getKind() != lltok::DwarfAttEncoding)
3218 return TokError("expected DWARF type attribute encoding");
3220 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3222 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3223 Lex.getStrVal() + "'");
3224 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3225 Result.assign(Encoding);
3232 /// ::= DIFlagVector
3233 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3235 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3236 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3238 // Parser for a single flag.
3239 auto parseFlag = [&](unsigned &Val) {
3240 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3241 return ParseUInt32(Val);
3243 if (Lex.getKind() != lltok::DIFlag)
3244 return TokError("expected debug info flag");
3246 Val = DINode::getFlag(Lex.getStrVal());
3248 return TokError(Twine("invalid debug info flag flag '") +
3249 Lex.getStrVal() + "'");
3254 // Parse the flags and combine them together.
3255 unsigned Combined = 0;
3261 } while (EatIfPresent(lltok::bar));
3263 Result.assign(Combined);
3268 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3269 MDSignedField &Result) {
3270 if (Lex.getKind() != lltok::APSInt)
3271 return TokError("expected signed integer");
3273 auto &S = Lex.getAPSIntVal();
3275 return TokError("value for '" + Name + "' too small, limit is " +
3278 return TokError("value for '" + Name + "' too large, limit is " +
3280 Result.assign(S.getExtValue());
3281 assert(Result.Val >= Result.Min && "Expected value in range");
3282 assert(Result.Val <= Result.Max && "Expected value in range");
3288 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3289 switch (Lex.getKind()) {
3291 return TokError("expected 'true' or 'false'");
3292 case lltok::kw_true:
3293 Result.assign(true);
3295 case lltok::kw_false:
3296 Result.assign(false);
3304 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3305 if (Lex.getKind() == lltok::kw_null) {
3306 if (!Result.AllowNull)
3307 return TokError("'" + Name + "' cannot be null");
3309 Result.assign(nullptr);
3314 if (ParseMetadata(MD, nullptr))
3322 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3324 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3327 Result.assign(cast<ConstantAsMetadata>(MD));
3332 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3333 LocTy ValueLoc = Lex.getLoc();
3335 if (ParseStringConstant(S))
3338 if (!Result.AllowEmpty && S.empty())
3339 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3341 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3346 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3347 SmallVector<Metadata *, 4> MDs;
3348 if (ParseMDNodeVector(MDs))
3351 Result.assign(std::move(MDs));
3355 } // end namespace llvm
3357 template <class ParserTy>
3358 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3360 if (Lex.getKind() != lltok::LabelStr)
3361 return TokError("expected field label here");
3365 } while (EatIfPresent(lltok::comma));
3370 template <class ParserTy>
3371 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3372 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3375 if (ParseToken(lltok::lparen, "expected '(' here"))
3377 if (Lex.getKind() != lltok::rparen)
3378 if (ParseMDFieldsImplBody(parseField))
3381 ClosingLoc = Lex.getLoc();
3382 return ParseToken(lltok::rparen, "expected ')' here");
3385 template <class FieldTy>
3386 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3388 return TokError("field '" + Name + "' cannot be specified more than once");
3390 LocTy Loc = Lex.getLoc();
3392 return ParseMDField(Loc, Name, Result);
3395 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3396 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3398 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3399 if (Lex.getStrVal() == #CLASS) \
3400 return Parse##CLASS(N, IsDistinct);
3401 #include "llvm/IR/Metadata.def"
3403 return TokError("expected metadata type");
3406 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3407 #define NOP_FIELD(NAME, TYPE, INIT)
3408 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3410 return Error(ClosingLoc, "missing required field '" #NAME "'");
3411 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3412 if (Lex.getStrVal() == #NAME) \
3413 return ParseMDField(#NAME, NAME);
3414 #define PARSE_MD_FIELDS() \
3415 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3418 if (ParseMDFieldsImpl([&]() -> bool { \
3419 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3420 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3423 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3425 #define GET_OR_DISTINCT(CLASS, ARGS) \
3426 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3428 /// ParseDILocationFields:
3429 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3430 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3431 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3432 OPTIONAL(line, LineField, ); \
3433 OPTIONAL(column, ColumnField, ); \
3434 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3435 OPTIONAL(inlinedAt, MDField, );
3437 #undef VISIT_MD_FIELDS
3439 Result = GET_OR_DISTINCT(
3440 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3444 /// ParseGenericDINode:
3445 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3446 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3447 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3448 REQUIRED(tag, DwarfTagField, ); \
3449 OPTIONAL(header, MDStringField, ); \
3450 OPTIONAL(operands, MDFieldList, );
3452 #undef VISIT_MD_FIELDS
3454 Result = GET_OR_DISTINCT(GenericDINode,
3455 (Context, tag.Val, header.Val, operands.Val));
3459 /// ParseDISubrange:
3460 /// ::= !DISubrange(count: 30, lowerBound: 2)
3461 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3462 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3463 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3464 OPTIONAL(lowerBound, MDSignedField, );
3466 #undef VISIT_MD_FIELDS
3468 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3472 /// ParseDIEnumerator:
3473 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3474 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3475 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3476 REQUIRED(name, MDStringField, ); \
3477 REQUIRED(value, MDSignedField, );
3479 #undef VISIT_MD_FIELDS
3481 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3485 /// ParseDIBasicType:
3486 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3487 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3488 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3489 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3490 OPTIONAL(name, MDStringField, ); \
3491 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3492 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3493 OPTIONAL(encoding, DwarfAttEncodingField, );
3495 #undef VISIT_MD_FIELDS
3497 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3498 align.Val, encoding.Val));
3502 /// ParseDIDerivedType:
3503 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3504 /// line: 7, scope: !1, baseType: !2, size: 32,
3505 /// align: 32, offset: 0, flags: 0, extraData: !3)
3506 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3507 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3508 REQUIRED(tag, DwarfTagField, ); \
3509 OPTIONAL(name, MDStringField, ); \
3510 OPTIONAL(file, MDField, ); \
3511 OPTIONAL(line, LineField, ); \
3512 OPTIONAL(scope, MDField, ); \
3513 REQUIRED(baseType, MDField, ); \
3514 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3515 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3516 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3517 OPTIONAL(flags, DIFlagField, ); \
3518 OPTIONAL(extraData, MDField, );
3520 #undef VISIT_MD_FIELDS
3522 Result = GET_OR_DISTINCT(DIDerivedType,
3523 (Context, tag.Val, name.Val, file.Val, line.Val,
3524 scope.Val, baseType.Val, size.Val, align.Val,
3525 offset.Val, flags.Val, extraData.Val));
3529 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3530 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3531 REQUIRED(tag, DwarfTagField, ); \
3532 OPTIONAL(name, MDStringField, ); \
3533 OPTIONAL(file, MDField, ); \
3534 OPTIONAL(line, LineField, ); \
3535 OPTIONAL(scope, MDField, ); \
3536 OPTIONAL(baseType, MDField, ); \
3537 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3538 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3539 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3540 OPTIONAL(flags, DIFlagField, ); \
3541 OPTIONAL(elements, MDField, ); \
3542 OPTIONAL(runtimeLang, DwarfLangField, ); \
3543 OPTIONAL(vtableHolder, MDField, ); \
3544 OPTIONAL(templateParams, MDField, ); \
3545 OPTIONAL(identifier, MDStringField, );
3547 #undef VISIT_MD_FIELDS
3549 Result = GET_OR_DISTINCT(
3551 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3552 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3553 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3557 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3558 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3559 OPTIONAL(flags, DIFlagField, ); \
3560 REQUIRED(types, MDField, );
3562 #undef VISIT_MD_FIELDS
3564 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3568 /// ParseDIFileType:
3569 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3570 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3571 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3572 REQUIRED(filename, MDStringField, ); \
3573 REQUIRED(directory, MDStringField, );
3575 #undef VISIT_MD_FIELDS
3577 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3581 /// ParseDICompileUnit:
3582 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3583 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3584 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3585 /// enums: !1, retainedTypes: !2, subprograms: !3,
3586 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3587 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3588 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3589 REQUIRED(language, DwarfLangField, ); \
3590 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3591 OPTIONAL(producer, MDStringField, ); \
3592 OPTIONAL(isOptimized, MDBoolField, ); \
3593 OPTIONAL(flags, MDStringField, ); \
3594 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3595 OPTIONAL(splitDebugFilename, MDStringField, ); \
3596 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3597 OPTIONAL(enums, MDField, ); \
3598 OPTIONAL(retainedTypes, MDField, ); \
3599 OPTIONAL(subprograms, MDField, ); \
3600 OPTIONAL(globals, MDField, ); \
3601 OPTIONAL(imports, MDField, ); \
3602 OPTIONAL(dwoId, MDUnsignedField, );
3604 #undef VISIT_MD_FIELDS
3606 Result = GET_OR_DISTINCT(DICompileUnit,
3607 (Context, language.Val, file.Val, producer.Val,
3608 isOptimized.Val, flags.Val, runtimeVersion.Val,
3609 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3610 retainedTypes.Val, subprograms.Val, globals.Val,
3611 imports.Val, dwoId.Val));
3615 /// ParseDISubprogram:
3616 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3617 /// file: !1, line: 7, type: !2, isLocal: false,
3618 /// isDefinition: true, scopeLine: 8, containingType: !3,
3619 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3620 /// virtualIndex: 10, flags: 11,
3621 /// isOptimized: false, function: void ()* @_Z3foov,
3622 /// templateParams: !4, declaration: !5, variables: !6)
3623 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3624 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3625 OPTIONAL(scope, MDField, ); \
3626 OPTIONAL(name, MDStringField, ); \
3627 OPTIONAL(linkageName, MDStringField, ); \
3628 OPTIONAL(file, MDField, ); \
3629 OPTIONAL(line, LineField, ); \
3630 OPTIONAL(type, MDField, ); \
3631 OPTIONAL(isLocal, MDBoolField, ); \
3632 OPTIONAL(isDefinition, MDBoolField, (true)); \
3633 OPTIONAL(scopeLine, LineField, ); \
3634 OPTIONAL(containingType, MDField, ); \
3635 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3636 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3637 OPTIONAL(flags, DIFlagField, ); \
3638 OPTIONAL(isOptimized, MDBoolField, ); \
3639 OPTIONAL(function, MDConstant, ); \
3640 OPTIONAL(templateParams, MDField, ); \
3641 OPTIONAL(declaration, MDField, ); \
3642 OPTIONAL(variables, MDField, );
3644 #undef VISIT_MD_FIELDS
3646 Result = GET_OR_DISTINCT(
3647 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3648 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3649 scopeLine.Val, containingType.Val, virtuality.Val,
3650 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3651 templateParams.Val, declaration.Val, variables.Val));
3655 /// ParseDILexicalBlock:
3656 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3657 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3658 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3659 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3660 OPTIONAL(file, MDField, ); \
3661 OPTIONAL(line, LineField, ); \
3662 OPTIONAL(column, ColumnField, );
3664 #undef VISIT_MD_FIELDS
3666 Result = GET_OR_DISTINCT(
3667 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3671 /// ParseDILexicalBlockFile:
3672 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3673 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3674 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3675 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3676 OPTIONAL(file, MDField, ); \
3677 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3679 #undef VISIT_MD_FIELDS
3681 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3682 (Context, scope.Val, file.Val, discriminator.Val));
3686 /// ParseDINamespace:
3687 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3688 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3689 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3690 REQUIRED(scope, MDField, ); \
3691 OPTIONAL(file, MDField, ); \
3692 OPTIONAL(name, MDStringField, ); \
3693 OPTIONAL(line, LineField, );
3695 #undef VISIT_MD_FIELDS
3697 Result = GET_OR_DISTINCT(DINamespace,
3698 (Context, scope.Val, file.Val, name.Val, line.Val));
3703 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3704 /// includePath: "/usr/include", isysroot: "/")
3705 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3706 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3707 REQUIRED(scope, MDField, ); \
3708 REQUIRED(name, MDStringField, ); \
3709 OPTIONAL(configMacros, MDStringField, ); \
3710 OPTIONAL(includePath, MDStringField, ); \
3711 OPTIONAL(isysroot, MDStringField, );
3713 #undef VISIT_MD_FIELDS
3715 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3716 configMacros.Val, includePath.Val, isysroot.Val));
3720 /// ParseDITemplateTypeParameter:
3721 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3722 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3723 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3724 OPTIONAL(name, MDStringField, ); \
3725 REQUIRED(type, MDField, );
3727 #undef VISIT_MD_FIELDS
3730 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3734 /// ParseDITemplateValueParameter:
3735 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3736 /// name: "V", type: !1, value: i32 7)
3737 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3738 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3739 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3740 OPTIONAL(name, MDStringField, ); \
3741 OPTIONAL(type, MDField, ); \
3742 REQUIRED(value, MDField, );
3744 #undef VISIT_MD_FIELDS
3746 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3747 (Context, tag.Val, name.Val, type.Val, value.Val));
3751 /// ParseDIGlobalVariable:
3752 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3753 /// file: !1, line: 7, type: !2, isLocal: false,
3754 /// isDefinition: true, variable: i32* @foo,
3755 /// declaration: !3)
3756 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3757 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3758 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3759 OPTIONAL(scope, MDField, ); \
3760 OPTIONAL(linkageName, MDStringField, ); \
3761 OPTIONAL(file, MDField, ); \
3762 OPTIONAL(line, LineField, ); \
3763 OPTIONAL(type, MDField, ); \
3764 OPTIONAL(isLocal, MDBoolField, ); \
3765 OPTIONAL(isDefinition, MDBoolField, (true)); \
3766 OPTIONAL(variable, MDConstant, ); \
3767 OPTIONAL(declaration, MDField, );
3769 #undef VISIT_MD_FIELDS
3771 Result = GET_OR_DISTINCT(DIGlobalVariable,
3772 (Context, scope.Val, name.Val, linkageName.Val,
3773 file.Val, line.Val, type.Val, isLocal.Val,
3774 isDefinition.Val, variable.Val, declaration.Val));
3778 /// ParseDILocalVariable:
3779 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
3780 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3781 /// ::= !DILocalVariable(scope: !0, name: "foo",
3782 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3783 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3784 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3785 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3786 OPTIONAL(name, MDStringField, ); \
3787 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3788 OPTIONAL(file, MDField, ); \
3789 OPTIONAL(line, LineField, ); \
3790 OPTIONAL(type, MDField, ); \
3791 OPTIONAL(flags, DIFlagField, );
3793 #undef VISIT_MD_FIELDS
3795 Result = GET_OR_DISTINCT(DILocalVariable,
3796 (Context, scope.Val, name.Val, file.Val, line.Val,
3797 type.Val, arg.Val, flags.Val));
3801 /// ParseDIExpression:
3802 /// ::= !DIExpression(0, 7, -1)
3803 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3804 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3807 if (ParseToken(lltok::lparen, "expected '(' here"))
3810 SmallVector<uint64_t, 8> Elements;
3811 if (Lex.getKind() != lltok::rparen)
3813 if (Lex.getKind() == lltok::DwarfOp) {
3814 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3816 Elements.push_back(Op);
3819 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3822 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3823 return TokError("expected unsigned integer");
3825 auto &U = Lex.getAPSIntVal();
3826 if (U.ugt(UINT64_MAX))
3827 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3828 Elements.push_back(U.getZExtValue());
3830 } while (EatIfPresent(lltok::comma));
3832 if (ParseToken(lltok::rparen, "expected ')' here"))
3835 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3839 /// ParseDIObjCProperty:
3840 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3841 /// getter: "getFoo", attributes: 7, type: !2)
3842 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3843 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3844 OPTIONAL(name, MDStringField, ); \
3845 OPTIONAL(file, MDField, ); \
3846 OPTIONAL(line, LineField, ); \
3847 OPTIONAL(setter, MDStringField, ); \
3848 OPTIONAL(getter, MDStringField, ); \
3849 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3850 OPTIONAL(type, MDField, );
3852 #undef VISIT_MD_FIELDS
3854 Result = GET_OR_DISTINCT(DIObjCProperty,
3855 (Context, name.Val, file.Val, line.Val, setter.Val,
3856 getter.Val, attributes.Val, type.Val));
3860 /// ParseDIImportedEntity:
3861 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3862 /// line: 7, name: "foo")
3863 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3864 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3865 REQUIRED(tag, DwarfTagField, ); \
3866 REQUIRED(scope, MDField, ); \
3867 OPTIONAL(entity, MDField, ); \
3868 OPTIONAL(line, LineField, ); \
3869 OPTIONAL(name, MDStringField, );
3871 #undef VISIT_MD_FIELDS
3873 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3874 entity.Val, line.Val, name.Val));
3878 #undef PARSE_MD_FIELD
3880 #undef REQUIRE_FIELD
3881 #undef DECLARE_FIELD
3883 /// ParseMetadataAsValue
3884 /// ::= metadata i32 %local
3885 /// ::= metadata i32 @global
3886 /// ::= metadata i32 7
3888 /// ::= metadata !{...}
3889 /// ::= metadata !"string"
3890 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3891 // Note: the type 'metadata' has already been parsed.
3893 if (ParseMetadata(MD, &PFS))
3896 V = MetadataAsValue::get(Context, MD);
3900 /// ParseValueAsMetadata
3904 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3905 PerFunctionState *PFS) {
3908 if (ParseType(Ty, TypeMsg, Loc))
3910 if (Ty->isMetadataTy())
3911 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3914 if (ParseValue(Ty, V, PFS))
3917 MD = ValueAsMetadata::get(V);
3928 /// ::= !DILocation(...)
3929 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3930 if (Lex.getKind() == lltok::MetadataVar) {
3932 if (ParseSpecializedMDNode(N))
3940 if (Lex.getKind() != lltok::exclaim)
3941 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3944 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3948 // ::= '!' STRINGCONSTANT
3949 if (Lex.getKind() == lltok::StringConstant) {
3951 if (ParseMDString(S))
3961 if (ParseMDNodeTail(N))
3968 //===----------------------------------------------------------------------===//
3969 // Function Parsing.
3970 //===----------------------------------------------------------------------===//
3972 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3973 PerFunctionState *PFS) {
3974 if (Ty->isFunctionTy())
3975 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3978 case ValID::t_LocalID:
3979 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3980 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3981 return V == nullptr;
3982 case ValID::t_LocalName:
3983 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3984 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3985 return V == nullptr;
3986 case ValID::t_InlineAsm: {
3988 if (!InlineAsm::Verify(ID.FTy, ID.StrVal2))
3989 return Error(ID.Loc, "invalid type for inline asm constraint string");
3990 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
3991 (ID.UIntVal >> 1) & 1,
3992 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
3995 case ValID::t_GlobalName:
3996 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3997 return V == nullptr;
3998 case ValID::t_GlobalID:
3999 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4000 return V == nullptr;
4001 case ValID::t_APSInt:
4002 if (!Ty->isIntegerTy())
4003 return Error(ID.Loc, "integer constant must have integer type");
4004 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4005 V = ConstantInt::get(Context, ID.APSIntVal);
4007 case ValID::t_APFloat:
4008 if (!Ty->isFloatingPointTy() ||
4009 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4010 return Error(ID.Loc, "floating point constant invalid for type");
4012 // The lexer has no type info, so builds all half, float, and double FP
4013 // constants as double. Fix this here. Long double does not need this.
4014 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4017 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4019 else if (Ty->isFloatTy())
4020 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4023 V = ConstantFP::get(Context, ID.APFloatVal);
4025 if (V->getType() != Ty)
4026 return Error(ID.Loc, "floating point constant does not have type '" +
4027 getTypeString(Ty) + "'");
4031 if (!Ty->isPointerTy())
4032 return Error(ID.Loc, "null must be a pointer type");
4033 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4035 case ValID::t_Undef:
4036 // FIXME: LabelTy should not be a first-class type.
4037 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4038 return Error(ID.Loc, "invalid type for undef constant");
4039 V = UndefValue::get(Ty);
4041 case ValID::t_EmptyArray:
4042 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4043 return Error(ID.Loc, "invalid empty array initializer");
4044 V = UndefValue::get(Ty);
4047 // FIXME: LabelTy should not be a first-class type.
4048 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4049 return Error(ID.Loc, "invalid type for null constant");
4050 V = Constant::getNullValue(Ty);
4052 case ValID::t_Constant:
4053 if (ID.ConstantVal->getType() != Ty)
4054 return Error(ID.Loc, "constant expression type mismatch");
4058 case ValID::t_ConstantStruct:
4059 case ValID::t_PackedConstantStruct:
4060 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4061 if (ST->getNumElements() != ID.UIntVal)
4062 return Error(ID.Loc,
4063 "initializer with struct type has wrong # elements");
4064 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4065 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4067 // Verify that the elements are compatible with the structtype.
4068 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4069 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4070 return Error(ID.Loc, "element " + Twine(i) +
4071 " of struct initializer doesn't match struct element type");
4073 V = ConstantStruct::get(
4074 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4076 return Error(ID.Loc, "constant expression type mismatch");
4079 llvm_unreachable("Invalid ValID");
4082 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4085 auto Loc = Lex.getLoc();
4086 if (ParseValID(ID, /*PFS=*/nullptr))
4089 case ValID::t_APSInt:
4090 case ValID::t_APFloat:
4091 case ValID::t_Constant:
4092 case ValID::t_ConstantStruct:
4093 case ValID::t_PackedConstantStruct: {
4095 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4097 assert(isa<Constant>(V) && "Expected a constant value");
4098 C = cast<Constant>(V);
4102 return Error(Loc, "expected a constant value");
4106 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4109 return ParseValID(ID, PFS) ||
4110 ConvertValIDToValue(Ty, ID, V, PFS);
4113 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4115 return ParseType(Ty) ||
4116 ParseValue(Ty, V, PFS);
4119 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4120 PerFunctionState &PFS) {
4123 if (ParseTypeAndValue(V, PFS)) return true;
4124 if (!isa<BasicBlock>(V))
4125 return Error(Loc, "expected a basic block");
4126 BB = cast<BasicBlock>(V);
4132 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4133 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4134 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4135 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4136 // Parse the linkage.
4137 LocTy LinkageLoc = Lex.getLoc();
4140 unsigned Visibility;
4141 unsigned DLLStorageClass;
4142 AttrBuilder RetAttrs;
4144 Type *RetType = nullptr;
4145 LocTy RetTypeLoc = Lex.getLoc();
4146 if (ParseOptionalLinkage(Linkage) ||
4147 ParseOptionalVisibility(Visibility) ||
4148 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4149 ParseOptionalCallingConv(CC) ||
4150 ParseOptionalReturnAttrs(RetAttrs) ||
4151 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4154 // Verify that the linkage is ok.
4155 switch ((GlobalValue::LinkageTypes)Linkage) {
4156 case GlobalValue::ExternalLinkage:
4157 break; // always ok.
4158 case GlobalValue::ExternalWeakLinkage:
4160 return Error(LinkageLoc, "invalid linkage for function definition");
4162 case GlobalValue::PrivateLinkage:
4163 case GlobalValue::InternalLinkage:
4164 case GlobalValue::AvailableExternallyLinkage:
4165 case GlobalValue::LinkOnceAnyLinkage:
4166 case GlobalValue::LinkOnceODRLinkage:
4167 case GlobalValue::WeakAnyLinkage:
4168 case GlobalValue::WeakODRLinkage:
4170 return Error(LinkageLoc, "invalid linkage for function declaration");
4172 case GlobalValue::AppendingLinkage:
4173 case GlobalValue::CommonLinkage:
4174 return Error(LinkageLoc, "invalid function linkage type");
4177 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4178 return Error(LinkageLoc,
4179 "symbol with local linkage must have default visibility");
4181 if (!FunctionType::isValidReturnType(RetType))
4182 return Error(RetTypeLoc, "invalid function return type");
4184 LocTy NameLoc = Lex.getLoc();
4186 std::string FunctionName;
4187 if (Lex.getKind() == lltok::GlobalVar) {
4188 FunctionName = Lex.getStrVal();
4189 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4190 unsigned NameID = Lex.getUIntVal();
4192 if (NameID != NumberedVals.size())
4193 return TokError("function expected to be numbered '%" +
4194 Twine(NumberedVals.size()) + "'");
4196 return TokError("expected function name");
4201 if (Lex.getKind() != lltok::lparen)
4202 return TokError("expected '(' in function argument list");
4204 SmallVector<ArgInfo, 8> ArgList;
4206 AttrBuilder FuncAttrs;
4207 std::vector<unsigned> FwdRefAttrGrps;
4209 std::string Section;
4213 LocTy UnnamedAddrLoc;
4214 Constant *Prefix = nullptr;
4215 Constant *Prologue = nullptr;
4216 Constant *PersonalityFn = nullptr;
4219 if (ParseArgumentList(ArgList, isVarArg) ||
4220 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4222 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4224 (EatIfPresent(lltok::kw_section) &&
4225 ParseStringConstant(Section)) ||
4226 parseOptionalComdat(FunctionName, C) ||
4227 ParseOptionalAlignment(Alignment) ||
4228 (EatIfPresent(lltok::kw_gc) &&
4229 ParseStringConstant(GC)) ||
4230 (EatIfPresent(lltok::kw_prefix) &&
4231 ParseGlobalTypeAndValue(Prefix)) ||
4232 (EatIfPresent(lltok::kw_prologue) &&
4233 ParseGlobalTypeAndValue(Prologue)) ||
4234 (EatIfPresent(lltok::kw_personality) &&
4235 ParseGlobalTypeAndValue(PersonalityFn)))
4238 if (FuncAttrs.contains(Attribute::Builtin))
4239 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4241 // If the alignment was parsed as an attribute, move to the alignment field.
4242 if (FuncAttrs.hasAlignmentAttr()) {
4243 Alignment = FuncAttrs.getAlignment();
4244 FuncAttrs.removeAttribute(Attribute::Alignment);
4247 // Okay, if we got here, the function is syntactically valid. Convert types
4248 // and do semantic checks.
4249 std::vector<Type*> ParamTypeList;
4250 SmallVector<AttributeSet, 8> Attrs;
4252 if (RetAttrs.hasAttributes())
4253 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4254 AttributeSet::ReturnIndex,
4257 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4258 ParamTypeList.push_back(ArgList[i].Ty);
4259 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4260 AttrBuilder B(ArgList[i].Attrs, i + 1);
4261 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4265 if (FuncAttrs.hasAttributes())
4266 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4267 AttributeSet::FunctionIndex,
4270 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4272 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4273 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4276 FunctionType::get(RetType, ParamTypeList, isVarArg);
4277 PointerType *PFT = PointerType::getUnqual(FT);
4280 if (!FunctionName.empty()) {
4281 // If this was a definition of a forward reference, remove the definition
4282 // from the forward reference table and fill in the forward ref.
4283 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4284 ForwardRefVals.find(FunctionName);
4285 if (FRVI != ForwardRefVals.end()) {
4286 Fn = M->getFunction(FunctionName);
4288 return Error(FRVI->second.second, "invalid forward reference to "
4289 "function as global value!");
4290 if (Fn->getType() != PFT)
4291 return Error(FRVI->second.second, "invalid forward reference to "
4292 "function '" + FunctionName + "' with wrong type!");
4294 ForwardRefVals.erase(FRVI);
4295 } else if ((Fn = M->getFunction(FunctionName))) {
4296 // Reject redefinitions.
4297 return Error(NameLoc, "invalid redefinition of function '" +
4298 FunctionName + "'");
4299 } else if (M->getNamedValue(FunctionName)) {
4300 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4304 // If this is a definition of a forward referenced function, make sure the
4306 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4307 = ForwardRefValIDs.find(NumberedVals.size());
4308 if (I != ForwardRefValIDs.end()) {
4309 Fn = cast<Function>(I->second.first);
4310 if (Fn->getType() != PFT)
4311 return Error(NameLoc, "type of definition and forward reference of '@" +
4312 Twine(NumberedVals.size()) + "' disagree");
4313 ForwardRefValIDs.erase(I);
4318 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4319 else // Move the forward-reference to the correct spot in the module.
4320 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4322 if (FunctionName.empty())
4323 NumberedVals.push_back(Fn);
4325 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4326 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4327 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4328 Fn->setCallingConv(CC);
4329 Fn->setAttributes(PAL);
4330 Fn->setUnnamedAddr(UnnamedAddr);
4331 Fn->setAlignment(Alignment);
4332 Fn->setSection(Section);
4334 Fn->setPersonalityFn(PersonalityFn);
4335 if (!GC.empty()) Fn->setGC(GC.c_str());
4336 Fn->setPrefixData(Prefix);
4337 Fn->setPrologueData(Prologue);
4338 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4340 // Add all of the arguments we parsed to the function.
4341 Function::arg_iterator ArgIt = Fn->arg_begin();
4342 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4343 // If the argument has a name, insert it into the argument symbol table.
4344 if (ArgList[i].Name.empty()) continue;
4346 // Set the name, if it conflicted, it will be auto-renamed.
4347 ArgIt->setName(ArgList[i].Name);
4349 if (ArgIt->getName() != ArgList[i].Name)
4350 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4351 ArgList[i].Name + "'");
4357 // Check the declaration has no block address forward references.
4359 if (FunctionName.empty()) {
4360 ID.Kind = ValID::t_GlobalID;
4361 ID.UIntVal = NumberedVals.size() - 1;
4363 ID.Kind = ValID::t_GlobalName;
4364 ID.StrVal = FunctionName;
4366 auto Blocks = ForwardRefBlockAddresses.find(ID);
4367 if (Blocks != ForwardRefBlockAddresses.end())
4368 return Error(Blocks->first.Loc,
4369 "cannot take blockaddress inside a declaration");
4373 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4375 if (FunctionNumber == -1) {
4376 ID.Kind = ValID::t_GlobalName;
4377 ID.StrVal = F.getName();
4379 ID.Kind = ValID::t_GlobalID;
4380 ID.UIntVal = FunctionNumber;
4383 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4384 if (Blocks == P.ForwardRefBlockAddresses.end())
4387 for (const auto &I : Blocks->second) {
4388 const ValID &BBID = I.first;
4389 GlobalValue *GV = I.second;
4391 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4392 "Expected local id or name");
4394 if (BBID.Kind == ValID::t_LocalName)
4395 BB = GetBB(BBID.StrVal, BBID.Loc);
4397 BB = GetBB(BBID.UIntVal, BBID.Loc);
4399 return P.Error(BBID.Loc, "referenced value is not a basic block");
4401 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4402 GV->eraseFromParent();
4405 P.ForwardRefBlockAddresses.erase(Blocks);
4409 /// ParseFunctionBody
4410 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4411 bool LLParser::ParseFunctionBody(Function &Fn) {
4412 if (Lex.getKind() != lltok::lbrace)
4413 return TokError("expected '{' in function body");
4414 Lex.Lex(); // eat the {.
4416 int FunctionNumber = -1;
4417 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4419 PerFunctionState PFS(*this, Fn, FunctionNumber);
4421 // Resolve block addresses and allow basic blocks to be forward-declared
4422 // within this function.
4423 if (PFS.resolveForwardRefBlockAddresses())
4425 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4427 // We need at least one basic block.
4428 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4429 return TokError("function body requires at least one basic block");
4431 while (Lex.getKind() != lltok::rbrace &&
4432 Lex.getKind() != lltok::kw_uselistorder)
4433 if (ParseBasicBlock(PFS)) return true;
4435 while (Lex.getKind() != lltok::rbrace)
4436 if (ParseUseListOrder(&PFS))
4442 // Verify function is ok.
4443 return PFS.FinishFunction();
4447 /// ::= LabelStr? Instruction*
4448 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4449 // If this basic block starts out with a name, remember it.
4451 LocTy NameLoc = Lex.getLoc();
4452 if (Lex.getKind() == lltok::LabelStr) {
4453 Name = Lex.getStrVal();
4457 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4459 return Error(NameLoc,
4460 "unable to create block named '" + Name + "'");
4462 std::string NameStr;
4464 // Parse the instructions in this block until we get a terminator.
4467 // This instruction may have three possibilities for a name: a) none
4468 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4469 LocTy NameLoc = Lex.getLoc();
4473 if (Lex.getKind() == lltok::LocalVarID) {
4474 NameID = Lex.getUIntVal();
4476 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4478 } else if (Lex.getKind() == lltok::LocalVar) {
4479 NameStr = Lex.getStrVal();
4481 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4485 switch (ParseInstruction(Inst, BB, PFS)) {
4486 default: llvm_unreachable("Unknown ParseInstruction result!");
4487 case InstError: return true;
4489 BB->getInstList().push_back(Inst);
4491 // With a normal result, we check to see if the instruction is followed by
4492 // a comma and metadata.
4493 if (EatIfPresent(lltok::comma))
4494 if (ParseInstructionMetadata(*Inst))
4497 case InstExtraComma:
4498 BB->getInstList().push_back(Inst);
4500 // If the instruction parser ate an extra comma at the end of it, it
4501 // *must* be followed by metadata.
4502 if (ParseInstructionMetadata(*Inst))
4507 // Set the name on the instruction.
4508 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4509 } while (!isa<TerminatorInst>(Inst));
4514 //===----------------------------------------------------------------------===//
4515 // Instruction Parsing.
4516 //===----------------------------------------------------------------------===//
4518 /// ParseInstruction - Parse one of the many different instructions.
4520 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4521 PerFunctionState &PFS) {
4522 lltok::Kind Token = Lex.getKind();
4523 if (Token == lltok::Eof)
4524 return TokError("found end of file when expecting more instructions");
4525 LocTy Loc = Lex.getLoc();
4526 unsigned KeywordVal = Lex.getUIntVal();
4527 Lex.Lex(); // Eat the keyword.
4530 default: return Error(Loc, "expected instruction opcode");
4531 // Terminator Instructions.
4532 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4533 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4534 case lltok::kw_br: return ParseBr(Inst, PFS);
4535 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4536 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4537 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4538 case lltok::kw_resume: return ParseResume(Inst, PFS);
4539 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4540 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4541 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4542 case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4543 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4544 case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
4545 // Binary Operators.
4549 case lltok::kw_shl: {
4550 bool NUW = EatIfPresent(lltok::kw_nuw);
4551 bool NSW = EatIfPresent(lltok::kw_nsw);
4552 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4554 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4556 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4557 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4560 case lltok::kw_fadd:
4561 case lltok::kw_fsub:
4562 case lltok::kw_fmul:
4563 case lltok::kw_fdiv:
4564 case lltok::kw_frem: {
4565 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4566 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4570 Inst->setFastMathFlags(FMF);
4574 case lltok::kw_sdiv:
4575 case lltok::kw_udiv:
4576 case lltok::kw_lshr:
4577 case lltok::kw_ashr: {
4578 bool Exact = EatIfPresent(lltok::kw_exact);
4580 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4581 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4585 case lltok::kw_urem:
4586 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4589 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4590 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4591 case lltok::kw_fcmp: {
4592 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4593 int Res = ParseCompare(Inst, PFS, KeywordVal);
4597 Inst->setFastMathFlags(FMF);
4602 case lltok::kw_trunc:
4603 case lltok::kw_zext:
4604 case lltok::kw_sext:
4605 case lltok::kw_fptrunc:
4606 case lltok::kw_fpext:
4607 case lltok::kw_bitcast:
4608 case lltok::kw_addrspacecast:
4609 case lltok::kw_uitofp:
4610 case lltok::kw_sitofp:
4611 case lltok::kw_fptoui:
4612 case lltok::kw_fptosi:
4613 case lltok::kw_inttoptr:
4614 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4616 case lltok::kw_select: return ParseSelect(Inst, PFS);
4617 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4618 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4619 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4620 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4621 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4622 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4624 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4625 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4626 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4628 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4629 case lltok::kw_load: return ParseLoad(Inst, PFS);
4630 case lltok::kw_store: return ParseStore(Inst, PFS);
4631 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4632 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4633 case lltok::kw_fence: return ParseFence(Inst, PFS);
4634 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4635 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4636 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4640 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4641 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4642 if (Opc == Instruction::FCmp) {
4643 switch (Lex.getKind()) {
4644 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4645 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4646 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4647 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4648 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4649 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4650 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4651 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4652 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4653 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4654 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4655 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4656 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4657 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4658 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4659 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4660 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4663 switch (Lex.getKind()) {
4664 default: return TokError("expected icmp predicate (e.g. 'eq')");
4665 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4666 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4667 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4668 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4669 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4670 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4671 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4672 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4673 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4674 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4681 //===----------------------------------------------------------------------===//
4682 // Terminator Instructions.
4683 //===----------------------------------------------------------------------===//
4685 /// ParseRet - Parse a return instruction.
4686 /// ::= 'ret' void (',' !dbg, !1)*
4687 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4688 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4689 PerFunctionState &PFS) {
4690 SMLoc TypeLoc = Lex.getLoc();
4692 if (ParseType(Ty, true /*void allowed*/)) return true;
4694 Type *ResType = PFS.getFunction().getReturnType();
4696 if (Ty->isVoidTy()) {
4697 if (!ResType->isVoidTy())
4698 return Error(TypeLoc, "value doesn't match function result type '" +
4699 getTypeString(ResType) + "'");
4701 Inst = ReturnInst::Create(Context);
4706 if (ParseValue(Ty, RV, PFS)) return true;
4708 if (ResType != RV->getType())
4709 return Error(TypeLoc, "value doesn't match function result type '" +
4710 getTypeString(ResType) + "'");
4712 Inst = ReturnInst::Create(Context, RV);
4718 /// ::= 'br' TypeAndValue
4719 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4720 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4723 BasicBlock *Op1, *Op2;
4724 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4726 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4727 Inst = BranchInst::Create(BB);
4731 if (Op0->getType() != Type::getInt1Ty(Context))
4732 return Error(Loc, "branch condition must have 'i1' type");
4734 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4735 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4736 ParseToken(lltok::comma, "expected ',' after true destination") ||
4737 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4740 Inst = BranchInst::Create(Op1, Op2, Op0);
4746 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4748 /// ::= (TypeAndValue ',' TypeAndValue)*
4749 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4750 LocTy CondLoc, BBLoc;
4752 BasicBlock *DefaultBB;
4753 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4754 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4755 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4756 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4759 if (!Cond->getType()->isIntegerTy())
4760 return Error(CondLoc, "switch condition must have integer type");
4762 // Parse the jump table pairs.
4763 SmallPtrSet<Value*, 32> SeenCases;
4764 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4765 while (Lex.getKind() != lltok::rsquare) {
4769 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4770 ParseToken(lltok::comma, "expected ',' after case value") ||
4771 ParseTypeAndBasicBlock(DestBB, PFS))
4774 if (!SeenCases.insert(Constant).second)
4775 return Error(CondLoc, "duplicate case value in switch");
4776 if (!isa<ConstantInt>(Constant))
4777 return Error(CondLoc, "case value is not a constant integer");
4779 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4782 Lex.Lex(); // Eat the ']'.
4784 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4785 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4786 SI->addCase(Table[i].first, Table[i].second);
4793 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4794 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4797 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4798 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4799 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4802 if (!Address->getType()->isPointerTy())
4803 return Error(AddrLoc, "indirectbr address must have pointer type");
4805 // Parse the destination list.
4806 SmallVector<BasicBlock*, 16> DestList;
4808 if (Lex.getKind() != lltok::rsquare) {
4810 if (ParseTypeAndBasicBlock(DestBB, PFS))
4812 DestList.push_back(DestBB);
4814 while (EatIfPresent(lltok::comma)) {
4815 if (ParseTypeAndBasicBlock(DestBB, PFS))
4817 DestList.push_back(DestBB);
4821 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4824 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4825 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4826 IBI->addDestination(DestList[i]);
4833 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4834 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4835 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4836 LocTy CallLoc = Lex.getLoc();
4837 AttrBuilder RetAttrs, FnAttrs;
4838 std::vector<unsigned> FwdRefAttrGrps;
4841 Type *RetType = nullptr;
4844 SmallVector<ParamInfo, 16> ArgList;
4846 BasicBlock *NormalBB, *UnwindBB;
4847 if (ParseOptionalCallingConv(CC) ||
4848 ParseOptionalReturnAttrs(RetAttrs) ||
4849 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4850 ParseValID(CalleeID) ||
4851 ParseParameterList(ArgList, PFS) ||
4852 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4854 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4855 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4856 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4857 ParseTypeAndBasicBlock(UnwindBB, PFS))
4860 // If RetType is a non-function pointer type, then this is the short syntax
4861 // for the call, which means that RetType is just the return type. Infer the
4862 // rest of the function argument types from the arguments that are present.
4863 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4865 // Pull out the types of all of the arguments...
4866 std::vector<Type*> ParamTypes;
4867 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4868 ParamTypes.push_back(ArgList[i].V->getType());
4870 if (!FunctionType::isValidReturnType(RetType))
4871 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4873 Ty = FunctionType::get(RetType, ParamTypes, false);
4878 // Look up the callee.
4880 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4883 // Set up the Attribute for the function.
4884 SmallVector<AttributeSet, 8> Attrs;
4885 if (RetAttrs.hasAttributes())
4886 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4887 AttributeSet::ReturnIndex,
4890 SmallVector<Value*, 8> Args;
4892 // Loop through FunctionType's arguments and ensure they are specified
4893 // correctly. Also, gather any parameter attributes.
4894 FunctionType::param_iterator I = Ty->param_begin();
4895 FunctionType::param_iterator E = Ty->param_end();
4896 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4897 Type *ExpectedTy = nullptr;
4900 } else if (!Ty->isVarArg()) {
4901 return Error(ArgList[i].Loc, "too many arguments specified");
4904 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4905 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4906 getTypeString(ExpectedTy) + "'");
4907 Args.push_back(ArgList[i].V);
4908 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4909 AttrBuilder B(ArgList[i].Attrs, i + 1);
4910 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4915 return Error(CallLoc, "not enough parameters specified for call");
4917 if (FnAttrs.hasAttributes()) {
4918 if (FnAttrs.hasAlignmentAttr())
4919 return Error(CallLoc, "invoke instructions may not have an alignment");
4921 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4922 AttributeSet::FunctionIndex,
4926 // Finish off the Attribute and check them
4927 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4929 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4930 II->setCallingConv(CC);
4931 II->setAttributes(PAL);
4932 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4938 /// ::= 'resume' TypeAndValue
4939 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4940 Value *Exn; LocTy ExnLoc;
4941 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4944 ResumeInst *RI = ResumeInst::Create(Exn);
4949 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
4950 PerFunctionState &PFS) {
4951 if (ParseToken(lltok::lsquare, "expected '[' in cleanuppad"))
4954 while (Lex.getKind() != lltok::rsquare) {
4955 // If this isn't the first argument, we need a comma.
4956 if (!Args.empty() &&
4957 ParseToken(lltok::comma, "expected ',' in argument list"))
4960 // Parse the argument.
4962 Type *ArgTy = nullptr;
4963 if (ParseType(ArgTy, ArgLoc))
4967 if (ArgTy->isMetadataTy()) {
4968 if (ParseMetadataAsValue(V, PFS))
4971 if (ParseValue(ArgTy, V, PFS))
4977 Lex.Lex(); // Lex the ']'.
4982 /// ::= 'cleanupret' ('void' | TypeAndValue) unwind ('to' 'caller' | TypeAndValue)
4983 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
4984 Type *RetTy = nullptr;
4985 Value *RetVal = nullptr;
4986 if (ParseType(RetTy, /*AllowVoid=*/true))
4989 if (!RetTy->isVoidTy())
4990 if (ParseValue(RetTy, RetVal, PFS))
4993 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
4996 BasicBlock *UnwindBB = nullptr;
4997 if (Lex.getKind() == lltok::kw_to) {
4999 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5002 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5007 Inst = CleanupReturnInst::Create(Context, RetVal, UnwindBB);
5012 /// ::= 'catchret' TypeAndValue
5013 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5015 if (ParseTypeAndBasicBlock(BB, PFS))
5018 Inst = CatchReturnInst::Create(BB);
5023 /// ::= 'catchpad' Type ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5024 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5025 Type *RetType = nullptr;
5027 SmallVector<Value *, 8> Args;
5028 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5031 BasicBlock *NormalBB, *UnwindBB;
5032 if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5033 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5034 ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5035 ParseTypeAndBasicBlock(UnwindBB, PFS))
5038 Inst = CatchPadInst::Create(RetType, NormalBB, UnwindBB, Args);
5042 /// ParseTerminatePad
5043 /// ::= 'terminatepad' ParamList 'to' TypeAndValue
5044 bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5045 SmallVector<Value *, 8> Args;
5046 if (ParseExceptionArgs(Args, PFS))
5049 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5052 BasicBlock *UnwindBB = nullptr;
5053 if (Lex.getKind() == lltok::kw_to) {
5055 if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5058 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5063 Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5068 /// ::= 'cleanuppad' ParamList
5069 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5070 Type *RetType = nullptr;
5072 SmallVector<Value *, 8> Args;
5073 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5076 Inst = CleanupPadInst::Create(RetType, Args);
5080 /// ParseCatchEndPad
5081 /// ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5082 bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5083 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5086 BasicBlock *UnwindBB = nullptr;
5087 if (Lex.getKind() == lltok::kw_to) {
5089 if (Lex.getKind() == lltok::kw_caller) {
5095 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5100 Inst = CatchEndPadInst::Create(Context, UnwindBB);
5104 //===----------------------------------------------------------------------===//
5105 // Binary Operators.
5106 //===----------------------------------------------------------------------===//
5109 /// ::= ArithmeticOps TypeAndValue ',' Value
5111 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5112 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5113 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5114 unsigned Opc, unsigned OperandType) {
5115 LocTy Loc; Value *LHS, *RHS;
5116 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5117 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5118 ParseValue(LHS->getType(), RHS, PFS))
5122 switch (OperandType) {
5123 default: llvm_unreachable("Unknown operand type!");
5124 case 0: // int or FP.
5125 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5126 LHS->getType()->isFPOrFPVectorTy();
5128 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5129 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5133 return Error(Loc, "invalid operand type for instruction");
5135 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5140 /// ::= ArithmeticOps TypeAndValue ',' Value {
5141 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5143 LocTy Loc; Value *LHS, *RHS;
5144 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5145 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5146 ParseValue(LHS->getType(), RHS, PFS))
5149 if (!LHS->getType()->isIntOrIntVectorTy())
5150 return Error(Loc,"instruction requires integer or integer vector operands");
5152 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5158 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5159 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5160 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5162 // Parse the integer/fp comparison predicate.
5166 if (ParseCmpPredicate(Pred, Opc) ||
5167 ParseTypeAndValue(LHS, Loc, PFS) ||
5168 ParseToken(lltok::comma, "expected ',' after compare value") ||
5169 ParseValue(LHS->getType(), RHS, PFS))
5172 if (Opc == Instruction::FCmp) {
5173 if (!LHS->getType()->isFPOrFPVectorTy())
5174 return Error(Loc, "fcmp requires floating point operands");
5175 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5177 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5178 if (!LHS->getType()->isIntOrIntVectorTy() &&
5179 !LHS->getType()->getScalarType()->isPointerTy())
5180 return Error(Loc, "icmp requires integer operands");
5181 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5186 //===----------------------------------------------------------------------===//
5187 // Other Instructions.
5188 //===----------------------------------------------------------------------===//
5192 /// ::= CastOpc TypeAndValue 'to' Type
5193 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5197 Type *DestTy = nullptr;
5198 if (ParseTypeAndValue(Op, Loc, PFS) ||
5199 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5203 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5204 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5205 return Error(Loc, "invalid cast opcode for cast from '" +
5206 getTypeString(Op->getType()) + "' to '" +
5207 getTypeString(DestTy) + "'");
5209 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5214 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5215 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5217 Value *Op0, *Op1, *Op2;
5218 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5219 ParseToken(lltok::comma, "expected ',' after select condition") ||
5220 ParseTypeAndValue(Op1, PFS) ||
5221 ParseToken(lltok::comma, "expected ',' after select value") ||
5222 ParseTypeAndValue(Op2, PFS))
5225 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5226 return Error(Loc, Reason);
5228 Inst = SelectInst::Create(Op0, Op1, Op2);
5233 /// ::= 'va_arg' TypeAndValue ',' Type
5234 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5236 Type *EltTy = nullptr;
5238 if (ParseTypeAndValue(Op, PFS) ||
5239 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5240 ParseType(EltTy, TypeLoc))
5243 if (!EltTy->isFirstClassType())
5244 return Error(TypeLoc, "va_arg requires operand with first class type");
5246 Inst = new VAArgInst(Op, EltTy);
5250 /// ParseExtractElement
5251 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5252 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5255 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5256 ParseToken(lltok::comma, "expected ',' after extract value") ||
5257 ParseTypeAndValue(Op1, PFS))
5260 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5261 return Error(Loc, "invalid extractelement operands");
5263 Inst = ExtractElementInst::Create(Op0, Op1);
5267 /// ParseInsertElement
5268 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5269 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5271 Value *Op0, *Op1, *Op2;
5272 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5273 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5274 ParseTypeAndValue(Op1, PFS) ||
5275 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5276 ParseTypeAndValue(Op2, PFS))
5279 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5280 return Error(Loc, "invalid insertelement operands");
5282 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5286 /// ParseShuffleVector
5287 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5288 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5290 Value *Op0, *Op1, *Op2;
5291 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5292 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5293 ParseTypeAndValue(Op1, PFS) ||
5294 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5295 ParseTypeAndValue(Op2, PFS))
5298 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5299 return Error(Loc, "invalid shufflevector operands");
5301 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5306 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5307 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5308 Type *Ty = nullptr; LocTy TypeLoc;
5311 if (ParseType(Ty, TypeLoc) ||
5312 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5313 ParseValue(Ty, Op0, PFS) ||
5314 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5315 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5316 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5319 bool AteExtraComma = false;
5320 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5322 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5324 if (!EatIfPresent(lltok::comma))
5327 if (Lex.getKind() == lltok::MetadataVar) {
5328 AteExtraComma = true;
5332 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5333 ParseValue(Ty, Op0, PFS) ||
5334 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5335 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5336 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5340 if (!Ty->isFirstClassType())
5341 return Error(TypeLoc, "phi node must have first class type");
5343 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5344 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5345 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5347 return AteExtraComma ? InstExtraComma : InstNormal;
5351 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5353 /// ::= 'catch' TypeAndValue
5355 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5356 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5357 Type *Ty = nullptr; LocTy TyLoc;
5359 if (ParseType(Ty, TyLoc))
5362 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5363 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5365 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5366 LandingPadInst::ClauseType CT;
5367 if (EatIfPresent(lltok::kw_catch))
5368 CT = LandingPadInst::Catch;
5369 else if (EatIfPresent(lltok::kw_filter))
5370 CT = LandingPadInst::Filter;
5372 return TokError("expected 'catch' or 'filter' clause type");
5376 if (ParseTypeAndValue(V, VLoc, PFS))
5379 // A 'catch' type expects a non-array constant. A filter clause expects an
5381 if (CT == LandingPadInst::Catch) {
5382 if (isa<ArrayType>(V->getType()))
5383 Error(VLoc, "'catch' clause has an invalid type");
5385 if (!isa<ArrayType>(V->getType()))
5386 Error(VLoc, "'filter' clause has an invalid type");
5389 Constant *CV = dyn_cast<Constant>(V);
5391 return Error(VLoc, "clause argument must be a constant");
5395 Inst = LP.release();
5400 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5401 /// ParameterList OptionalAttrs
5402 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5403 /// ParameterList OptionalAttrs
5404 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5405 /// ParameterList OptionalAttrs
5406 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5407 CallInst::TailCallKind TCK) {
5408 AttrBuilder RetAttrs, FnAttrs;
5409 std::vector<unsigned> FwdRefAttrGrps;
5412 Type *RetType = nullptr;
5415 SmallVector<ParamInfo, 16> ArgList;
5416 LocTy CallLoc = Lex.getLoc();
5418 if ((TCK != CallInst::TCK_None &&
5419 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5420 ParseOptionalCallingConv(CC) ||
5421 ParseOptionalReturnAttrs(RetAttrs) ||
5422 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5423 ParseValID(CalleeID) ||
5424 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5425 PFS.getFunction().isVarArg()) ||
5426 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5430 // If RetType is a non-function pointer type, then this is the short syntax
5431 // for the call, which means that RetType is just the return type. Infer the
5432 // rest of the function argument types from the arguments that are present.
5433 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5435 // Pull out the types of all of the arguments...
5436 std::vector<Type*> ParamTypes;
5437 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5438 ParamTypes.push_back(ArgList[i].V->getType());
5440 if (!FunctionType::isValidReturnType(RetType))
5441 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5443 Ty = FunctionType::get(RetType, ParamTypes, false);
5448 // Look up the callee.
5450 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5453 // Set up the Attribute for the function.
5454 SmallVector<AttributeSet, 8> Attrs;
5455 if (RetAttrs.hasAttributes())
5456 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5457 AttributeSet::ReturnIndex,
5460 SmallVector<Value*, 8> Args;
5462 // Loop through FunctionType's arguments and ensure they are specified
5463 // correctly. Also, gather any parameter attributes.
5464 FunctionType::param_iterator I = Ty->param_begin();
5465 FunctionType::param_iterator E = Ty->param_end();
5466 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5467 Type *ExpectedTy = nullptr;
5470 } else if (!Ty->isVarArg()) {
5471 return Error(ArgList[i].Loc, "too many arguments specified");
5474 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5475 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5476 getTypeString(ExpectedTy) + "'");
5477 Args.push_back(ArgList[i].V);
5478 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5479 AttrBuilder B(ArgList[i].Attrs, i + 1);
5480 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5485 return Error(CallLoc, "not enough parameters specified for call");
5487 if (FnAttrs.hasAttributes()) {
5488 if (FnAttrs.hasAlignmentAttr())
5489 return Error(CallLoc, "call instructions may not have an alignment");
5491 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5492 AttributeSet::FunctionIndex,
5496 // Finish off the Attribute and check them
5497 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5499 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5500 CI->setTailCallKind(TCK);
5501 CI->setCallingConv(CC);
5502 CI->setAttributes(PAL);
5503 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5508 //===----------------------------------------------------------------------===//
5509 // Memory Instructions.
5510 //===----------------------------------------------------------------------===//
5513 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5514 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5515 Value *Size = nullptr;
5516 LocTy SizeLoc, TyLoc;
5517 unsigned Alignment = 0;
5520 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5522 if (ParseType(Ty, TyLoc)) return true;
5524 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5525 return Error(TyLoc, "invalid type for alloca");
5527 bool AteExtraComma = false;
5528 if (EatIfPresent(lltok::comma)) {
5529 if (Lex.getKind() == lltok::kw_align) {
5530 if (ParseOptionalAlignment(Alignment)) return true;
5531 } else if (Lex.getKind() == lltok::MetadataVar) {
5532 AteExtraComma = true;
5534 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5535 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5540 if (Size && !Size->getType()->isIntegerTy())
5541 return Error(SizeLoc, "element count must have integer type");
5543 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5544 AI->setUsedWithInAlloca(IsInAlloca);
5546 return AteExtraComma ? InstExtraComma : InstNormal;
5550 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5551 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5552 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5553 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5554 Value *Val; LocTy Loc;
5555 unsigned Alignment = 0;
5556 bool AteExtraComma = false;
5557 bool isAtomic = false;
5558 AtomicOrdering Ordering = NotAtomic;
5559 SynchronizationScope Scope = CrossThread;
5561 if (Lex.getKind() == lltok::kw_atomic) {
5566 bool isVolatile = false;
5567 if (Lex.getKind() == lltok::kw_volatile) {
5573 LocTy ExplicitTypeLoc = Lex.getLoc();
5574 if (ParseType(Ty) ||
5575 ParseToken(lltok::comma, "expected comma after load's type") ||
5576 ParseTypeAndValue(Val, Loc, PFS) ||
5577 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5578 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5581 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5582 return Error(Loc, "load operand must be a pointer to a first class type");
5583 if (isAtomic && !Alignment)
5584 return Error(Loc, "atomic load must have explicit non-zero alignment");
5585 if (Ordering == Release || Ordering == AcquireRelease)
5586 return Error(Loc, "atomic load cannot use Release ordering");
5588 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5589 return Error(ExplicitTypeLoc,
5590 "explicit pointee type doesn't match operand's pointee type");
5592 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5593 return AteExtraComma ? InstExtraComma : InstNormal;
5598 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5599 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5600 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5601 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5602 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5603 unsigned Alignment = 0;
5604 bool AteExtraComma = false;
5605 bool isAtomic = false;
5606 AtomicOrdering Ordering = NotAtomic;
5607 SynchronizationScope Scope = CrossThread;
5609 if (Lex.getKind() == lltok::kw_atomic) {
5614 bool isVolatile = false;
5615 if (Lex.getKind() == lltok::kw_volatile) {
5620 if (ParseTypeAndValue(Val, Loc, PFS) ||
5621 ParseToken(lltok::comma, "expected ',' after store operand") ||
5622 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5623 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5624 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5627 if (!Ptr->getType()->isPointerTy())
5628 return Error(PtrLoc, "store operand must be a pointer");
5629 if (!Val->getType()->isFirstClassType())
5630 return Error(Loc, "store operand must be a first class value");
5631 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5632 return Error(Loc, "stored value and pointer type do not match");
5633 if (isAtomic && !Alignment)
5634 return Error(Loc, "atomic store must have explicit non-zero alignment");
5635 if (Ordering == Acquire || Ordering == AcquireRelease)
5636 return Error(Loc, "atomic store cannot use Acquire ordering");
5638 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5639 return AteExtraComma ? InstExtraComma : InstNormal;
5643 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5644 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5645 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5646 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5647 bool AteExtraComma = false;
5648 AtomicOrdering SuccessOrdering = NotAtomic;
5649 AtomicOrdering FailureOrdering = NotAtomic;
5650 SynchronizationScope Scope = CrossThread;
5651 bool isVolatile = false;
5652 bool isWeak = false;
5654 if (EatIfPresent(lltok::kw_weak))
5657 if (EatIfPresent(lltok::kw_volatile))
5660 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5661 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5662 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5663 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5664 ParseTypeAndValue(New, NewLoc, PFS) ||
5665 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5666 ParseOrdering(FailureOrdering))
5669 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5670 return TokError("cmpxchg cannot be unordered");
5671 if (SuccessOrdering < FailureOrdering)
5672 return TokError("cmpxchg must be at least as ordered on success as failure");
5673 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5674 return TokError("cmpxchg failure ordering cannot include release semantics");
5675 if (!Ptr->getType()->isPointerTy())
5676 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5677 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5678 return Error(CmpLoc, "compare value and pointer type do not match");
5679 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5680 return Error(NewLoc, "new value and pointer type do not match");
5681 if (!New->getType()->isIntegerTy())
5682 return Error(NewLoc, "cmpxchg operand must be an integer");
5683 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5684 if (Size < 8 || (Size & (Size - 1)))
5685 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5688 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5689 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5690 CXI->setVolatile(isVolatile);
5691 CXI->setWeak(isWeak);
5693 return AteExtraComma ? InstExtraComma : InstNormal;
5697 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5698 /// 'singlethread'? AtomicOrdering
5699 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5700 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5701 bool AteExtraComma = false;
5702 AtomicOrdering Ordering = NotAtomic;
5703 SynchronizationScope Scope = CrossThread;
5704 bool isVolatile = false;
5705 AtomicRMWInst::BinOp Operation;
5707 if (EatIfPresent(lltok::kw_volatile))
5710 switch (Lex.getKind()) {
5711 default: return TokError("expected binary operation in atomicrmw");
5712 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5713 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5714 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5715 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5716 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5717 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5718 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5719 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5720 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5721 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5722 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5724 Lex.Lex(); // Eat the operation.
5726 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5727 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5728 ParseTypeAndValue(Val, ValLoc, PFS) ||
5729 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5732 if (Ordering == Unordered)
5733 return TokError("atomicrmw cannot be unordered");
5734 if (!Ptr->getType()->isPointerTy())
5735 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5736 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5737 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5738 if (!Val->getType()->isIntegerTy())
5739 return Error(ValLoc, "atomicrmw operand must be an integer");
5740 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5741 if (Size < 8 || (Size & (Size - 1)))
5742 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5745 AtomicRMWInst *RMWI =
5746 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5747 RMWI->setVolatile(isVolatile);
5749 return AteExtraComma ? InstExtraComma : InstNormal;
5753 /// ::= 'fence' 'singlethread'? AtomicOrdering
5754 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5755 AtomicOrdering Ordering = NotAtomic;
5756 SynchronizationScope Scope = CrossThread;
5757 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5760 if (Ordering == Unordered)
5761 return TokError("fence cannot be unordered");
5762 if (Ordering == Monotonic)
5763 return TokError("fence cannot be monotonic");
5765 Inst = new FenceInst(Context, Ordering, Scope);
5769 /// ParseGetElementPtr
5770 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5771 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5772 Value *Ptr = nullptr;
5773 Value *Val = nullptr;
5776 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5779 LocTy ExplicitTypeLoc = Lex.getLoc();
5780 if (ParseType(Ty) ||
5781 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5782 ParseTypeAndValue(Ptr, Loc, PFS))
5785 Type *BaseType = Ptr->getType();
5786 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5787 if (!BasePointerType)
5788 return Error(Loc, "base of getelementptr must be a pointer");
5790 if (Ty != BasePointerType->getElementType())
5791 return Error(ExplicitTypeLoc,
5792 "explicit pointee type doesn't match operand's pointee type");
5794 SmallVector<Value*, 16> Indices;
5795 bool AteExtraComma = false;
5796 // GEP returns a vector of pointers if at least one of parameters is a vector.
5797 // All vector parameters should have the same vector width.
5798 unsigned GEPWidth = BaseType->isVectorTy() ?
5799 BaseType->getVectorNumElements() : 0;
5801 while (EatIfPresent(lltok::comma)) {
5802 if (Lex.getKind() == lltok::MetadataVar) {
5803 AteExtraComma = true;
5806 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5807 if (!Val->getType()->getScalarType()->isIntegerTy())
5808 return Error(EltLoc, "getelementptr index must be an integer");
5810 if (Val->getType()->isVectorTy()) {
5811 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5812 if (GEPWidth && GEPWidth != ValNumEl)
5813 return Error(EltLoc,
5814 "getelementptr vector index has a wrong number of elements");
5815 GEPWidth = ValNumEl;
5817 Indices.push_back(Val);
5820 SmallPtrSet<Type*, 4> Visited;
5821 if (!Indices.empty() && !Ty->isSized(&Visited))
5822 return Error(Loc, "base element of getelementptr must be sized");
5824 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5825 return Error(Loc, "invalid getelementptr indices");
5826 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5828 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5829 return AteExtraComma ? InstExtraComma : InstNormal;
5832 /// ParseExtractValue
5833 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5834 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5835 Value *Val; LocTy Loc;
5836 SmallVector<unsigned, 4> Indices;
5838 if (ParseTypeAndValue(Val, Loc, PFS) ||
5839 ParseIndexList(Indices, AteExtraComma))
5842 if (!Val->getType()->isAggregateType())
5843 return Error(Loc, "extractvalue operand must be aggregate type");
5845 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5846 return Error(Loc, "invalid indices for extractvalue");
5847 Inst = ExtractValueInst::Create(Val, Indices);
5848 return AteExtraComma ? InstExtraComma : InstNormal;
5851 /// ParseInsertValue
5852 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5853 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5854 Value *Val0, *Val1; LocTy Loc0, Loc1;
5855 SmallVector<unsigned, 4> Indices;
5857 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5858 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5859 ParseTypeAndValue(Val1, Loc1, PFS) ||
5860 ParseIndexList(Indices, AteExtraComma))
5863 if (!Val0->getType()->isAggregateType())
5864 return Error(Loc0, "insertvalue operand must be aggregate type");
5866 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5868 return Error(Loc0, "invalid indices for insertvalue");
5869 if (IndexedType != Val1->getType())
5870 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5871 getTypeString(Val1->getType()) + "' instead of '" +
5872 getTypeString(IndexedType) + "'");
5873 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5874 return AteExtraComma ? InstExtraComma : InstNormal;
5877 //===----------------------------------------------------------------------===//
5878 // Embedded metadata.
5879 //===----------------------------------------------------------------------===//
5881 /// ParseMDNodeVector
5882 /// ::= { Element (',' Element)* }
5884 /// ::= 'null' | TypeAndValue
5885 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5886 if (ParseToken(lltok::lbrace, "expected '{' here"))
5889 // Check for an empty list.
5890 if (EatIfPresent(lltok::rbrace))
5894 // Null is a special case since it is typeless.
5895 if (EatIfPresent(lltok::kw_null)) {
5896 Elts.push_back(nullptr);
5901 if (ParseMetadata(MD, nullptr))
5904 } while (EatIfPresent(lltok::comma));
5906 return ParseToken(lltok::rbrace, "expected end of metadata node");
5909 //===----------------------------------------------------------------------===//
5910 // Use-list order directives.
5911 //===----------------------------------------------------------------------===//
5912 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5915 return Error(Loc, "value has no uses");
5917 unsigned NumUses = 0;
5918 SmallDenseMap<const Use *, unsigned, 16> Order;
5919 for (const Use &U : V->uses()) {
5920 if (++NumUses > Indexes.size())
5922 Order[&U] = Indexes[NumUses - 1];
5925 return Error(Loc, "value only has one use");
5926 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5927 return Error(Loc, "wrong number of indexes, expected " +
5928 Twine(std::distance(V->use_begin(), V->use_end())));
5930 V->sortUseList([&](const Use &L, const Use &R) {
5931 return Order.lookup(&L) < Order.lookup(&R);
5936 /// ParseUseListOrderIndexes
5937 /// ::= '{' uint32 (',' uint32)+ '}'
5938 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5939 SMLoc Loc = Lex.getLoc();
5940 if (ParseToken(lltok::lbrace, "expected '{' here"))
5942 if (Lex.getKind() == lltok::rbrace)
5943 return Lex.Error("expected non-empty list of uselistorder indexes");
5945 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5946 // indexes should be distinct numbers in the range [0, size-1], and should
5948 unsigned Offset = 0;
5950 bool IsOrdered = true;
5951 assert(Indexes.empty() && "Expected empty order vector");
5954 if (ParseUInt32(Index))
5957 // Update consistency checks.
5958 Offset += Index - Indexes.size();
5959 Max = std::max(Max, Index);
5960 IsOrdered &= Index == Indexes.size();
5962 Indexes.push_back(Index);
5963 } while (EatIfPresent(lltok::comma));
5965 if (ParseToken(lltok::rbrace, "expected '}' here"))
5968 if (Indexes.size() < 2)
5969 return Error(Loc, "expected >= 2 uselistorder indexes");
5970 if (Offset != 0 || Max >= Indexes.size())
5971 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5973 return Error(Loc, "expected uselistorder indexes to change the order");
5978 /// ParseUseListOrder
5979 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5980 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5981 SMLoc Loc = Lex.getLoc();
5982 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5986 SmallVector<unsigned, 16> Indexes;
5987 if (ParseTypeAndValue(V, PFS) ||
5988 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5989 ParseUseListOrderIndexes(Indexes))
5992 return sortUseListOrder(V, Indexes, Loc);
5995 /// ParseUseListOrderBB
5996 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5997 bool LLParser::ParseUseListOrderBB() {
5998 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5999 SMLoc Loc = Lex.getLoc();
6003 SmallVector<unsigned, 16> Indexes;
6004 if (ParseValID(Fn) ||
6005 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6006 ParseValID(Label) ||
6007 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6008 ParseUseListOrderIndexes(Indexes))
6011 // Check the function.
6013 if (Fn.Kind == ValID::t_GlobalName)
6014 GV = M->getNamedValue(Fn.StrVal);
6015 else if (Fn.Kind == ValID::t_GlobalID)
6016 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6018 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6020 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6021 auto *F = dyn_cast<Function>(GV);
6023 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6024 if (F->isDeclaration())
6025 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6027 // Check the basic block.
6028 if (Label.Kind == ValID::t_LocalID)
6029 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6030 if (Label.Kind != ValID::t_LocalName)
6031 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6032 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6034 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6035 if (!isa<BasicBlock>(V))
6036 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6038 return sortUseListOrder(V, Indexes, Loc);