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/AsmParser/SlotMapping.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/CallingConv.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/ValueSymbolTable.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.h"
35 static std::string getTypeString(Type *T) {
37 raw_string_ostream Tmp(Result);
42 /// Run: module ::= toplevelentity*
43 bool LLParser::Run() {
47 return ParseTopLevelEntities() ||
48 ValidateEndOfModule();
51 bool LLParser::parseStandaloneConstantValue(Constant *&C) {
55 if (ParseType(Ty) || parseConstantValue(Ty, C))
57 if (Lex.getKind() != lltok::Eof)
58 return Error(Lex.getLoc(), "expected end of string");
62 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64 bool LLParser::ValidateEndOfModule() {
65 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
66 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
68 // Handle any function attribute group forward references.
69 for (std::map<Value*, std::vector<unsigned> >::iterator
70 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
73 std::vector<unsigned> &Vec = I->second;
76 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
78 B.merge(NumberedAttrBuilders[*VI]);
80 if (Function *Fn = dyn_cast<Function>(V)) {
81 AttributeSet AS = Fn->getAttributes();
82 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84 AS.getFnAttributes());
88 // If the alignment was parsed as an attribute, move to the alignment
90 if (FnAttrs.hasAlignmentAttr()) {
91 Fn->setAlignment(FnAttrs.getAlignment());
92 FnAttrs.removeAttribute(Attribute::Alignment);
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
99 Fn->setAttributes(AS);
100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101 AttributeSet AS = CI->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
110 CI->setAttributes(AS);
111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112 AttributeSet AS = II->getAttributes();
113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115 AS.getFnAttributes());
117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118 AttributeSet::get(Context,
119 AttributeSet::FunctionIndex,
121 II->setAttributes(AS);
123 llvm_unreachable("invalid object with forward attribute group reference");
127 // If there are entries in ForwardRefBlockAddresses at this point, the
128 // function was never defined.
129 if (!ForwardRefBlockAddresses.empty())
130 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
131 "expected function name in blockaddress");
133 for (const auto &NT : NumberedTypes)
134 if (NT.second.second.isValid())
135 return Error(NT.second.second,
136 "use of undefined type '%" + Twine(NT.first) + "'");
138 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
139 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
140 if (I->second.second.isValid())
141 return Error(I->second.second,
142 "use of undefined type named '" + I->getKey() + "'");
144 if (!ForwardRefComdats.empty())
145 return Error(ForwardRefComdats.begin()->second,
146 "use of undefined comdat '$" +
147 ForwardRefComdats.begin()->first + "'");
149 if (!ForwardRefVals.empty())
150 return Error(ForwardRefVals.begin()->second.second,
151 "use of undefined value '@" + ForwardRefVals.begin()->first +
154 if (!ForwardRefValIDs.empty())
155 return Error(ForwardRefValIDs.begin()->second.second,
156 "use of undefined value '@" +
157 Twine(ForwardRefValIDs.begin()->first) + "'");
159 if (!ForwardRefMDNodes.empty())
160 return Error(ForwardRefMDNodes.begin()->second.second,
161 "use of undefined metadata '!" +
162 Twine(ForwardRefMDNodes.begin()->first) + "'");
164 // Resolve metadata cycles.
165 for (auto &N : NumberedMetadata) {
166 if (N.second && !N.second->isResolved())
167 N.second->resolveCycles();
170 // Look for intrinsic functions and CallInst that need to be upgraded
171 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
172 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
174 UpgradeDebugInfo(*M);
178 // Initialize the slot mapping.
179 // Because by this point we've parsed and validated everything, we can "steal"
180 // the mapping from LLParser as it doesn't need it anymore.
181 Slots->GlobalValues = std::move(NumberedVals);
182 Slots->MetadataNodes = std::move(NumberedMetadata);
187 //===----------------------------------------------------------------------===//
188 // Top-Level Entities
189 //===----------------------------------------------------------------------===//
191 bool LLParser::ParseTopLevelEntities() {
193 switch (Lex.getKind()) {
194 default: return TokError("expected top-level entity");
195 case lltok::Eof: return false;
196 case lltok::kw_declare: if (ParseDeclare()) return true; break;
197 case lltok::kw_define: if (ParseDefine()) return true; break;
198 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
199 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
200 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
201 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
202 case lltok::LocalVar: if (ParseNamedType()) return true; break;
203 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
204 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
205 case lltok::ComdatVar: if (parseComdat()) return true; break;
206 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
207 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
209 // The Global variable production with no name can have many different
210 // optional leading prefixes, the production is:
211 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
212 // OptionalThreadLocal OptionalAddrSpace OptionalUnnamedAddr
213 // ('constant'|'global') ...
214 case lltok::kw_private: // OptionalLinkage
215 case lltok::kw_internal: // OptionalLinkage
216 case lltok::kw_weak: // OptionalLinkage
217 case lltok::kw_weak_odr: // OptionalLinkage
218 case lltok::kw_linkonce: // OptionalLinkage
219 case lltok::kw_linkonce_odr: // OptionalLinkage
220 case lltok::kw_appending: // OptionalLinkage
221 case lltok::kw_common: // OptionalLinkage
222 case lltok::kw_extern_weak: // OptionalLinkage
223 case lltok::kw_external: // OptionalLinkage
224 case lltok::kw_default: // OptionalVisibility
225 case lltok::kw_hidden: // OptionalVisibility
226 case lltok::kw_protected: // OptionalVisibility
227 case lltok::kw_dllimport: // OptionalDLLStorageClass
228 case lltok::kw_dllexport: // OptionalDLLStorageClass
229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: { // GlobalType
233 unsigned Linkage, Visibility, DLLStorageClass;
235 GlobalVariable::ThreadLocalMode TLM;
237 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
238 ParseOptionalVisibility(Visibility) ||
239 ParseOptionalDLLStorageClass(DLLStorageClass) ||
240 ParseOptionalThreadLocal(TLM) ||
241 parseOptionalUnnamedAddr(UnnamedAddr) ||
242 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
243 DLLStorageClass, TLM, UnnamedAddr))
248 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
249 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
250 case lltok::kw_uselistorder_bb:
251 if (ParseUseListOrderBB()) return true; break;
258 /// ::= 'module' 'asm' STRINGCONSTANT
259 bool LLParser::ParseModuleAsm() {
260 assert(Lex.getKind() == lltok::kw_module);
264 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
265 ParseStringConstant(AsmStr)) return true;
267 M->appendModuleInlineAsm(AsmStr);
272 /// ::= 'target' 'triple' '=' STRINGCONSTANT
273 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
274 bool LLParser::ParseTargetDefinition() {
275 assert(Lex.getKind() == lltok::kw_target);
278 default: return TokError("unknown target property");
279 case lltok::kw_triple:
281 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
282 ParseStringConstant(Str))
284 M->setTargetTriple(Str);
286 case lltok::kw_datalayout:
288 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
289 ParseStringConstant(Str))
291 M->setDataLayout(Str);
297 /// ::= 'deplibs' '=' '[' ']'
298 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
299 /// FIXME: Remove in 4.0. Currently parse, but ignore.
300 bool LLParser::ParseDepLibs() {
301 assert(Lex.getKind() == lltok::kw_deplibs);
303 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
304 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
307 if (EatIfPresent(lltok::rsquare))
312 if (ParseStringConstant(Str)) return true;
313 } while (EatIfPresent(lltok::comma));
315 return ParseToken(lltok::rsquare, "expected ']' at end of list");
318 /// ParseUnnamedType:
319 /// ::= LocalVarID '=' 'type' type
320 bool LLParser::ParseUnnamedType() {
321 LocTy TypeLoc = Lex.getLoc();
322 unsigned TypeID = Lex.getUIntVal();
323 Lex.Lex(); // eat LocalVarID;
325 if (ParseToken(lltok::equal, "expected '=' after name") ||
326 ParseToken(lltok::kw_type, "expected 'type' after '='"))
329 Type *Result = nullptr;
330 if (ParseStructDefinition(TypeLoc, "",
331 NumberedTypes[TypeID], Result)) return true;
333 if (!isa<StructType>(Result)) {
334 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
336 return Error(TypeLoc, "non-struct types may not be recursive");
337 Entry.first = Result;
338 Entry.second = SMLoc();
346 /// ::= LocalVar '=' 'type' type
347 bool LLParser::ParseNamedType() {
348 std::string Name = Lex.getStrVal();
349 LocTy NameLoc = Lex.getLoc();
350 Lex.Lex(); // eat LocalVar.
352 if (ParseToken(lltok::equal, "expected '=' after name") ||
353 ParseToken(lltok::kw_type, "expected 'type' after name"))
356 Type *Result = nullptr;
357 if (ParseStructDefinition(NameLoc, Name,
358 NamedTypes[Name], Result)) return true;
360 if (!isa<StructType>(Result)) {
361 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
363 return Error(NameLoc, "non-struct types may not be recursive");
364 Entry.first = Result;
365 Entry.second = SMLoc();
373 /// ::= 'declare' FunctionHeader
374 bool LLParser::ParseDeclare() {
375 assert(Lex.getKind() == lltok::kw_declare);
379 return ParseFunctionHeader(F, false);
383 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
384 bool LLParser::ParseDefine() {
385 assert(Lex.getKind() == lltok::kw_define);
389 return ParseFunctionHeader(F, true) ||
390 ParseOptionalFunctionMetadata(*F) ||
391 ParseFunctionBody(*F);
397 bool LLParser::ParseGlobalType(bool &IsConstant) {
398 if (Lex.getKind() == lltok::kw_constant)
400 else if (Lex.getKind() == lltok::kw_global)
404 return TokError("expected 'global' or 'constant'");
410 /// ParseUnnamedGlobal:
411 /// OptionalVisibility ALIAS ...
412 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
413 /// ... -> global variable
414 /// GlobalID '=' OptionalVisibility ALIAS ...
415 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
416 /// ... -> global variable
417 bool LLParser::ParseUnnamedGlobal() {
418 unsigned VarID = NumberedVals.size();
420 LocTy NameLoc = Lex.getLoc();
422 // Handle the GlobalID form.
423 if (Lex.getKind() == lltok::GlobalID) {
424 if (Lex.getUIntVal() != VarID)
425 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
427 Lex.Lex(); // eat GlobalID;
429 if (ParseToken(lltok::equal, "expected '=' after name"))
434 unsigned Linkage, Visibility, DLLStorageClass;
435 GlobalVariable::ThreadLocalMode TLM;
437 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
438 ParseOptionalVisibility(Visibility) ||
439 ParseOptionalDLLStorageClass(DLLStorageClass) ||
440 ParseOptionalThreadLocal(TLM) ||
441 parseOptionalUnnamedAddr(UnnamedAddr))
444 if (Lex.getKind() != lltok::kw_alias)
445 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
446 DLLStorageClass, TLM, UnnamedAddr);
447 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
451 /// ParseNamedGlobal:
452 /// GlobalVar '=' OptionalVisibility ALIAS ...
453 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454 /// ... -> global variable
455 bool LLParser::ParseNamedGlobal() {
456 assert(Lex.getKind() == lltok::GlobalVar);
457 LocTy NameLoc = Lex.getLoc();
458 std::string Name = Lex.getStrVal();
462 unsigned Linkage, Visibility, DLLStorageClass;
463 GlobalVariable::ThreadLocalMode TLM;
465 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
466 ParseOptionalLinkage(Linkage, HasLinkage) ||
467 ParseOptionalVisibility(Visibility) ||
468 ParseOptionalDLLStorageClass(DLLStorageClass) ||
469 ParseOptionalThreadLocal(TLM) ||
470 parseOptionalUnnamedAddr(UnnamedAddr))
473 if (Lex.getKind() != lltok::kw_alias)
474 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
475 DLLStorageClass, TLM, UnnamedAddr);
477 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
481 bool LLParser::parseComdat() {
482 assert(Lex.getKind() == lltok::ComdatVar);
483 std::string Name = Lex.getStrVal();
484 LocTy NameLoc = Lex.getLoc();
487 if (ParseToken(lltok::equal, "expected '=' here"))
490 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
491 return TokError("expected comdat type");
493 Comdat::SelectionKind SK;
494 switch (Lex.getKind()) {
496 return TokError("unknown selection kind");
500 case lltok::kw_exactmatch:
501 SK = Comdat::ExactMatch;
503 case lltok::kw_largest:
504 SK = Comdat::Largest;
506 case lltok::kw_noduplicates:
507 SK = Comdat::NoDuplicates;
509 case lltok::kw_samesize:
510 SK = Comdat::SameSize;
515 // See if the comdat was forward referenced, if so, use the comdat.
516 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
517 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
518 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
519 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
522 if (I != ComdatSymTab.end())
525 C = M->getOrInsertComdat(Name);
526 C->setSelectionKind(SK);
532 // ::= '!' STRINGCONSTANT
533 bool LLParser::ParseMDString(MDString *&Result) {
535 if (ParseStringConstant(Str)) return true;
536 llvm::UpgradeMDStringConstant(Str);
537 Result = MDString::get(Context, Str);
542 // ::= '!' MDNodeNumber
543 bool LLParser::ParseMDNodeID(MDNode *&Result) {
544 // !{ ..., !42, ... }
546 if (ParseUInt32(MID))
549 // If not a forward reference, just return it now.
550 if (NumberedMetadata.count(MID)) {
551 Result = NumberedMetadata[MID];
555 // Otherwise, create MDNode forward reference.
556 auto &FwdRef = ForwardRefMDNodes[MID];
557 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
559 Result = FwdRef.first.get();
560 NumberedMetadata[MID].reset(Result);
564 /// ParseNamedMetadata:
565 /// !foo = !{ !1, !2 }
566 bool LLParser::ParseNamedMetadata() {
567 assert(Lex.getKind() == lltok::MetadataVar);
568 std::string Name = Lex.getStrVal();
571 if (ParseToken(lltok::equal, "expected '=' here") ||
572 ParseToken(lltok::exclaim, "Expected '!' here") ||
573 ParseToken(lltok::lbrace, "Expected '{' here"))
576 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
577 if (Lex.getKind() != lltok::rbrace)
579 if (ParseToken(lltok::exclaim, "Expected '!' here"))
583 if (ParseMDNodeID(N)) return true;
585 } while (EatIfPresent(lltok::comma));
587 return ParseToken(lltok::rbrace, "expected end of metadata node");
590 /// ParseStandaloneMetadata:
592 bool LLParser::ParseStandaloneMetadata() {
593 assert(Lex.getKind() == lltok::exclaim);
595 unsigned MetadataID = 0;
598 if (ParseUInt32(MetadataID) ||
599 ParseToken(lltok::equal, "expected '=' here"))
602 // Detect common error, from old metadata syntax.
603 if (Lex.getKind() == lltok::Type)
604 return TokError("unexpected type in metadata definition");
606 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
607 if (Lex.getKind() == lltok::MetadataVar) {
608 if (ParseSpecializedMDNode(Init, IsDistinct))
610 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
611 ParseMDTuple(Init, IsDistinct))
614 // See if this was forward referenced, if so, handle it.
615 auto FI = ForwardRefMDNodes.find(MetadataID);
616 if (FI != ForwardRefMDNodes.end()) {
617 FI->second.first->replaceAllUsesWith(Init);
618 ForwardRefMDNodes.erase(FI);
620 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
622 if (NumberedMetadata.count(MetadataID))
623 return TokError("Metadata id is already used");
624 NumberedMetadata[MetadataID].reset(Init);
630 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
631 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
632 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
636 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
637 /// OptionalDLLStorageClass OptionalThreadLocal
638 /// OptionalUnnamedAddr 'alias' Aliasee
643 /// Everything through OptionalUnnamedAddr has already been parsed.
645 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
646 unsigned Visibility, unsigned DLLStorageClass,
647 GlobalVariable::ThreadLocalMode TLM,
649 assert(Lex.getKind() == lltok::kw_alias);
652 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
654 if(!GlobalAlias::isValidLinkage(Linkage))
655 return Error(NameLoc, "invalid linkage type for alias");
657 if (!isValidVisibilityForLinkage(Visibility, L))
658 return Error(NameLoc,
659 "symbol with local linkage must have default visibility");
662 LocTy AliaseeLoc = Lex.getLoc();
663 if (Lex.getKind() != lltok::kw_bitcast &&
664 Lex.getKind() != lltok::kw_getelementptr &&
665 Lex.getKind() != lltok::kw_addrspacecast &&
666 Lex.getKind() != lltok::kw_inttoptr) {
667 if (ParseGlobalTypeAndValue(Aliasee))
670 // The bitcast dest type is not present, it is implied by the dest type.
674 if (ID.Kind != ValID::t_Constant)
675 return Error(AliaseeLoc, "invalid aliasee");
676 Aliasee = ID.ConstantVal;
679 Type *AliaseeType = Aliasee->getType();
680 auto *PTy = dyn_cast<PointerType>(AliaseeType);
682 return Error(AliaseeLoc, "An alias must have pointer type");
684 // Okay, create the alias but do not insert it into the module yet.
685 std::unique_ptr<GlobalAlias> GA(
686 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
687 Aliasee, /*Parent*/ nullptr));
688 GA->setThreadLocalMode(TLM);
689 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
690 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
691 GA->setUnnamedAddr(UnnamedAddr);
694 NumberedVals.push_back(GA.get());
696 // See if this value already exists in the symbol table. If so, it is either
697 // a redefinition or a definition of a forward reference.
698 if (GlobalValue *Val = M->getNamedValue(Name)) {
699 // See if this was a redefinition. If so, there is no entry in
701 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
702 I = ForwardRefVals.find(Name);
703 if (I == ForwardRefVals.end())
704 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
706 // Otherwise, this was a definition of forward ref. Verify that types
708 if (Val->getType() != GA->getType())
709 return Error(NameLoc,
710 "forward reference and definition of alias have different types");
712 // If they agree, just RAUW the old value with the alias and remove the
714 Val->replaceAllUsesWith(GA.get());
715 Val->eraseFromParent();
716 ForwardRefVals.erase(I);
719 // Insert into the module, we know its name won't collide now.
720 M->getAliasList().push_back(GA.get());
721 assert(GA->getName() == Name && "Should not be a name conflict!");
723 // The module owns this now
730 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
731 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
732 /// OptionalExternallyInitialized GlobalType Type Const
733 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
734 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
735 /// OptionalExternallyInitialized GlobalType Type Const
737 /// Everything up to and including OptionalUnnamedAddr has been parsed
740 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
741 unsigned Linkage, bool HasLinkage,
742 unsigned Visibility, unsigned DLLStorageClass,
743 GlobalVariable::ThreadLocalMode TLM,
745 if (!isValidVisibilityForLinkage(Visibility, Linkage))
746 return Error(NameLoc,
747 "symbol with local linkage must have default visibility");
750 bool IsConstant, IsExternallyInitialized;
751 LocTy IsExternallyInitializedLoc;
755 if (ParseOptionalAddrSpace(AddrSpace) ||
756 ParseOptionalToken(lltok::kw_externally_initialized,
757 IsExternallyInitialized,
758 &IsExternallyInitializedLoc) ||
759 ParseGlobalType(IsConstant) ||
760 ParseType(Ty, TyLoc))
763 // If the linkage is specified and is external, then no initializer is
765 Constant *Init = nullptr;
766 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
767 Linkage != GlobalValue::ExternalLinkage)) {
768 if (ParseGlobalValue(Ty, Init))
772 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
773 return Error(TyLoc, "invalid type for global variable");
775 GlobalValue *GVal = nullptr;
777 // See if the global was forward referenced, if so, use the global.
779 GVal = M->getNamedValue(Name);
781 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
782 return Error(NameLoc, "redefinition of global '@" + Name + "'");
785 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
786 I = ForwardRefValIDs.find(NumberedVals.size());
787 if (I != ForwardRefValIDs.end()) {
788 GVal = I->second.first;
789 ForwardRefValIDs.erase(I);
795 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
796 Name, nullptr, GlobalVariable::NotThreadLocal,
799 if (GVal->getValueType() != Ty)
801 "forward reference and definition of global have different types");
803 GV = cast<GlobalVariable>(GVal);
805 // Move the forward-reference to the correct spot in the module.
806 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
810 NumberedVals.push_back(GV);
812 // Set the parsed properties on the global.
814 GV->setInitializer(Init);
815 GV->setConstant(IsConstant);
816 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
817 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
818 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
819 GV->setExternallyInitialized(IsExternallyInitialized);
820 GV->setThreadLocalMode(TLM);
821 GV->setUnnamedAddr(UnnamedAddr);
823 // Parse attributes on the global.
824 while (Lex.getKind() == lltok::comma) {
827 if (Lex.getKind() == lltok::kw_section) {
829 GV->setSection(Lex.getStrVal());
830 if (ParseToken(lltok::StringConstant, "expected global section string"))
832 } else if (Lex.getKind() == lltok::kw_align) {
834 if (ParseOptionalAlignment(Alignment)) return true;
835 GV->setAlignment(Alignment);
838 if (parseOptionalComdat(Name, C))
843 return TokError("unknown global variable property!");
850 /// ParseUnnamedAttrGrp
851 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
852 bool LLParser::ParseUnnamedAttrGrp() {
853 assert(Lex.getKind() == lltok::kw_attributes);
854 LocTy AttrGrpLoc = Lex.getLoc();
857 if (Lex.getKind() != lltok::AttrGrpID)
858 return TokError("expected attribute group id");
860 unsigned VarID = Lex.getUIntVal();
861 std::vector<unsigned> unused;
865 if (ParseToken(lltok::equal, "expected '=' here") ||
866 ParseToken(lltok::lbrace, "expected '{' here") ||
867 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
869 ParseToken(lltok::rbrace, "expected end of attribute group"))
872 if (!NumberedAttrBuilders[VarID].hasAttributes())
873 return Error(AttrGrpLoc, "attribute group has no attributes");
878 /// ParseFnAttributeValuePairs
879 /// ::= <attr> | <attr> '=' <value>
880 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
881 std::vector<unsigned> &FwdRefAttrGrps,
882 bool inAttrGrp, LocTy &BuiltinLoc) {
883 bool HaveError = false;
888 lltok::Kind Token = Lex.getKind();
889 if (Token == lltok::kw_builtin)
890 BuiltinLoc = Lex.getLoc();
893 if (!inAttrGrp) return HaveError;
894 return Error(Lex.getLoc(), "unterminated attribute group");
899 case lltok::AttrGrpID: {
900 // Allow a function to reference an attribute group:
902 // define void @foo() #1 { ... }
906 "cannot have an attribute group reference in an attribute group");
908 unsigned AttrGrpNum = Lex.getUIntVal();
909 if (inAttrGrp) break;
911 // Save the reference to the attribute group. We'll fill it in later.
912 FwdRefAttrGrps.push_back(AttrGrpNum);
915 // Target-dependent attributes:
916 case lltok::StringConstant: {
917 std::string Attr = Lex.getStrVal();
920 if (EatIfPresent(lltok::equal) &&
921 ParseStringConstant(Val))
924 B.addAttribute(Attr, Val);
928 // Target-independent attributes:
929 case lltok::kw_align: {
930 // As a hack, we allow function alignment to be initially parsed as an
931 // attribute on a function declaration/definition or added to an attribute
932 // group and later moved to the alignment field.
936 if (ParseToken(lltok::equal, "expected '=' here") ||
937 ParseUInt32(Alignment))
940 if (ParseOptionalAlignment(Alignment))
943 B.addAlignmentAttr(Alignment);
946 case lltok::kw_alignstack: {
950 if (ParseToken(lltok::equal, "expected '=' here") ||
951 ParseUInt32(Alignment))
954 if (ParseOptionalStackAlignment(Alignment))
957 B.addStackAlignmentAttr(Alignment);
960 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
961 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
962 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
963 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
964 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
965 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
966 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
967 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
968 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
969 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
970 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
971 case lltok::kw_noimplicitfloat:
972 B.addAttribute(Attribute::NoImplicitFloat); break;
973 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
974 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
975 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
976 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
977 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
978 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
979 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
980 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
981 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
982 case lltok::kw_returns_twice:
983 B.addAttribute(Attribute::ReturnsTwice); break;
984 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
985 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
986 case lltok::kw_sspstrong:
987 B.addAttribute(Attribute::StackProtectStrong); break;
988 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
989 case lltok::kw_sanitize_address:
990 B.addAttribute(Attribute::SanitizeAddress); break;
991 case lltok::kw_sanitize_thread:
992 B.addAttribute(Attribute::SanitizeThread); break;
993 case lltok::kw_sanitize_memory:
994 B.addAttribute(Attribute::SanitizeMemory); break;
995 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
998 case lltok::kw_inreg:
999 case lltok::kw_signext:
1000 case lltok::kw_zeroext:
1003 "invalid use of attribute on a function");
1005 case lltok::kw_byval:
1006 case lltok::kw_dereferenceable:
1007 case lltok::kw_dereferenceable_or_null:
1008 case lltok::kw_inalloca:
1009 case lltok::kw_nest:
1010 case lltok::kw_noalias:
1011 case lltok::kw_nocapture:
1012 case lltok::kw_nonnull:
1013 case lltok::kw_returned:
1014 case lltok::kw_sret:
1017 "invalid use of parameter-only attribute on a function");
1025 //===----------------------------------------------------------------------===//
1026 // GlobalValue Reference/Resolution Routines.
1027 //===----------------------------------------------------------------------===//
1029 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1030 /// forward reference record if needed. This can return null if the value
1031 /// exists but does not have the right type.
1032 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1034 PointerType *PTy = dyn_cast<PointerType>(Ty);
1036 Error(Loc, "global variable reference must have pointer type");
1040 // Look this name up in the normal function symbol table.
1042 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1044 // If this is a forward reference for the value, see if we already created a
1045 // forward ref record.
1047 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1048 I = ForwardRefVals.find(Name);
1049 if (I != ForwardRefVals.end())
1050 Val = I->second.first;
1053 // If we have the value in the symbol table or fwd-ref table, return it.
1055 if (Val->getType() == Ty) return Val;
1056 Error(Loc, "'@" + Name + "' defined with type '" +
1057 getTypeString(Val->getType()) + "'");
1061 // Otherwise, create a new forward reference for this value and remember it.
1062 GlobalValue *FwdVal;
1063 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1064 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1066 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1067 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1068 nullptr, GlobalVariable::NotThreadLocal,
1069 PTy->getAddressSpace());
1071 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1075 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1076 PointerType *PTy = dyn_cast<PointerType>(Ty);
1078 Error(Loc, "global variable reference must have pointer type");
1082 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1084 // If this is a forward reference for the value, see if we already created a
1085 // forward ref record.
1087 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1088 I = ForwardRefValIDs.find(ID);
1089 if (I != ForwardRefValIDs.end())
1090 Val = I->second.first;
1093 // If we have the value in the symbol table or fwd-ref table, return it.
1095 if (Val->getType() == Ty) return Val;
1096 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1097 getTypeString(Val->getType()) + "'");
1101 // Otherwise, create a new forward reference for this value and remember it.
1102 GlobalValue *FwdVal;
1103 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1104 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1106 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1107 GlobalValue::ExternalWeakLinkage, nullptr, "");
1109 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1114 //===----------------------------------------------------------------------===//
1115 // Comdat Reference/Resolution Routines.
1116 //===----------------------------------------------------------------------===//
1118 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1119 // Look this name up in the comdat symbol table.
1120 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1121 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1122 if (I != ComdatSymTab.end())
1125 // Otherwise, create a new forward reference for this value and remember it.
1126 Comdat *C = M->getOrInsertComdat(Name);
1127 ForwardRefComdats[Name] = Loc;
1132 //===----------------------------------------------------------------------===//
1134 //===----------------------------------------------------------------------===//
1136 /// ParseToken - If the current token has the specified kind, eat it and return
1137 /// success. Otherwise, emit the specified error and return failure.
1138 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1139 if (Lex.getKind() != T)
1140 return TokError(ErrMsg);
1145 /// ParseStringConstant
1146 /// ::= StringConstant
1147 bool LLParser::ParseStringConstant(std::string &Result) {
1148 if (Lex.getKind() != lltok::StringConstant)
1149 return TokError("expected string constant");
1150 Result = Lex.getStrVal();
1157 bool LLParser::ParseUInt32(unsigned &Val) {
1158 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1159 return TokError("expected integer");
1160 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1161 if (Val64 != unsigned(Val64))
1162 return TokError("expected 32-bit integer (too large)");
1170 bool LLParser::ParseUInt64(uint64_t &Val) {
1171 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1172 return TokError("expected integer");
1173 Val = Lex.getAPSIntVal().getLimitedValue();
1179 /// := 'localdynamic'
1180 /// := 'initialexec'
1182 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1183 switch (Lex.getKind()) {
1185 return TokError("expected localdynamic, initialexec or localexec");
1186 case lltok::kw_localdynamic:
1187 TLM = GlobalVariable::LocalDynamicTLSModel;
1189 case lltok::kw_initialexec:
1190 TLM = GlobalVariable::InitialExecTLSModel;
1192 case lltok::kw_localexec:
1193 TLM = GlobalVariable::LocalExecTLSModel;
1201 /// ParseOptionalThreadLocal
1203 /// := 'thread_local'
1204 /// := 'thread_local' '(' tlsmodel ')'
1205 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1206 TLM = GlobalVariable::NotThreadLocal;
1207 if (!EatIfPresent(lltok::kw_thread_local))
1210 TLM = GlobalVariable::GeneralDynamicTLSModel;
1211 if (Lex.getKind() == lltok::lparen) {
1213 return ParseTLSModel(TLM) ||
1214 ParseToken(lltok::rparen, "expected ')' after thread local model");
1219 /// ParseOptionalAddrSpace
1221 /// := 'addrspace' '(' uint32 ')'
1222 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1224 if (!EatIfPresent(lltok::kw_addrspace))
1226 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1227 ParseUInt32(AddrSpace) ||
1228 ParseToken(lltok::rparen, "expected ')' in address space");
1231 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1232 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1233 bool HaveError = false;
1238 lltok::Kind Token = Lex.getKind();
1240 default: // End of attributes.
1242 case lltok::kw_align: {
1244 if (ParseOptionalAlignment(Alignment))
1246 B.addAlignmentAttr(Alignment);
1249 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1250 case lltok::kw_dereferenceable: {
1252 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1254 B.addDereferenceableAttr(Bytes);
1257 case lltok::kw_dereferenceable_or_null: {
1259 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1261 B.addDereferenceableOrNullAttr(Bytes);
1264 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1265 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1266 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1267 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1268 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1269 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1270 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1271 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1272 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1273 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1274 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1275 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1277 case lltok::kw_alignstack:
1278 case lltok::kw_alwaysinline:
1279 case lltok::kw_argmemonly:
1280 case lltok::kw_builtin:
1281 case lltok::kw_inlinehint:
1282 case lltok::kw_jumptable:
1283 case lltok::kw_minsize:
1284 case lltok::kw_naked:
1285 case lltok::kw_nobuiltin:
1286 case lltok::kw_noduplicate:
1287 case lltok::kw_noimplicitfloat:
1288 case lltok::kw_noinline:
1289 case lltok::kw_nonlazybind:
1290 case lltok::kw_noredzone:
1291 case lltok::kw_noreturn:
1292 case lltok::kw_nounwind:
1293 case lltok::kw_optnone:
1294 case lltok::kw_optsize:
1295 case lltok::kw_returns_twice:
1296 case lltok::kw_sanitize_address:
1297 case lltok::kw_sanitize_memory:
1298 case lltok::kw_sanitize_thread:
1300 case lltok::kw_sspreq:
1301 case lltok::kw_sspstrong:
1302 case lltok::kw_safestack:
1303 case lltok::kw_uwtable:
1304 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1312 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1313 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1314 bool HaveError = false;
1319 lltok::Kind Token = Lex.getKind();
1321 default: // End of attributes.
1323 case lltok::kw_dereferenceable: {
1325 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1327 B.addDereferenceableAttr(Bytes);
1330 case lltok::kw_dereferenceable_or_null: {
1332 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1334 B.addDereferenceableOrNullAttr(Bytes);
1337 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1338 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1339 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1340 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1341 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1344 case lltok::kw_align:
1345 case lltok::kw_byval:
1346 case lltok::kw_inalloca:
1347 case lltok::kw_nest:
1348 case lltok::kw_nocapture:
1349 case lltok::kw_returned:
1350 case lltok::kw_sret:
1351 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1354 case lltok::kw_alignstack:
1355 case lltok::kw_alwaysinline:
1356 case lltok::kw_argmemonly:
1357 case lltok::kw_builtin:
1358 case lltok::kw_cold:
1359 case lltok::kw_inlinehint:
1360 case lltok::kw_jumptable:
1361 case lltok::kw_minsize:
1362 case lltok::kw_naked:
1363 case lltok::kw_nobuiltin:
1364 case lltok::kw_noduplicate:
1365 case lltok::kw_noimplicitfloat:
1366 case lltok::kw_noinline:
1367 case lltok::kw_nonlazybind:
1368 case lltok::kw_noredzone:
1369 case lltok::kw_noreturn:
1370 case lltok::kw_nounwind:
1371 case lltok::kw_optnone:
1372 case lltok::kw_optsize:
1373 case lltok::kw_returns_twice:
1374 case lltok::kw_sanitize_address:
1375 case lltok::kw_sanitize_memory:
1376 case lltok::kw_sanitize_thread:
1378 case lltok::kw_sspreq:
1379 case lltok::kw_sspstrong:
1380 case lltok::kw_safestack:
1381 case lltok::kw_uwtable:
1382 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1385 case lltok::kw_readnone:
1386 case lltok::kw_readonly:
1387 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1394 /// ParseOptionalLinkage
1401 /// ::= 'linkonce_odr'
1402 /// ::= 'available_externally'
1405 /// ::= 'extern_weak'
1407 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1409 switch (Lex.getKind()) {
1410 default: Res=GlobalValue::ExternalLinkage; return false;
1411 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1412 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1413 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1414 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1415 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1416 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1417 case lltok::kw_available_externally:
1418 Res = GlobalValue::AvailableExternallyLinkage;
1420 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1421 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1422 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1423 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1430 /// ParseOptionalVisibility
1436 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1437 switch (Lex.getKind()) {
1438 default: Res = GlobalValue::DefaultVisibility; return false;
1439 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1440 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1441 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1447 /// ParseOptionalDLLStorageClass
1452 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1453 switch (Lex.getKind()) {
1454 default: Res = GlobalValue::DefaultStorageClass; return false;
1455 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1456 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1462 /// ParseOptionalCallingConv
1466 /// ::= 'intel_ocl_bicc'
1468 /// ::= 'x86_stdcallcc'
1469 /// ::= 'x86_fastcallcc'
1470 /// ::= 'x86_thiscallcc'
1471 /// ::= 'x86_vectorcallcc'
1472 /// ::= 'arm_apcscc'
1473 /// ::= 'arm_aapcscc'
1474 /// ::= 'arm_aapcs_vfpcc'
1475 /// ::= 'msp430_intrcc'
1476 /// ::= 'ptx_kernel'
1477 /// ::= 'ptx_device'
1479 /// ::= 'spir_kernel'
1480 /// ::= 'x86_64_sysvcc'
1481 /// ::= 'x86_64_win64cc'
1482 /// ::= 'webkit_jscc'
1484 /// ::= 'preserve_mostcc'
1485 /// ::= 'preserve_allcc'
1489 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1490 switch (Lex.getKind()) {
1491 default: CC = CallingConv::C; return false;
1492 case lltok::kw_ccc: CC = CallingConv::C; break;
1493 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1494 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1495 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1496 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1497 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1498 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1499 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1500 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1501 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1502 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1503 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1504 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1505 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1506 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1507 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1508 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1509 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1510 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1511 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1512 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1513 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1514 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1515 case lltok::kw_cc: {
1517 return ParseUInt32(CC);
1525 /// ParseMetadataAttachment
1527 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1528 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1530 std::string Name = Lex.getStrVal();
1531 Kind = M->getMDKindID(Name);
1534 return ParseMDNode(MD);
1537 /// ParseInstructionMetadata
1538 /// ::= !dbg !42 (',' !dbg !57)*
1539 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1541 if (Lex.getKind() != lltok::MetadataVar)
1542 return TokError("expected metadata after comma");
1546 if (ParseMetadataAttachment(MDK, N))
1549 Inst.setMetadata(MDK, N);
1550 if (MDK == LLVMContext::MD_tbaa)
1551 InstsWithTBAATag.push_back(&Inst);
1553 // If this is the end of the list, we're done.
1554 } while (EatIfPresent(lltok::comma));
1558 /// ParseOptionalFunctionMetadata
1560 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1561 while (Lex.getKind() == lltok::MetadataVar) {
1564 if (ParseMetadataAttachment(MDK, N))
1567 F.setMetadata(MDK, N);
1572 /// ParseOptionalAlignment
1575 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1577 if (!EatIfPresent(lltok::kw_align))
1579 LocTy AlignLoc = Lex.getLoc();
1580 if (ParseUInt32(Alignment)) return true;
1581 if (!isPowerOf2_32(Alignment))
1582 return Error(AlignLoc, "alignment is not a power of two");
1583 if (Alignment > Value::MaximumAlignment)
1584 return Error(AlignLoc, "huge alignments are not supported yet");
1588 /// ParseOptionalDerefAttrBytes
1590 /// ::= AttrKind '(' 4 ')'
1592 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1593 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1595 assert((AttrKind == lltok::kw_dereferenceable ||
1596 AttrKind == lltok::kw_dereferenceable_or_null) &&
1600 if (!EatIfPresent(AttrKind))
1602 LocTy ParenLoc = Lex.getLoc();
1603 if (!EatIfPresent(lltok::lparen))
1604 return Error(ParenLoc, "expected '('");
1605 LocTy DerefLoc = Lex.getLoc();
1606 if (ParseUInt64(Bytes)) return true;
1607 ParenLoc = Lex.getLoc();
1608 if (!EatIfPresent(lltok::rparen))
1609 return Error(ParenLoc, "expected ')'");
1611 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1615 /// ParseOptionalCommaAlign
1619 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1621 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1622 bool &AteExtraComma) {
1623 AteExtraComma = false;
1624 while (EatIfPresent(lltok::comma)) {
1625 // Metadata at the end is an early exit.
1626 if (Lex.getKind() == lltok::MetadataVar) {
1627 AteExtraComma = true;
1631 if (Lex.getKind() != lltok::kw_align)
1632 return Error(Lex.getLoc(), "expected metadata or 'align'");
1634 if (ParseOptionalAlignment(Alignment)) return true;
1640 /// ParseScopeAndOrdering
1641 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1644 /// This sets Scope and Ordering to the parsed values.
1645 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1646 AtomicOrdering &Ordering) {
1650 Scope = CrossThread;
1651 if (EatIfPresent(lltok::kw_singlethread))
1652 Scope = SingleThread;
1654 return ParseOrdering(Ordering);
1658 /// ::= AtomicOrdering
1660 /// This sets Ordering to the parsed value.
1661 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1662 switch (Lex.getKind()) {
1663 default: return TokError("Expected ordering on atomic instruction");
1664 case lltok::kw_unordered: Ordering = Unordered; break;
1665 case lltok::kw_monotonic: Ordering = Monotonic; break;
1666 case lltok::kw_acquire: Ordering = Acquire; break;
1667 case lltok::kw_release: Ordering = Release; break;
1668 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1669 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1675 /// ParseOptionalStackAlignment
1677 /// ::= 'alignstack' '(' 4 ')'
1678 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1680 if (!EatIfPresent(lltok::kw_alignstack))
1682 LocTy ParenLoc = Lex.getLoc();
1683 if (!EatIfPresent(lltok::lparen))
1684 return Error(ParenLoc, "expected '('");
1685 LocTy AlignLoc = Lex.getLoc();
1686 if (ParseUInt32(Alignment)) return true;
1687 ParenLoc = Lex.getLoc();
1688 if (!EatIfPresent(lltok::rparen))
1689 return Error(ParenLoc, "expected ')'");
1690 if (!isPowerOf2_32(Alignment))
1691 return Error(AlignLoc, "stack alignment is not a power of two");
1695 /// ParseIndexList - This parses the index list for an insert/extractvalue
1696 /// instruction. This sets AteExtraComma in the case where we eat an extra
1697 /// comma at the end of the line and find that it is followed by metadata.
1698 /// Clients that don't allow metadata can call the version of this function that
1699 /// only takes one argument.
1702 /// ::= (',' uint32)+
1704 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1705 bool &AteExtraComma) {
1706 AteExtraComma = false;
1708 if (Lex.getKind() != lltok::comma)
1709 return TokError("expected ',' as start of index list");
1711 while (EatIfPresent(lltok::comma)) {
1712 if (Lex.getKind() == lltok::MetadataVar) {
1713 if (Indices.empty()) return TokError("expected index");
1714 AteExtraComma = true;
1718 if (ParseUInt32(Idx)) return true;
1719 Indices.push_back(Idx);
1725 //===----------------------------------------------------------------------===//
1727 //===----------------------------------------------------------------------===//
1729 /// ParseType - Parse a type.
1730 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1731 SMLoc TypeLoc = Lex.getLoc();
1732 switch (Lex.getKind()) {
1734 return TokError(Msg);
1736 // Type ::= 'float' | 'void' (etc)
1737 Result = Lex.getTyVal();
1741 // Type ::= StructType
1742 if (ParseAnonStructType(Result, false))
1745 case lltok::lsquare:
1746 // Type ::= '[' ... ']'
1747 Lex.Lex(); // eat the lsquare.
1748 if (ParseArrayVectorType(Result, false))
1751 case lltok::less: // Either vector or packed struct.
1752 // Type ::= '<' ... '>'
1754 if (Lex.getKind() == lltok::lbrace) {
1755 if (ParseAnonStructType(Result, true) ||
1756 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1758 } else if (ParseArrayVectorType(Result, true))
1761 case lltok::LocalVar: {
1763 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1765 // If the type hasn't been defined yet, create a forward definition and
1766 // remember where that forward def'n was seen (in case it never is defined).
1768 Entry.first = StructType::create(Context, Lex.getStrVal());
1769 Entry.second = Lex.getLoc();
1771 Result = Entry.first;
1776 case lltok::LocalVarID: {
1778 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1780 // If the type hasn't been defined yet, create a forward definition and
1781 // remember where that forward def'n was seen (in case it never is defined).
1783 Entry.first = StructType::create(Context);
1784 Entry.second = Lex.getLoc();
1786 Result = Entry.first;
1792 // Parse the type suffixes.
1794 switch (Lex.getKind()) {
1797 if (!AllowVoid && Result->isVoidTy())
1798 return Error(TypeLoc, "void type only allowed for function results");
1801 // Type ::= Type '*'
1803 if (Result->isLabelTy())
1804 return TokError("basic block pointers are invalid");
1805 if (Result->isVoidTy())
1806 return TokError("pointers to void are invalid - use i8* instead");
1807 if (!PointerType::isValidElementType(Result))
1808 return TokError("pointer to this type is invalid");
1809 Result = PointerType::getUnqual(Result);
1813 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1814 case lltok::kw_addrspace: {
1815 if (Result->isLabelTy())
1816 return TokError("basic block pointers are invalid");
1817 if (Result->isVoidTy())
1818 return TokError("pointers to void are invalid; use i8* instead");
1819 if (!PointerType::isValidElementType(Result))
1820 return TokError("pointer to this type is invalid");
1822 if (ParseOptionalAddrSpace(AddrSpace) ||
1823 ParseToken(lltok::star, "expected '*' in address space"))
1826 Result = PointerType::get(Result, AddrSpace);
1830 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1832 if (ParseFunctionType(Result))
1839 /// ParseParameterList
1841 /// ::= '(' Arg (',' Arg)* ')'
1843 /// ::= Type OptionalAttributes Value OptionalAttributes
1844 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1845 PerFunctionState &PFS, bool IsMustTailCall,
1846 bool InVarArgsFunc) {
1847 if (ParseToken(lltok::lparen, "expected '(' in call"))
1850 unsigned AttrIndex = 1;
1851 while (Lex.getKind() != lltok::rparen) {
1852 // If this isn't the first argument, we need a comma.
1853 if (!ArgList.empty() &&
1854 ParseToken(lltok::comma, "expected ',' in argument list"))
1857 // Parse an ellipsis if this is a musttail call in a variadic function.
1858 if (Lex.getKind() == lltok::dotdotdot) {
1859 const char *Msg = "unexpected ellipsis in argument list for ";
1860 if (!IsMustTailCall)
1861 return TokError(Twine(Msg) + "non-musttail call");
1863 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1864 Lex.Lex(); // Lex the '...', it is purely for readability.
1865 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1868 // Parse the argument.
1870 Type *ArgTy = nullptr;
1871 AttrBuilder ArgAttrs;
1873 if (ParseType(ArgTy, ArgLoc))
1876 if (ArgTy->isMetadataTy()) {
1877 if (ParseMetadataAsValue(V, PFS))
1880 // Otherwise, handle normal operands.
1881 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1884 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1889 if (IsMustTailCall && InVarArgsFunc)
1890 return TokError("expected '...' at end of argument list for musttail call "
1891 "in varargs function");
1893 Lex.Lex(); // Lex the ')'.
1899 /// ParseArgumentList - Parse the argument list for a function type or function
1901 /// ::= '(' ArgTypeListI ')'
1905 /// ::= ArgTypeList ',' '...'
1906 /// ::= ArgType (',' ArgType)*
1908 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1911 assert(Lex.getKind() == lltok::lparen);
1912 Lex.Lex(); // eat the (.
1914 if (Lex.getKind() == lltok::rparen) {
1916 } else if (Lex.getKind() == lltok::dotdotdot) {
1920 LocTy TypeLoc = Lex.getLoc();
1921 Type *ArgTy = nullptr;
1925 if (ParseType(ArgTy) ||
1926 ParseOptionalParamAttrs(Attrs)) return true;
1928 if (ArgTy->isVoidTy())
1929 return Error(TypeLoc, "argument can not have void type");
1931 if (Lex.getKind() == lltok::LocalVar) {
1932 Name = Lex.getStrVal();
1936 if (!FunctionType::isValidArgumentType(ArgTy))
1937 return Error(TypeLoc, "invalid type for function argument");
1939 unsigned AttrIndex = 1;
1940 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
1941 AttrIndex++, Attrs),
1944 while (EatIfPresent(lltok::comma)) {
1945 // Handle ... at end of arg list.
1946 if (EatIfPresent(lltok::dotdotdot)) {
1951 // Otherwise must be an argument type.
1952 TypeLoc = Lex.getLoc();
1953 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1955 if (ArgTy->isVoidTy())
1956 return Error(TypeLoc, "argument can not have void type");
1958 if (Lex.getKind() == lltok::LocalVar) {
1959 Name = Lex.getStrVal();
1965 if (!ArgTy->isFirstClassType())
1966 return Error(TypeLoc, "invalid type for function argument");
1968 ArgList.emplace_back(
1970 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
1975 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1978 /// ParseFunctionType
1979 /// ::= Type ArgumentList OptionalAttrs
1980 bool LLParser::ParseFunctionType(Type *&Result) {
1981 assert(Lex.getKind() == lltok::lparen);
1983 if (!FunctionType::isValidReturnType(Result))
1984 return TokError("invalid function return type");
1986 SmallVector<ArgInfo, 8> ArgList;
1988 if (ParseArgumentList(ArgList, isVarArg))
1991 // Reject names on the arguments lists.
1992 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1993 if (!ArgList[i].Name.empty())
1994 return Error(ArgList[i].Loc, "argument name invalid in function type");
1995 if (ArgList[i].Attrs.hasAttributes(i + 1))
1996 return Error(ArgList[i].Loc,
1997 "argument attributes invalid in function type");
2000 SmallVector<Type*, 16> ArgListTy;
2001 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2002 ArgListTy.push_back(ArgList[i].Ty);
2004 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2008 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2010 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2011 SmallVector<Type*, 8> Elts;
2012 if (ParseStructBody(Elts)) return true;
2014 Result = StructType::get(Context, Elts, Packed);
2018 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2019 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2020 std::pair<Type*, LocTy> &Entry,
2022 // If the type was already defined, diagnose the redefinition.
2023 if (Entry.first && !Entry.second.isValid())
2024 return Error(TypeLoc, "redefinition of type");
2026 // If we have opaque, just return without filling in the definition for the
2027 // struct. This counts as a definition as far as the .ll file goes.
2028 if (EatIfPresent(lltok::kw_opaque)) {
2029 // This type is being defined, so clear the location to indicate this.
2030 Entry.second = SMLoc();
2032 // If this type number has never been uttered, create it.
2034 Entry.first = StructType::create(Context, Name);
2035 ResultTy = Entry.first;
2039 // If the type starts with '<', then it is either a packed struct or a vector.
2040 bool isPacked = EatIfPresent(lltok::less);
2042 // If we don't have a struct, then we have a random type alias, which we
2043 // accept for compatibility with old files. These types are not allowed to be
2044 // forward referenced and not allowed to be recursive.
2045 if (Lex.getKind() != lltok::lbrace) {
2047 return Error(TypeLoc, "forward references to non-struct type");
2051 return ParseArrayVectorType(ResultTy, true);
2052 return ParseType(ResultTy);
2055 // This type is being defined, so clear the location to indicate this.
2056 Entry.second = SMLoc();
2058 // If this type number has never been uttered, create it.
2060 Entry.first = StructType::create(Context, Name);
2062 StructType *STy = cast<StructType>(Entry.first);
2064 SmallVector<Type*, 8> Body;
2065 if (ParseStructBody(Body) ||
2066 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2069 STy->setBody(Body, isPacked);
2075 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2078 /// ::= '{' Type (',' Type)* '}'
2079 /// ::= '<' '{' '}' '>'
2080 /// ::= '<' '{' Type (',' Type)* '}' '>'
2081 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2082 assert(Lex.getKind() == lltok::lbrace);
2083 Lex.Lex(); // Consume the '{'
2085 // Handle the empty struct.
2086 if (EatIfPresent(lltok::rbrace))
2089 LocTy EltTyLoc = Lex.getLoc();
2091 if (ParseType(Ty)) return true;
2094 if (!StructType::isValidElementType(Ty))
2095 return Error(EltTyLoc, "invalid element type for struct");
2097 while (EatIfPresent(lltok::comma)) {
2098 EltTyLoc = Lex.getLoc();
2099 if (ParseType(Ty)) return true;
2101 if (!StructType::isValidElementType(Ty))
2102 return Error(EltTyLoc, "invalid element type for struct");
2107 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2110 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2111 /// token has already been consumed.
2113 /// ::= '[' APSINTVAL 'x' Types ']'
2114 /// ::= '<' APSINTVAL 'x' Types '>'
2115 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2116 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2117 Lex.getAPSIntVal().getBitWidth() > 64)
2118 return TokError("expected number in address space");
2120 LocTy SizeLoc = Lex.getLoc();
2121 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2124 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2127 LocTy TypeLoc = Lex.getLoc();
2128 Type *EltTy = nullptr;
2129 if (ParseType(EltTy)) return true;
2131 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2132 "expected end of sequential type"))
2137 return Error(SizeLoc, "zero element vector is illegal");
2138 if ((unsigned)Size != Size)
2139 return Error(SizeLoc, "size too large for vector");
2140 if (!VectorType::isValidElementType(EltTy))
2141 return Error(TypeLoc, "invalid vector element type");
2142 Result = VectorType::get(EltTy, unsigned(Size));
2144 if (!ArrayType::isValidElementType(EltTy))
2145 return Error(TypeLoc, "invalid array element type");
2146 Result = ArrayType::get(EltTy, Size);
2151 //===----------------------------------------------------------------------===//
2152 // Function Semantic Analysis.
2153 //===----------------------------------------------------------------------===//
2155 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2157 : P(p), F(f), FunctionNumber(functionNumber) {
2159 // Insert unnamed arguments into the NumberedVals list.
2160 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2163 NumberedVals.push_back(AI);
2166 LLParser::PerFunctionState::~PerFunctionState() {
2167 // If there were any forward referenced non-basicblock values, delete them.
2168 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2169 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2170 if (!isa<BasicBlock>(I->second.first)) {
2171 I->second.first->replaceAllUsesWith(
2172 UndefValue::get(I->second.first->getType()));
2173 delete I->second.first;
2174 I->second.first = nullptr;
2177 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2178 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2179 if (!isa<BasicBlock>(I->second.first)) {
2180 I->second.first->replaceAllUsesWith(
2181 UndefValue::get(I->second.first->getType()));
2182 delete I->second.first;
2183 I->second.first = nullptr;
2187 bool LLParser::PerFunctionState::FinishFunction() {
2188 if (!ForwardRefVals.empty())
2189 return P.Error(ForwardRefVals.begin()->second.second,
2190 "use of undefined value '%" + ForwardRefVals.begin()->first +
2192 if (!ForwardRefValIDs.empty())
2193 return P.Error(ForwardRefValIDs.begin()->second.second,
2194 "use of undefined value '%" +
2195 Twine(ForwardRefValIDs.begin()->first) + "'");
2200 /// GetVal - Get a value with the specified name or ID, creating a
2201 /// forward reference record if needed. This can return null if the value
2202 /// exists but does not have the right type.
2203 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2204 Type *Ty, LocTy Loc) {
2205 // Look this name up in the normal function symbol table.
2206 Value *Val = F.getValueSymbolTable().lookup(Name);
2208 // If this is a forward reference for the value, see if we already created a
2209 // forward ref record.
2211 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2212 I = ForwardRefVals.find(Name);
2213 if (I != ForwardRefVals.end())
2214 Val = I->second.first;
2217 // If we have the value in the symbol table or fwd-ref table, return it.
2219 if (Val->getType() == Ty) return Val;
2220 if (Ty->isLabelTy())
2221 P.Error(Loc, "'%" + Name + "' is not a basic block");
2223 P.Error(Loc, "'%" + Name + "' defined with type '" +
2224 getTypeString(Val->getType()) + "'");
2228 // Don't make placeholders with invalid type.
2229 if (!Ty->isFirstClassType()) {
2230 P.Error(Loc, "invalid use of a non-first-class type");
2234 // Otherwise, create a new forward reference for this value and remember it.
2236 if (Ty->isLabelTy())
2237 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2239 FwdVal = new Argument(Ty, Name);
2241 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2245 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2247 // Look this name up in the normal function symbol table.
2248 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2250 // If this is a forward reference for the value, see if we already created a
2251 // forward ref record.
2253 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2254 I = ForwardRefValIDs.find(ID);
2255 if (I != ForwardRefValIDs.end())
2256 Val = I->second.first;
2259 // If we have the value in the symbol table or fwd-ref table, return it.
2261 if (Val->getType() == Ty) return Val;
2262 if (Ty->isLabelTy())
2263 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2265 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2266 getTypeString(Val->getType()) + "'");
2270 if (!Ty->isFirstClassType()) {
2271 P.Error(Loc, "invalid use of a non-first-class type");
2275 // Otherwise, create a new forward reference for this value and remember it.
2277 if (Ty->isLabelTy())
2278 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2280 FwdVal = new Argument(Ty);
2282 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2286 /// SetInstName - After an instruction is parsed and inserted into its
2287 /// basic block, this installs its name.
2288 bool LLParser::PerFunctionState::SetInstName(int NameID,
2289 const std::string &NameStr,
2290 LocTy NameLoc, Instruction *Inst) {
2291 // If this instruction has void type, it cannot have a name or ID specified.
2292 if (Inst->getType()->isVoidTy()) {
2293 if (NameID != -1 || !NameStr.empty())
2294 return P.Error(NameLoc, "instructions returning void cannot have a name");
2298 // If this was a numbered instruction, verify that the instruction is the
2299 // expected value and resolve any forward references.
2300 if (NameStr.empty()) {
2301 // If neither a name nor an ID was specified, just use the next ID.
2303 NameID = NumberedVals.size();
2305 if (unsigned(NameID) != NumberedVals.size())
2306 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2307 Twine(NumberedVals.size()) + "'");
2309 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2310 ForwardRefValIDs.find(NameID);
2311 if (FI != ForwardRefValIDs.end()) {
2312 if (FI->second.first->getType() != Inst->getType())
2313 return P.Error(NameLoc, "instruction forward referenced with type '" +
2314 getTypeString(FI->second.first->getType()) + "'");
2315 FI->second.first->replaceAllUsesWith(Inst);
2316 delete FI->second.first;
2317 ForwardRefValIDs.erase(FI);
2320 NumberedVals.push_back(Inst);
2324 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2325 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2326 FI = ForwardRefVals.find(NameStr);
2327 if (FI != ForwardRefVals.end()) {
2328 if (FI->second.first->getType() != Inst->getType())
2329 return P.Error(NameLoc, "instruction forward referenced with type '" +
2330 getTypeString(FI->second.first->getType()) + "'");
2331 FI->second.first->replaceAllUsesWith(Inst);
2332 delete FI->second.first;
2333 ForwardRefVals.erase(FI);
2336 // Set the name on the instruction.
2337 Inst->setName(NameStr);
2339 if (Inst->getName() != NameStr)
2340 return P.Error(NameLoc, "multiple definition of local value named '" +
2345 /// GetBB - Get a basic block with the specified name or ID, creating a
2346 /// forward reference record if needed.
2347 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2349 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2350 Type::getLabelTy(F.getContext()), Loc));
2353 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2354 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2355 Type::getLabelTy(F.getContext()), Loc));
2358 /// DefineBB - Define the specified basic block, which is either named or
2359 /// unnamed. If there is an error, this returns null otherwise it returns
2360 /// the block being defined.
2361 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2365 BB = GetBB(NumberedVals.size(), Loc);
2367 BB = GetBB(Name, Loc);
2368 if (!BB) return nullptr; // Already diagnosed error.
2370 // Move the block to the end of the function. Forward ref'd blocks are
2371 // inserted wherever they happen to be referenced.
2372 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2374 // Remove the block from forward ref sets.
2376 ForwardRefValIDs.erase(NumberedVals.size());
2377 NumberedVals.push_back(BB);
2379 // BB forward references are already in the function symbol table.
2380 ForwardRefVals.erase(Name);
2386 //===----------------------------------------------------------------------===//
2388 //===----------------------------------------------------------------------===//
2390 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2391 /// type implied. For example, if we parse "4" we don't know what integer type
2392 /// it has. The value will later be combined with its type and checked for
2393 /// sanity. PFS is used to convert function-local operands of metadata (since
2394 /// metadata operands are not just parsed here but also converted to values).
2395 /// PFS can be null when we are not parsing metadata values inside a function.
2396 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2397 ID.Loc = Lex.getLoc();
2398 switch (Lex.getKind()) {
2399 default: return TokError("expected value token");
2400 case lltok::GlobalID: // @42
2401 ID.UIntVal = Lex.getUIntVal();
2402 ID.Kind = ValID::t_GlobalID;
2404 case lltok::GlobalVar: // @foo
2405 ID.StrVal = Lex.getStrVal();
2406 ID.Kind = ValID::t_GlobalName;
2408 case lltok::LocalVarID: // %42
2409 ID.UIntVal = Lex.getUIntVal();
2410 ID.Kind = ValID::t_LocalID;
2412 case lltok::LocalVar: // %foo
2413 ID.StrVal = Lex.getStrVal();
2414 ID.Kind = ValID::t_LocalName;
2417 ID.APSIntVal = Lex.getAPSIntVal();
2418 ID.Kind = ValID::t_APSInt;
2420 case lltok::APFloat:
2421 ID.APFloatVal = Lex.getAPFloatVal();
2422 ID.Kind = ValID::t_APFloat;
2424 case lltok::kw_true:
2425 ID.ConstantVal = ConstantInt::getTrue(Context);
2426 ID.Kind = ValID::t_Constant;
2428 case lltok::kw_false:
2429 ID.ConstantVal = ConstantInt::getFalse(Context);
2430 ID.Kind = ValID::t_Constant;
2432 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2433 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2434 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2436 case lltok::lbrace: {
2437 // ValID ::= '{' ConstVector '}'
2439 SmallVector<Constant*, 16> Elts;
2440 if (ParseGlobalValueVector(Elts) ||
2441 ParseToken(lltok::rbrace, "expected end of struct constant"))
2444 ID.ConstantStructElts = new Constant*[Elts.size()];
2445 ID.UIntVal = Elts.size();
2446 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2447 ID.Kind = ValID::t_ConstantStruct;
2451 // ValID ::= '<' ConstVector '>' --> Vector.
2452 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2454 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2456 SmallVector<Constant*, 16> Elts;
2457 LocTy FirstEltLoc = Lex.getLoc();
2458 if (ParseGlobalValueVector(Elts) ||
2460 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2461 ParseToken(lltok::greater, "expected end of constant"))
2464 if (isPackedStruct) {
2465 ID.ConstantStructElts = new Constant*[Elts.size()];
2466 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2467 ID.UIntVal = Elts.size();
2468 ID.Kind = ValID::t_PackedConstantStruct;
2473 return Error(ID.Loc, "constant vector must not be empty");
2475 if (!Elts[0]->getType()->isIntegerTy() &&
2476 !Elts[0]->getType()->isFloatingPointTy() &&
2477 !Elts[0]->getType()->isPointerTy())
2478 return Error(FirstEltLoc,
2479 "vector elements must have integer, pointer or floating point type");
2481 // Verify that all the vector elements have the same type.
2482 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2483 if (Elts[i]->getType() != Elts[0]->getType())
2484 return Error(FirstEltLoc,
2485 "vector element #" + Twine(i) +
2486 " is not of type '" + getTypeString(Elts[0]->getType()));
2488 ID.ConstantVal = ConstantVector::get(Elts);
2489 ID.Kind = ValID::t_Constant;
2492 case lltok::lsquare: { // Array Constant
2494 SmallVector<Constant*, 16> Elts;
2495 LocTy FirstEltLoc = Lex.getLoc();
2496 if (ParseGlobalValueVector(Elts) ||
2497 ParseToken(lltok::rsquare, "expected end of array constant"))
2500 // Handle empty element.
2502 // Use undef instead of an array because it's inconvenient to determine
2503 // the element type at this point, there being no elements to examine.
2504 ID.Kind = ValID::t_EmptyArray;
2508 if (!Elts[0]->getType()->isFirstClassType())
2509 return Error(FirstEltLoc, "invalid array element type: " +
2510 getTypeString(Elts[0]->getType()));
2512 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2514 // Verify all elements are correct type!
2515 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2516 if (Elts[i]->getType() != Elts[0]->getType())
2517 return Error(FirstEltLoc,
2518 "array element #" + Twine(i) +
2519 " is not of type '" + getTypeString(Elts[0]->getType()));
2522 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2523 ID.Kind = ValID::t_Constant;
2526 case lltok::kw_c: // c "foo"
2528 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2530 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2531 ID.Kind = ValID::t_Constant;
2534 case lltok::kw_asm: {
2535 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2537 bool HasSideEffect, AlignStack, AsmDialect;
2539 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2540 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2541 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2542 ParseStringConstant(ID.StrVal) ||
2543 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2544 ParseToken(lltok::StringConstant, "expected constraint string"))
2546 ID.StrVal2 = Lex.getStrVal();
2547 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2548 (unsigned(AsmDialect)<<2);
2549 ID.Kind = ValID::t_InlineAsm;
2553 case lltok::kw_blockaddress: {
2554 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2559 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2561 ParseToken(lltok::comma, "expected comma in block address expression")||
2562 ParseValID(Label) ||
2563 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2566 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2567 return Error(Fn.Loc, "expected function name in blockaddress");
2568 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2569 return Error(Label.Loc, "expected basic block name in blockaddress");
2571 // Try to find the function (but skip it if it's forward-referenced).
2572 GlobalValue *GV = nullptr;
2573 if (Fn.Kind == ValID::t_GlobalID) {
2574 if (Fn.UIntVal < NumberedVals.size())
2575 GV = NumberedVals[Fn.UIntVal];
2576 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2577 GV = M->getNamedValue(Fn.StrVal);
2579 Function *F = nullptr;
2581 // Confirm that it's actually a function with a definition.
2582 if (!isa<Function>(GV))
2583 return Error(Fn.Loc, "expected function name in blockaddress");
2584 F = cast<Function>(GV);
2585 if (F->isDeclaration())
2586 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2590 // Make a global variable as a placeholder for this reference.
2591 GlobalValue *&FwdRef =
2592 ForwardRefBlockAddresses.insert(std::make_pair(
2594 std::map<ValID, GlobalValue *>()))
2595 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2598 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2599 GlobalValue::InternalLinkage, nullptr, "");
2600 ID.ConstantVal = FwdRef;
2601 ID.Kind = ValID::t_Constant;
2605 // We found the function; now find the basic block. Don't use PFS, since we
2606 // might be inside a constant expression.
2608 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2609 if (Label.Kind == ValID::t_LocalID)
2610 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2612 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2614 return Error(Label.Loc, "referenced value is not a basic block");
2616 if (Label.Kind == ValID::t_LocalID)
2617 return Error(Label.Loc, "cannot take address of numeric label after "
2618 "the function is defined");
2619 BB = dyn_cast_or_null<BasicBlock>(
2620 F->getValueSymbolTable().lookup(Label.StrVal));
2622 return Error(Label.Loc, "referenced value is not a basic block");
2625 ID.ConstantVal = BlockAddress::get(F, BB);
2626 ID.Kind = ValID::t_Constant;
2630 case lltok::kw_trunc:
2631 case lltok::kw_zext:
2632 case lltok::kw_sext:
2633 case lltok::kw_fptrunc:
2634 case lltok::kw_fpext:
2635 case lltok::kw_bitcast:
2636 case lltok::kw_addrspacecast:
2637 case lltok::kw_uitofp:
2638 case lltok::kw_sitofp:
2639 case lltok::kw_fptoui:
2640 case lltok::kw_fptosi:
2641 case lltok::kw_inttoptr:
2642 case lltok::kw_ptrtoint: {
2643 unsigned Opc = Lex.getUIntVal();
2644 Type *DestTy = nullptr;
2647 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2648 ParseGlobalTypeAndValue(SrcVal) ||
2649 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2650 ParseType(DestTy) ||
2651 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2653 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2654 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2655 getTypeString(SrcVal->getType()) + "' to '" +
2656 getTypeString(DestTy) + "'");
2657 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2659 ID.Kind = ValID::t_Constant;
2662 case lltok::kw_extractvalue: {
2665 SmallVector<unsigned, 4> Indices;
2666 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2667 ParseGlobalTypeAndValue(Val) ||
2668 ParseIndexList(Indices) ||
2669 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2672 if (!Val->getType()->isAggregateType())
2673 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2674 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2675 return Error(ID.Loc, "invalid indices for extractvalue");
2676 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2677 ID.Kind = ValID::t_Constant;
2680 case lltok::kw_insertvalue: {
2682 Constant *Val0, *Val1;
2683 SmallVector<unsigned, 4> Indices;
2684 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2685 ParseGlobalTypeAndValue(Val0) ||
2686 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2687 ParseGlobalTypeAndValue(Val1) ||
2688 ParseIndexList(Indices) ||
2689 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2691 if (!Val0->getType()->isAggregateType())
2692 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2694 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2696 return Error(ID.Loc, "invalid indices for insertvalue");
2697 if (IndexedType != Val1->getType())
2698 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2699 getTypeString(Val1->getType()) +
2700 "' instead of '" + getTypeString(IndexedType) +
2702 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2703 ID.Kind = ValID::t_Constant;
2706 case lltok::kw_icmp:
2707 case lltok::kw_fcmp: {
2708 unsigned PredVal, Opc = Lex.getUIntVal();
2709 Constant *Val0, *Val1;
2711 if (ParseCmpPredicate(PredVal, Opc) ||
2712 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2713 ParseGlobalTypeAndValue(Val0) ||
2714 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2715 ParseGlobalTypeAndValue(Val1) ||
2716 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2719 if (Val0->getType() != Val1->getType())
2720 return Error(ID.Loc, "compare operands must have the same type");
2722 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2724 if (Opc == Instruction::FCmp) {
2725 if (!Val0->getType()->isFPOrFPVectorTy())
2726 return Error(ID.Loc, "fcmp requires floating point operands");
2727 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2729 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2730 if (!Val0->getType()->isIntOrIntVectorTy() &&
2731 !Val0->getType()->getScalarType()->isPointerTy())
2732 return Error(ID.Loc, "icmp requires pointer or integer operands");
2733 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2735 ID.Kind = ValID::t_Constant;
2739 // Binary Operators.
2741 case lltok::kw_fadd:
2743 case lltok::kw_fsub:
2745 case lltok::kw_fmul:
2746 case lltok::kw_udiv:
2747 case lltok::kw_sdiv:
2748 case lltok::kw_fdiv:
2749 case lltok::kw_urem:
2750 case lltok::kw_srem:
2751 case lltok::kw_frem:
2753 case lltok::kw_lshr:
2754 case lltok::kw_ashr: {
2758 unsigned Opc = Lex.getUIntVal();
2759 Constant *Val0, *Val1;
2761 LocTy ModifierLoc = Lex.getLoc();
2762 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2763 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2764 if (EatIfPresent(lltok::kw_nuw))
2766 if (EatIfPresent(lltok::kw_nsw)) {
2768 if (EatIfPresent(lltok::kw_nuw))
2771 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2772 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2773 if (EatIfPresent(lltok::kw_exact))
2776 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2777 ParseGlobalTypeAndValue(Val0) ||
2778 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2779 ParseGlobalTypeAndValue(Val1) ||
2780 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2782 if (Val0->getType() != Val1->getType())
2783 return Error(ID.Loc, "operands of constexpr must have same type");
2784 if (!Val0->getType()->isIntOrIntVectorTy()) {
2786 return Error(ModifierLoc, "nuw only applies to integer operations");
2788 return Error(ModifierLoc, "nsw only applies to integer operations");
2790 // Check that the type is valid for the operator.
2792 case Instruction::Add:
2793 case Instruction::Sub:
2794 case Instruction::Mul:
2795 case Instruction::UDiv:
2796 case Instruction::SDiv:
2797 case Instruction::URem:
2798 case Instruction::SRem:
2799 case Instruction::Shl:
2800 case Instruction::AShr:
2801 case Instruction::LShr:
2802 if (!Val0->getType()->isIntOrIntVectorTy())
2803 return Error(ID.Loc, "constexpr requires integer operands");
2805 case Instruction::FAdd:
2806 case Instruction::FSub:
2807 case Instruction::FMul:
2808 case Instruction::FDiv:
2809 case Instruction::FRem:
2810 if (!Val0->getType()->isFPOrFPVectorTy())
2811 return Error(ID.Loc, "constexpr requires fp operands");
2813 default: llvm_unreachable("Unknown binary operator!");
2816 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2817 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2818 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2819 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2821 ID.Kind = ValID::t_Constant;
2825 // Logical Operations
2828 case lltok::kw_xor: {
2829 unsigned Opc = Lex.getUIntVal();
2830 Constant *Val0, *Val1;
2832 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2833 ParseGlobalTypeAndValue(Val0) ||
2834 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2835 ParseGlobalTypeAndValue(Val1) ||
2836 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2838 if (Val0->getType() != Val1->getType())
2839 return Error(ID.Loc, "operands of constexpr must have same type");
2840 if (!Val0->getType()->isIntOrIntVectorTy())
2841 return Error(ID.Loc,
2842 "constexpr requires integer or integer vector operands");
2843 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2844 ID.Kind = ValID::t_Constant;
2848 case lltok::kw_getelementptr:
2849 case lltok::kw_shufflevector:
2850 case lltok::kw_insertelement:
2851 case lltok::kw_extractelement:
2852 case lltok::kw_select: {
2853 unsigned Opc = Lex.getUIntVal();
2854 SmallVector<Constant*, 16> Elts;
2855 bool InBounds = false;
2859 if (Opc == Instruction::GetElementPtr)
2860 InBounds = EatIfPresent(lltok::kw_inbounds);
2862 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2865 LocTy ExplicitTypeLoc = Lex.getLoc();
2866 if (Opc == Instruction::GetElementPtr) {
2867 if (ParseType(Ty) ||
2868 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2872 if (ParseGlobalValueVector(Elts) ||
2873 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2876 if (Opc == Instruction::GetElementPtr) {
2877 if (Elts.size() == 0 ||
2878 !Elts[0]->getType()->getScalarType()->isPointerTy())
2879 return Error(ID.Loc, "base of getelementptr must be a pointer");
2881 Type *BaseType = Elts[0]->getType();
2882 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2883 if (Ty != BasePointerType->getElementType())
2886 "explicit pointee type doesn't match operand's pointee type");
2888 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2889 for (Constant *Val : Indices) {
2890 Type *ValTy = Val->getType();
2891 if (!ValTy->getScalarType()->isIntegerTy())
2892 return Error(ID.Loc, "getelementptr index must be an integer");
2893 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2894 return Error(ID.Loc, "getelementptr index type missmatch");
2895 if (ValTy->isVectorTy()) {
2896 unsigned ValNumEl = ValTy->getVectorNumElements();
2897 unsigned PtrNumEl = BaseType->getVectorNumElements();
2898 if (ValNumEl != PtrNumEl)
2901 "getelementptr vector index has a wrong number of elements");
2905 SmallPtrSet<const Type*, 4> Visited;
2906 if (!Indices.empty() && !Ty->isSized(&Visited))
2907 return Error(ID.Loc, "base element of getelementptr must be sized");
2909 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2910 return Error(ID.Loc, "invalid getelementptr indices");
2912 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2913 } else if (Opc == Instruction::Select) {
2914 if (Elts.size() != 3)
2915 return Error(ID.Loc, "expected three operands to select");
2916 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2918 return Error(ID.Loc, Reason);
2919 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2920 } else if (Opc == Instruction::ShuffleVector) {
2921 if (Elts.size() != 3)
2922 return Error(ID.Loc, "expected three operands to shufflevector");
2923 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2924 return Error(ID.Loc, "invalid operands to shufflevector");
2926 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2927 } else if (Opc == Instruction::ExtractElement) {
2928 if (Elts.size() != 2)
2929 return Error(ID.Loc, "expected two operands to extractelement");
2930 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2931 return Error(ID.Loc, "invalid extractelement operands");
2932 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2934 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2935 if (Elts.size() != 3)
2936 return Error(ID.Loc, "expected three operands to insertelement");
2937 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2938 return Error(ID.Loc, "invalid insertelement operands");
2940 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2943 ID.Kind = ValID::t_Constant;
2952 /// ParseGlobalValue - Parse a global value with the specified type.
2953 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2957 bool Parsed = ParseValID(ID) ||
2958 ConvertValIDToValue(Ty, ID, V, nullptr);
2959 if (V && !(C = dyn_cast<Constant>(V)))
2960 return Error(ID.Loc, "global values must be constants");
2964 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2966 return ParseType(Ty) ||
2967 ParseGlobalValue(Ty, V);
2970 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2973 LocTy KwLoc = Lex.getLoc();
2974 if (!EatIfPresent(lltok::kw_comdat))
2977 if (EatIfPresent(lltok::lparen)) {
2978 if (Lex.getKind() != lltok::ComdatVar)
2979 return TokError("expected comdat variable");
2980 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2982 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2985 if (GlobalName.empty())
2986 return TokError("comdat cannot be unnamed");
2987 C = getComdat(GlobalName, KwLoc);
2993 /// ParseGlobalValueVector
2995 /// ::= TypeAndValue (',' TypeAndValue)*
2996 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2998 if (Lex.getKind() == lltok::rbrace ||
2999 Lex.getKind() == lltok::rsquare ||
3000 Lex.getKind() == lltok::greater ||
3001 Lex.getKind() == lltok::rparen)
3005 if (ParseGlobalTypeAndValue(C)) return true;
3008 while (EatIfPresent(lltok::comma)) {
3009 if (ParseGlobalTypeAndValue(C)) return true;
3016 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3017 SmallVector<Metadata *, 16> Elts;
3018 if (ParseMDNodeVector(Elts))
3021 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3028 /// ::= !DILocation(...)
3029 bool LLParser::ParseMDNode(MDNode *&N) {
3030 if (Lex.getKind() == lltok::MetadataVar)
3031 return ParseSpecializedMDNode(N);
3033 return ParseToken(lltok::exclaim, "expected '!' here") ||
3037 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3039 if (Lex.getKind() == lltok::lbrace)
3040 return ParseMDTuple(N);
3043 return ParseMDNodeID(N);
3048 /// Structure to represent an optional metadata field.
3049 template <class FieldTy> struct MDFieldImpl {
3050 typedef MDFieldImpl ImplTy;
3054 void assign(FieldTy Val) {
3056 this->Val = std::move(Val);
3059 explicit MDFieldImpl(FieldTy Default)
3060 : Val(std::move(Default)), Seen(false) {}
3063 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3066 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3067 : ImplTy(Default), Max(Max) {}
3069 struct LineField : public MDUnsignedField {
3070 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3072 struct ColumnField : public MDUnsignedField {
3073 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3075 struct DwarfTagField : public MDUnsignedField {
3076 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3077 DwarfTagField(dwarf::Tag DefaultTag)
3078 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3080 struct DwarfAttEncodingField : public MDUnsignedField {
3081 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3083 struct DwarfVirtualityField : public MDUnsignedField {
3084 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3086 struct DwarfLangField : public MDUnsignedField {
3087 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3090 struct DIFlagField : public MDUnsignedField {
3091 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3094 struct MDSignedField : public MDFieldImpl<int64_t> {
3098 MDSignedField(int64_t Default = 0)
3099 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3100 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3101 : ImplTy(Default), Min(Min), Max(Max) {}
3104 struct MDBoolField : public MDFieldImpl<bool> {
3105 MDBoolField(bool Default = false) : ImplTy(Default) {}
3107 struct MDField : public MDFieldImpl<Metadata *> {
3110 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3112 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3113 MDConstant() : ImplTy(nullptr) {}
3115 struct MDStringField : public MDFieldImpl<MDString *> {
3117 MDStringField(bool AllowEmpty = true)
3118 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3120 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3121 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3129 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3130 MDUnsignedField &Result) {
3131 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3132 return TokError("expected unsigned integer");
3134 auto &U = Lex.getAPSIntVal();
3135 if (U.ugt(Result.Max))
3136 return TokError("value for '" + Name + "' too large, limit is " +
3138 Result.assign(U.getZExtValue());
3139 assert(Result.Val <= Result.Max && "Expected value in range");
3145 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3146 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3149 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3150 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3154 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3155 if (Lex.getKind() == lltok::APSInt)
3156 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3158 if (Lex.getKind() != lltok::DwarfTag)
3159 return TokError("expected DWARF tag");
3161 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3162 if (Tag == dwarf::DW_TAG_invalid)
3163 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3164 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3172 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3173 DwarfVirtualityField &Result) {
3174 if (Lex.getKind() == lltok::APSInt)
3175 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3177 if (Lex.getKind() != lltok::DwarfVirtuality)
3178 return TokError("expected DWARF virtuality code");
3180 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3182 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3183 Lex.getStrVal() + "'");
3184 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3185 Result.assign(Virtuality);
3191 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3192 if (Lex.getKind() == lltok::APSInt)
3193 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3195 if (Lex.getKind() != lltok::DwarfLang)
3196 return TokError("expected DWARF language");
3198 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3200 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3202 assert(Lang <= Result.Max && "Expected valid DWARF language");
3203 Result.assign(Lang);
3209 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3210 DwarfAttEncodingField &Result) {
3211 if (Lex.getKind() == lltok::APSInt)
3212 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3214 if (Lex.getKind() != lltok::DwarfAttEncoding)
3215 return TokError("expected DWARF type attribute encoding");
3217 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3219 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3220 Lex.getStrVal() + "'");
3221 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3222 Result.assign(Encoding);
3229 /// ::= DIFlagVector
3230 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3232 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3233 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3235 // Parser for a single flag.
3236 auto parseFlag = [&](unsigned &Val) {
3237 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3238 return ParseUInt32(Val);
3240 if (Lex.getKind() != lltok::DIFlag)
3241 return TokError("expected debug info flag");
3243 Val = DINode::getFlag(Lex.getStrVal());
3245 return TokError(Twine("invalid debug info flag flag '") +
3246 Lex.getStrVal() + "'");
3251 // Parse the flags and combine them together.
3252 unsigned Combined = 0;
3258 } while (EatIfPresent(lltok::bar));
3260 Result.assign(Combined);
3265 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3266 MDSignedField &Result) {
3267 if (Lex.getKind() != lltok::APSInt)
3268 return TokError("expected signed integer");
3270 auto &S = Lex.getAPSIntVal();
3272 return TokError("value for '" + Name + "' too small, limit is " +
3275 return TokError("value for '" + Name + "' too large, limit is " +
3277 Result.assign(S.getExtValue());
3278 assert(Result.Val >= Result.Min && "Expected value in range");
3279 assert(Result.Val <= Result.Max && "Expected value in range");
3285 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3286 switch (Lex.getKind()) {
3288 return TokError("expected 'true' or 'false'");
3289 case lltok::kw_true:
3290 Result.assign(true);
3292 case lltok::kw_false:
3293 Result.assign(false);
3301 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3302 if (Lex.getKind() == lltok::kw_null) {
3303 if (!Result.AllowNull)
3304 return TokError("'" + Name + "' cannot be null");
3306 Result.assign(nullptr);
3311 if (ParseMetadata(MD, nullptr))
3319 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3321 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3324 Result.assign(cast<ConstantAsMetadata>(MD));
3329 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3330 LocTy ValueLoc = Lex.getLoc();
3332 if (ParseStringConstant(S))
3335 if (!Result.AllowEmpty && S.empty())
3336 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3338 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3343 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3344 SmallVector<Metadata *, 4> MDs;
3345 if (ParseMDNodeVector(MDs))
3348 Result.assign(std::move(MDs));
3352 } // end namespace llvm
3354 template <class ParserTy>
3355 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3357 if (Lex.getKind() != lltok::LabelStr)
3358 return TokError("expected field label here");
3362 } while (EatIfPresent(lltok::comma));
3367 template <class ParserTy>
3368 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3369 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3372 if (ParseToken(lltok::lparen, "expected '(' here"))
3374 if (Lex.getKind() != lltok::rparen)
3375 if (ParseMDFieldsImplBody(parseField))
3378 ClosingLoc = Lex.getLoc();
3379 return ParseToken(lltok::rparen, "expected ')' here");
3382 template <class FieldTy>
3383 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3385 return TokError("field '" + Name + "' cannot be specified more than once");
3387 LocTy Loc = Lex.getLoc();
3389 return ParseMDField(Loc, Name, Result);
3392 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3393 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3395 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3396 if (Lex.getStrVal() == #CLASS) \
3397 return Parse##CLASS(N, IsDistinct);
3398 #include "llvm/IR/Metadata.def"
3400 return TokError("expected metadata type");
3403 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3404 #define NOP_FIELD(NAME, TYPE, INIT)
3405 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3407 return Error(ClosingLoc, "missing required field '" #NAME "'");
3408 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3409 if (Lex.getStrVal() == #NAME) \
3410 return ParseMDField(#NAME, NAME);
3411 #define PARSE_MD_FIELDS() \
3412 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3415 if (ParseMDFieldsImpl([&]() -> bool { \
3416 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3417 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3420 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3422 #define GET_OR_DISTINCT(CLASS, ARGS) \
3423 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3425 /// ParseDILocationFields:
3426 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3427 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3428 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3429 OPTIONAL(line, LineField, ); \
3430 OPTIONAL(column, ColumnField, ); \
3431 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3432 OPTIONAL(inlinedAt, MDField, );
3434 #undef VISIT_MD_FIELDS
3436 Result = GET_OR_DISTINCT(
3437 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3441 /// ParseGenericDINode:
3442 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3443 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3444 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3445 REQUIRED(tag, DwarfTagField, ); \
3446 OPTIONAL(header, MDStringField, ); \
3447 OPTIONAL(operands, MDFieldList, );
3449 #undef VISIT_MD_FIELDS
3451 Result = GET_OR_DISTINCT(GenericDINode,
3452 (Context, tag.Val, header.Val, operands.Val));
3456 /// ParseDISubrange:
3457 /// ::= !DISubrange(count: 30, lowerBound: 2)
3458 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3459 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3460 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3461 OPTIONAL(lowerBound, MDSignedField, );
3463 #undef VISIT_MD_FIELDS
3465 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3469 /// ParseDIEnumerator:
3470 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3471 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3472 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3473 REQUIRED(name, MDStringField, ); \
3474 REQUIRED(value, MDSignedField, );
3476 #undef VISIT_MD_FIELDS
3478 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3482 /// ParseDIBasicType:
3483 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3484 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3485 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3486 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3487 OPTIONAL(name, MDStringField, ); \
3488 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3489 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3490 OPTIONAL(encoding, DwarfAttEncodingField, );
3492 #undef VISIT_MD_FIELDS
3494 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3495 align.Val, encoding.Val));
3499 /// ParseDIDerivedType:
3500 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3501 /// line: 7, scope: !1, baseType: !2, size: 32,
3502 /// align: 32, offset: 0, flags: 0, extraData: !3)
3503 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3504 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3505 REQUIRED(tag, DwarfTagField, ); \
3506 OPTIONAL(name, MDStringField, ); \
3507 OPTIONAL(file, MDField, ); \
3508 OPTIONAL(line, LineField, ); \
3509 OPTIONAL(scope, MDField, ); \
3510 REQUIRED(baseType, MDField, ); \
3511 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3512 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3513 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3514 OPTIONAL(flags, DIFlagField, ); \
3515 OPTIONAL(extraData, MDField, );
3517 #undef VISIT_MD_FIELDS
3519 Result = GET_OR_DISTINCT(DIDerivedType,
3520 (Context, tag.Val, name.Val, file.Val, line.Val,
3521 scope.Val, baseType.Val, size.Val, align.Val,
3522 offset.Val, flags.Val, extraData.Val));
3526 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3527 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3528 REQUIRED(tag, DwarfTagField, ); \
3529 OPTIONAL(name, MDStringField, ); \
3530 OPTIONAL(file, MDField, ); \
3531 OPTIONAL(line, LineField, ); \
3532 OPTIONAL(scope, MDField, ); \
3533 OPTIONAL(baseType, MDField, ); \
3534 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3535 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3536 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3537 OPTIONAL(flags, DIFlagField, ); \
3538 OPTIONAL(elements, MDField, ); \
3539 OPTIONAL(runtimeLang, DwarfLangField, ); \
3540 OPTIONAL(vtableHolder, MDField, ); \
3541 OPTIONAL(templateParams, MDField, ); \
3542 OPTIONAL(identifier, MDStringField, );
3544 #undef VISIT_MD_FIELDS
3546 Result = GET_OR_DISTINCT(
3548 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3549 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3550 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3554 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3555 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3556 OPTIONAL(flags, DIFlagField, ); \
3557 REQUIRED(types, MDField, );
3559 #undef VISIT_MD_FIELDS
3561 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3565 /// ParseDIFileType:
3566 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3567 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3568 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3569 REQUIRED(filename, MDStringField, ); \
3570 REQUIRED(directory, MDStringField, );
3572 #undef VISIT_MD_FIELDS
3574 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3578 /// ParseDICompileUnit:
3579 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3580 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3581 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3582 /// enums: !1, retainedTypes: !2, subprograms: !3,
3583 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3584 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3585 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3586 REQUIRED(language, DwarfLangField, ); \
3587 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3588 OPTIONAL(producer, MDStringField, ); \
3589 OPTIONAL(isOptimized, MDBoolField, ); \
3590 OPTIONAL(flags, MDStringField, ); \
3591 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3592 OPTIONAL(splitDebugFilename, MDStringField, ); \
3593 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3594 OPTIONAL(enums, MDField, ); \
3595 OPTIONAL(retainedTypes, MDField, ); \
3596 OPTIONAL(subprograms, MDField, ); \
3597 OPTIONAL(globals, MDField, ); \
3598 OPTIONAL(imports, MDField, ); \
3599 OPTIONAL(dwoId, MDUnsignedField, );
3601 #undef VISIT_MD_FIELDS
3603 Result = GET_OR_DISTINCT(DICompileUnit,
3604 (Context, language.Val, file.Val, producer.Val,
3605 isOptimized.Val, flags.Val, runtimeVersion.Val,
3606 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3607 retainedTypes.Val, subprograms.Val, globals.Val,
3608 imports.Val, dwoId.Val));
3612 /// ParseDISubprogram:
3613 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3614 /// file: !1, line: 7, type: !2, isLocal: false,
3615 /// isDefinition: true, scopeLine: 8, containingType: !3,
3616 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3617 /// virtualIndex: 10, flags: 11,
3618 /// isOptimized: false, function: void ()* @_Z3foov,
3619 /// templateParams: !4, declaration: !5, variables: !6)
3620 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3621 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3622 OPTIONAL(scope, MDField, ); \
3623 OPTIONAL(name, MDStringField, ); \
3624 OPTIONAL(linkageName, MDStringField, ); \
3625 OPTIONAL(file, MDField, ); \
3626 OPTIONAL(line, LineField, ); \
3627 OPTIONAL(type, MDField, ); \
3628 OPTIONAL(isLocal, MDBoolField, ); \
3629 OPTIONAL(isDefinition, MDBoolField, (true)); \
3630 OPTIONAL(scopeLine, LineField, ); \
3631 OPTIONAL(containingType, MDField, ); \
3632 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3633 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3634 OPTIONAL(flags, DIFlagField, ); \
3635 OPTIONAL(isOptimized, MDBoolField, ); \
3636 OPTIONAL(function, MDConstant, ); \
3637 OPTIONAL(templateParams, MDField, ); \
3638 OPTIONAL(declaration, MDField, ); \
3639 OPTIONAL(variables, MDField, );
3641 #undef VISIT_MD_FIELDS
3643 Result = GET_OR_DISTINCT(
3644 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3645 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3646 scopeLine.Val, containingType.Val, virtuality.Val,
3647 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3648 templateParams.Val, declaration.Val, variables.Val));
3652 /// ParseDILexicalBlock:
3653 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3654 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3655 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3656 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3657 OPTIONAL(file, MDField, ); \
3658 OPTIONAL(line, LineField, ); \
3659 OPTIONAL(column, ColumnField, );
3661 #undef VISIT_MD_FIELDS
3663 Result = GET_OR_DISTINCT(
3664 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3668 /// ParseDILexicalBlockFile:
3669 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3670 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3671 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3672 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3673 OPTIONAL(file, MDField, ); \
3674 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3676 #undef VISIT_MD_FIELDS
3678 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3679 (Context, scope.Val, file.Val, discriminator.Val));
3683 /// ParseDINamespace:
3684 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3685 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3686 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3687 REQUIRED(scope, MDField, ); \
3688 OPTIONAL(file, MDField, ); \
3689 OPTIONAL(name, MDStringField, ); \
3690 OPTIONAL(line, LineField, );
3692 #undef VISIT_MD_FIELDS
3694 Result = GET_OR_DISTINCT(DINamespace,
3695 (Context, scope.Val, file.Val, name.Val, line.Val));
3700 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
3701 /// includePath: "/usr/include", isysroot: "/")
3702 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
3703 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3704 REQUIRED(scope, MDField, ); \
3705 REQUIRED(name, MDStringField, ); \
3706 OPTIONAL(configMacros, MDStringField, ); \
3707 OPTIONAL(includePath, MDStringField, ); \
3708 OPTIONAL(isysroot, MDStringField, );
3710 #undef VISIT_MD_FIELDS
3712 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
3713 configMacros.Val, includePath.Val, isysroot.Val));
3717 /// ParseDITemplateTypeParameter:
3718 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3719 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3720 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3721 OPTIONAL(name, MDStringField, ); \
3722 REQUIRED(type, MDField, );
3724 #undef VISIT_MD_FIELDS
3727 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3731 /// ParseDITemplateValueParameter:
3732 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3733 /// name: "V", type: !1, value: i32 7)
3734 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3735 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3736 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3737 OPTIONAL(name, MDStringField, ); \
3738 OPTIONAL(type, MDField, ); \
3739 REQUIRED(value, MDField, );
3741 #undef VISIT_MD_FIELDS
3743 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3744 (Context, tag.Val, name.Val, type.Val, value.Val));
3748 /// ParseDIGlobalVariable:
3749 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3750 /// file: !1, line: 7, type: !2, isLocal: false,
3751 /// isDefinition: true, variable: i32* @foo,
3752 /// declaration: !3)
3753 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3754 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3755 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3756 OPTIONAL(scope, MDField, ); \
3757 OPTIONAL(linkageName, MDStringField, ); \
3758 OPTIONAL(file, MDField, ); \
3759 OPTIONAL(line, LineField, ); \
3760 OPTIONAL(type, MDField, ); \
3761 OPTIONAL(isLocal, MDBoolField, ); \
3762 OPTIONAL(isDefinition, MDBoolField, (true)); \
3763 OPTIONAL(variable, MDConstant, ); \
3764 OPTIONAL(declaration, MDField, );
3766 #undef VISIT_MD_FIELDS
3768 Result = GET_OR_DISTINCT(DIGlobalVariable,
3769 (Context, scope.Val, name.Val, linkageName.Val,
3770 file.Val, line.Val, type.Val, isLocal.Val,
3771 isDefinition.Val, variable.Val, declaration.Val));
3775 /// ParseDILocalVariable:
3776 /// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3777 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3778 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3779 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3780 REQUIRED(tag, DwarfTagField, ); \
3781 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3782 OPTIONAL(name, MDStringField, ); \
3783 OPTIONAL(file, MDField, ); \
3784 OPTIONAL(line, LineField, ); \
3785 OPTIONAL(type, MDField, ); \
3786 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3787 OPTIONAL(flags, DIFlagField, );
3789 #undef VISIT_MD_FIELDS
3791 Result = GET_OR_DISTINCT(DILocalVariable,
3792 (Context, tag.Val, scope.Val, name.Val, file.Val,
3793 line.Val, type.Val, arg.Val, flags.Val));
3797 /// ParseDIExpression:
3798 /// ::= !DIExpression(0, 7, -1)
3799 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3800 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3803 if (ParseToken(lltok::lparen, "expected '(' here"))
3806 SmallVector<uint64_t, 8> Elements;
3807 if (Lex.getKind() != lltok::rparen)
3809 if (Lex.getKind() == lltok::DwarfOp) {
3810 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3812 Elements.push_back(Op);
3815 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3818 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3819 return TokError("expected unsigned integer");
3821 auto &U = Lex.getAPSIntVal();
3822 if (U.ugt(UINT64_MAX))
3823 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3824 Elements.push_back(U.getZExtValue());
3826 } while (EatIfPresent(lltok::comma));
3828 if (ParseToken(lltok::rparen, "expected ')' here"))
3831 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3835 /// ParseDIObjCProperty:
3836 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3837 /// getter: "getFoo", attributes: 7, type: !2)
3838 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3839 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3840 OPTIONAL(name, MDStringField, ); \
3841 OPTIONAL(file, MDField, ); \
3842 OPTIONAL(line, LineField, ); \
3843 OPTIONAL(setter, MDStringField, ); \
3844 OPTIONAL(getter, MDStringField, ); \
3845 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3846 OPTIONAL(type, MDField, );
3848 #undef VISIT_MD_FIELDS
3850 Result = GET_OR_DISTINCT(DIObjCProperty,
3851 (Context, name.Val, file.Val, line.Val, setter.Val,
3852 getter.Val, attributes.Val, type.Val));
3856 /// ParseDIImportedEntity:
3857 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3858 /// line: 7, name: "foo")
3859 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3860 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3861 REQUIRED(tag, DwarfTagField, ); \
3862 REQUIRED(scope, MDField, ); \
3863 OPTIONAL(entity, MDField, ); \
3864 OPTIONAL(line, LineField, ); \
3865 OPTIONAL(name, MDStringField, );
3867 #undef VISIT_MD_FIELDS
3869 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3870 entity.Val, line.Val, name.Val));
3874 #undef PARSE_MD_FIELD
3876 #undef REQUIRE_FIELD
3877 #undef DECLARE_FIELD
3879 /// ParseMetadataAsValue
3880 /// ::= metadata i32 %local
3881 /// ::= metadata i32 @global
3882 /// ::= metadata i32 7
3884 /// ::= metadata !{...}
3885 /// ::= metadata !"string"
3886 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3887 // Note: the type 'metadata' has already been parsed.
3889 if (ParseMetadata(MD, &PFS))
3892 V = MetadataAsValue::get(Context, MD);
3896 /// ParseValueAsMetadata
3900 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3901 PerFunctionState *PFS) {
3904 if (ParseType(Ty, TypeMsg, Loc))
3906 if (Ty->isMetadataTy())
3907 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3910 if (ParseValue(Ty, V, PFS))
3913 MD = ValueAsMetadata::get(V);
3924 /// ::= !DILocation(...)
3925 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3926 if (Lex.getKind() == lltok::MetadataVar) {
3928 if (ParseSpecializedMDNode(N))
3936 if (Lex.getKind() != lltok::exclaim)
3937 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3940 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3944 // ::= '!' STRINGCONSTANT
3945 if (Lex.getKind() == lltok::StringConstant) {
3947 if (ParseMDString(S))
3957 if (ParseMDNodeTail(N))
3964 //===----------------------------------------------------------------------===//
3965 // Function Parsing.
3966 //===----------------------------------------------------------------------===//
3968 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3969 PerFunctionState *PFS) {
3970 if (Ty->isFunctionTy())
3971 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3974 case ValID::t_LocalID:
3975 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3976 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3977 return V == nullptr;
3978 case ValID::t_LocalName:
3979 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3980 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3981 return V == nullptr;
3982 case ValID::t_InlineAsm: {
3984 if (!InlineAsm::Verify(ID.FTy, ID.StrVal2))
3985 return Error(ID.Loc, "invalid type for inline asm constraint string");
3986 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
3987 (ID.UIntVal >> 1) & 1,
3988 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
3991 case ValID::t_GlobalName:
3992 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3993 return V == nullptr;
3994 case ValID::t_GlobalID:
3995 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3996 return V == nullptr;
3997 case ValID::t_APSInt:
3998 if (!Ty->isIntegerTy())
3999 return Error(ID.Loc, "integer constant must have integer type");
4000 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4001 V = ConstantInt::get(Context, ID.APSIntVal);
4003 case ValID::t_APFloat:
4004 if (!Ty->isFloatingPointTy() ||
4005 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4006 return Error(ID.Loc, "floating point constant invalid for type");
4008 // The lexer has no type info, so builds all half, float, and double FP
4009 // constants as double. Fix this here. Long double does not need this.
4010 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4013 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4015 else if (Ty->isFloatTy())
4016 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4019 V = ConstantFP::get(Context, ID.APFloatVal);
4021 if (V->getType() != Ty)
4022 return Error(ID.Loc, "floating point constant does not have type '" +
4023 getTypeString(Ty) + "'");
4027 if (!Ty->isPointerTy())
4028 return Error(ID.Loc, "null must be a pointer type");
4029 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4031 case ValID::t_Undef:
4032 // FIXME: LabelTy should not be a first-class type.
4033 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4034 return Error(ID.Loc, "invalid type for undef constant");
4035 V = UndefValue::get(Ty);
4037 case ValID::t_EmptyArray:
4038 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4039 return Error(ID.Loc, "invalid empty array initializer");
4040 V = UndefValue::get(Ty);
4043 // FIXME: LabelTy should not be a first-class type.
4044 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4045 return Error(ID.Loc, "invalid type for null constant");
4046 V = Constant::getNullValue(Ty);
4048 case ValID::t_Constant:
4049 if (ID.ConstantVal->getType() != Ty)
4050 return Error(ID.Loc, "constant expression type mismatch");
4054 case ValID::t_ConstantStruct:
4055 case ValID::t_PackedConstantStruct:
4056 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4057 if (ST->getNumElements() != ID.UIntVal)
4058 return Error(ID.Loc,
4059 "initializer with struct type has wrong # elements");
4060 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4061 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4063 // Verify that the elements are compatible with the structtype.
4064 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4065 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4066 return Error(ID.Loc, "element " + Twine(i) +
4067 " of struct initializer doesn't match struct element type");
4069 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4072 return Error(ID.Loc, "constant expression type mismatch");
4075 llvm_unreachable("Invalid ValID");
4078 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4081 auto Loc = Lex.getLoc();
4082 if (ParseValID(ID, /*PFS=*/nullptr))
4085 case ValID::t_APSInt:
4086 case ValID::t_APFloat:
4087 case ValID::t_Constant:
4088 case ValID::t_ConstantStruct:
4089 case ValID::t_PackedConstantStruct: {
4091 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4093 assert(isa<Constant>(V) && "Expected a constant value");
4094 C = cast<Constant>(V);
4098 return Error(Loc, "expected a constant value");
4102 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4105 return ParseValID(ID, PFS) ||
4106 ConvertValIDToValue(Ty, ID, V, PFS);
4109 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4111 return ParseType(Ty) ||
4112 ParseValue(Ty, V, PFS);
4115 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4116 PerFunctionState &PFS) {
4119 if (ParseTypeAndValue(V, PFS)) return true;
4120 if (!isa<BasicBlock>(V))
4121 return Error(Loc, "expected a basic block");
4122 BB = cast<BasicBlock>(V);
4128 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4129 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4130 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4131 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4132 // Parse the linkage.
4133 LocTy LinkageLoc = Lex.getLoc();
4136 unsigned Visibility;
4137 unsigned DLLStorageClass;
4138 AttrBuilder RetAttrs;
4140 Type *RetType = nullptr;
4141 LocTy RetTypeLoc = Lex.getLoc();
4142 if (ParseOptionalLinkage(Linkage) ||
4143 ParseOptionalVisibility(Visibility) ||
4144 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4145 ParseOptionalCallingConv(CC) ||
4146 ParseOptionalReturnAttrs(RetAttrs) ||
4147 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4150 // Verify that the linkage is ok.
4151 switch ((GlobalValue::LinkageTypes)Linkage) {
4152 case GlobalValue::ExternalLinkage:
4153 break; // always ok.
4154 case GlobalValue::ExternalWeakLinkage:
4156 return Error(LinkageLoc, "invalid linkage for function definition");
4158 case GlobalValue::PrivateLinkage:
4159 case GlobalValue::InternalLinkage:
4160 case GlobalValue::AvailableExternallyLinkage:
4161 case GlobalValue::LinkOnceAnyLinkage:
4162 case GlobalValue::LinkOnceODRLinkage:
4163 case GlobalValue::WeakAnyLinkage:
4164 case GlobalValue::WeakODRLinkage:
4166 return Error(LinkageLoc, "invalid linkage for function declaration");
4168 case GlobalValue::AppendingLinkage:
4169 case GlobalValue::CommonLinkage:
4170 return Error(LinkageLoc, "invalid function linkage type");
4173 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4174 return Error(LinkageLoc,
4175 "symbol with local linkage must have default visibility");
4177 if (!FunctionType::isValidReturnType(RetType))
4178 return Error(RetTypeLoc, "invalid function return type");
4180 LocTy NameLoc = Lex.getLoc();
4182 std::string FunctionName;
4183 if (Lex.getKind() == lltok::GlobalVar) {
4184 FunctionName = Lex.getStrVal();
4185 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4186 unsigned NameID = Lex.getUIntVal();
4188 if (NameID != NumberedVals.size())
4189 return TokError("function expected to be numbered '%" +
4190 Twine(NumberedVals.size()) + "'");
4192 return TokError("expected function name");
4197 if (Lex.getKind() != lltok::lparen)
4198 return TokError("expected '(' in function argument list");
4200 SmallVector<ArgInfo, 8> ArgList;
4202 AttrBuilder FuncAttrs;
4203 std::vector<unsigned> FwdRefAttrGrps;
4205 std::string Section;
4209 LocTy UnnamedAddrLoc;
4210 Constant *Prefix = nullptr;
4211 Constant *Prologue = nullptr;
4212 Constant *PersonalityFn = nullptr;
4215 if (ParseArgumentList(ArgList, isVarArg) ||
4216 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4218 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4220 (EatIfPresent(lltok::kw_section) &&
4221 ParseStringConstant(Section)) ||
4222 parseOptionalComdat(FunctionName, C) ||
4223 ParseOptionalAlignment(Alignment) ||
4224 (EatIfPresent(lltok::kw_gc) &&
4225 ParseStringConstant(GC)) ||
4226 (EatIfPresent(lltok::kw_prefix) &&
4227 ParseGlobalTypeAndValue(Prefix)) ||
4228 (EatIfPresent(lltok::kw_prologue) &&
4229 ParseGlobalTypeAndValue(Prologue)) ||
4230 (EatIfPresent(lltok::kw_personality) &&
4231 ParseGlobalTypeAndValue(PersonalityFn)))
4234 if (FuncAttrs.contains(Attribute::Builtin))
4235 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4237 // If the alignment was parsed as an attribute, move to the alignment field.
4238 if (FuncAttrs.hasAlignmentAttr()) {
4239 Alignment = FuncAttrs.getAlignment();
4240 FuncAttrs.removeAttribute(Attribute::Alignment);
4243 // Okay, if we got here, the function is syntactically valid. Convert types
4244 // and do semantic checks.
4245 std::vector<Type*> ParamTypeList;
4246 SmallVector<AttributeSet, 8> Attrs;
4248 if (RetAttrs.hasAttributes())
4249 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4250 AttributeSet::ReturnIndex,
4253 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4254 ParamTypeList.push_back(ArgList[i].Ty);
4255 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4256 AttrBuilder B(ArgList[i].Attrs, i + 1);
4257 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4261 if (FuncAttrs.hasAttributes())
4262 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4263 AttributeSet::FunctionIndex,
4266 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4268 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4269 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4272 FunctionType::get(RetType, ParamTypeList, isVarArg);
4273 PointerType *PFT = PointerType::getUnqual(FT);
4276 if (!FunctionName.empty()) {
4277 // If this was a definition of a forward reference, remove the definition
4278 // from the forward reference table and fill in the forward ref.
4279 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4280 ForwardRefVals.find(FunctionName);
4281 if (FRVI != ForwardRefVals.end()) {
4282 Fn = M->getFunction(FunctionName);
4284 return Error(FRVI->second.second, "invalid forward reference to "
4285 "function as global value!");
4286 if (Fn->getType() != PFT)
4287 return Error(FRVI->second.second, "invalid forward reference to "
4288 "function '" + FunctionName + "' with wrong type!");
4290 ForwardRefVals.erase(FRVI);
4291 } else if ((Fn = M->getFunction(FunctionName))) {
4292 // Reject redefinitions.
4293 return Error(NameLoc, "invalid redefinition of function '" +
4294 FunctionName + "'");
4295 } else if (M->getNamedValue(FunctionName)) {
4296 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4300 // If this is a definition of a forward referenced function, make sure the
4302 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4303 = ForwardRefValIDs.find(NumberedVals.size());
4304 if (I != ForwardRefValIDs.end()) {
4305 Fn = cast<Function>(I->second.first);
4306 if (Fn->getType() != PFT)
4307 return Error(NameLoc, "type of definition and forward reference of '@" +
4308 Twine(NumberedVals.size()) + "' disagree");
4309 ForwardRefValIDs.erase(I);
4314 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4315 else // Move the forward-reference to the correct spot in the module.
4316 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4318 if (FunctionName.empty())
4319 NumberedVals.push_back(Fn);
4321 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4322 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4323 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4324 Fn->setCallingConv(CC);
4325 Fn->setAttributes(PAL);
4326 Fn->setUnnamedAddr(UnnamedAddr);
4327 Fn->setAlignment(Alignment);
4328 Fn->setSection(Section);
4330 Fn->setPersonalityFn(PersonalityFn);
4331 if (!GC.empty()) Fn->setGC(GC.c_str());
4332 Fn->setPrefixData(Prefix);
4333 Fn->setPrologueData(Prologue);
4334 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4336 // Add all of the arguments we parsed to the function.
4337 Function::arg_iterator ArgIt = Fn->arg_begin();
4338 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4339 // If the argument has a name, insert it into the argument symbol table.
4340 if (ArgList[i].Name.empty()) continue;
4342 // Set the name, if it conflicted, it will be auto-renamed.
4343 ArgIt->setName(ArgList[i].Name);
4345 if (ArgIt->getName() != ArgList[i].Name)
4346 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4347 ArgList[i].Name + "'");
4353 // Check the declaration has no block address forward references.
4355 if (FunctionName.empty()) {
4356 ID.Kind = ValID::t_GlobalID;
4357 ID.UIntVal = NumberedVals.size() - 1;
4359 ID.Kind = ValID::t_GlobalName;
4360 ID.StrVal = FunctionName;
4362 auto Blocks = ForwardRefBlockAddresses.find(ID);
4363 if (Blocks != ForwardRefBlockAddresses.end())
4364 return Error(Blocks->first.Loc,
4365 "cannot take blockaddress inside a declaration");
4369 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4371 if (FunctionNumber == -1) {
4372 ID.Kind = ValID::t_GlobalName;
4373 ID.StrVal = F.getName();
4375 ID.Kind = ValID::t_GlobalID;
4376 ID.UIntVal = FunctionNumber;
4379 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4380 if (Blocks == P.ForwardRefBlockAddresses.end())
4383 for (const auto &I : Blocks->second) {
4384 const ValID &BBID = I.first;
4385 GlobalValue *GV = I.second;
4387 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4388 "Expected local id or name");
4390 if (BBID.Kind == ValID::t_LocalName)
4391 BB = GetBB(BBID.StrVal, BBID.Loc);
4393 BB = GetBB(BBID.UIntVal, BBID.Loc);
4395 return P.Error(BBID.Loc, "referenced value is not a basic block");
4397 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4398 GV->eraseFromParent();
4401 P.ForwardRefBlockAddresses.erase(Blocks);
4405 /// ParseFunctionBody
4406 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4407 bool LLParser::ParseFunctionBody(Function &Fn) {
4408 if (Lex.getKind() != lltok::lbrace)
4409 return TokError("expected '{' in function body");
4410 Lex.Lex(); // eat the {.
4412 int FunctionNumber = -1;
4413 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4415 PerFunctionState PFS(*this, Fn, FunctionNumber);
4417 // Resolve block addresses and allow basic blocks to be forward-declared
4418 // within this function.
4419 if (PFS.resolveForwardRefBlockAddresses())
4421 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4423 // We need at least one basic block.
4424 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4425 return TokError("function body requires at least one basic block");
4427 while (Lex.getKind() != lltok::rbrace &&
4428 Lex.getKind() != lltok::kw_uselistorder)
4429 if (ParseBasicBlock(PFS)) return true;
4431 while (Lex.getKind() != lltok::rbrace)
4432 if (ParseUseListOrder(&PFS))
4438 // Verify function is ok.
4439 return PFS.FinishFunction();
4443 /// ::= LabelStr? Instruction*
4444 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4445 // If this basic block starts out with a name, remember it.
4447 LocTy NameLoc = Lex.getLoc();
4448 if (Lex.getKind() == lltok::LabelStr) {
4449 Name = Lex.getStrVal();
4453 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4455 return Error(NameLoc,
4456 "unable to create block named '" + Name + "'");
4458 std::string NameStr;
4460 // Parse the instructions in this block until we get a terminator.
4463 // This instruction may have three possibilities for a name: a) none
4464 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4465 LocTy NameLoc = Lex.getLoc();
4469 if (Lex.getKind() == lltok::LocalVarID) {
4470 NameID = Lex.getUIntVal();
4472 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4474 } else if (Lex.getKind() == lltok::LocalVar) {
4475 NameStr = Lex.getStrVal();
4477 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4481 switch (ParseInstruction(Inst, BB, PFS)) {
4482 default: llvm_unreachable("Unknown ParseInstruction result!");
4483 case InstError: return true;
4485 BB->getInstList().push_back(Inst);
4487 // With a normal result, we check to see if the instruction is followed by
4488 // a comma and metadata.
4489 if (EatIfPresent(lltok::comma))
4490 if (ParseInstructionMetadata(*Inst))
4493 case InstExtraComma:
4494 BB->getInstList().push_back(Inst);
4496 // If the instruction parser ate an extra comma at the end of it, it
4497 // *must* be followed by metadata.
4498 if (ParseInstructionMetadata(*Inst))
4503 // Set the name on the instruction.
4504 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4505 } while (!isa<TerminatorInst>(Inst));
4510 //===----------------------------------------------------------------------===//
4511 // Instruction Parsing.
4512 //===----------------------------------------------------------------------===//
4514 /// ParseInstruction - Parse one of the many different instructions.
4516 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4517 PerFunctionState &PFS) {
4518 lltok::Kind Token = Lex.getKind();
4519 if (Token == lltok::Eof)
4520 return TokError("found end of file when expecting more instructions");
4521 LocTy Loc = Lex.getLoc();
4522 unsigned KeywordVal = Lex.getUIntVal();
4523 Lex.Lex(); // Eat the keyword.
4526 default: return Error(Loc, "expected instruction opcode");
4527 // Terminator Instructions.
4528 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4529 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4530 case lltok::kw_br: return ParseBr(Inst, PFS);
4531 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4532 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4533 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4534 case lltok::kw_resume: return ParseResume(Inst, PFS);
4535 // Binary Operators.
4539 case lltok::kw_shl: {
4540 bool NUW = EatIfPresent(lltok::kw_nuw);
4541 bool NSW = EatIfPresent(lltok::kw_nsw);
4542 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4544 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4546 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4547 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4550 case lltok::kw_fadd:
4551 case lltok::kw_fsub:
4552 case lltok::kw_fmul:
4553 case lltok::kw_fdiv:
4554 case lltok::kw_frem: {
4555 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4556 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4560 Inst->setFastMathFlags(FMF);
4564 case lltok::kw_sdiv:
4565 case lltok::kw_udiv:
4566 case lltok::kw_lshr:
4567 case lltok::kw_ashr: {
4568 bool Exact = EatIfPresent(lltok::kw_exact);
4570 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4571 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4575 case lltok::kw_urem:
4576 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4579 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4580 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4581 case lltok::kw_fcmp: {
4582 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4583 int Res = ParseCompare(Inst, PFS, KeywordVal);
4587 Inst->setFastMathFlags(FMF);
4592 case lltok::kw_trunc:
4593 case lltok::kw_zext:
4594 case lltok::kw_sext:
4595 case lltok::kw_fptrunc:
4596 case lltok::kw_fpext:
4597 case lltok::kw_bitcast:
4598 case lltok::kw_addrspacecast:
4599 case lltok::kw_uitofp:
4600 case lltok::kw_sitofp:
4601 case lltok::kw_fptoui:
4602 case lltok::kw_fptosi:
4603 case lltok::kw_inttoptr:
4604 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4606 case lltok::kw_select: return ParseSelect(Inst, PFS);
4607 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4608 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4609 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4610 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4611 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4612 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4614 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4615 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4616 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4618 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4619 case lltok::kw_load: return ParseLoad(Inst, PFS);
4620 case lltok::kw_store: return ParseStore(Inst, PFS);
4621 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4622 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4623 case lltok::kw_fence: return ParseFence(Inst, PFS);
4624 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4625 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4626 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4630 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4631 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4632 if (Opc == Instruction::FCmp) {
4633 switch (Lex.getKind()) {
4634 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4635 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4636 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4637 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4638 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4639 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4640 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4641 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4642 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4643 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4644 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4645 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4646 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4647 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4648 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4649 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4650 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4653 switch (Lex.getKind()) {
4654 default: return TokError("expected icmp predicate (e.g. 'eq')");
4655 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4656 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4657 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4658 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4659 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4660 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4661 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4662 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4663 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4664 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4671 //===----------------------------------------------------------------------===//
4672 // Terminator Instructions.
4673 //===----------------------------------------------------------------------===//
4675 /// ParseRet - Parse a return instruction.
4676 /// ::= 'ret' void (',' !dbg, !1)*
4677 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4678 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4679 PerFunctionState &PFS) {
4680 SMLoc TypeLoc = Lex.getLoc();
4682 if (ParseType(Ty, true /*void allowed*/)) return true;
4684 Type *ResType = PFS.getFunction().getReturnType();
4686 if (Ty->isVoidTy()) {
4687 if (!ResType->isVoidTy())
4688 return Error(TypeLoc, "value doesn't match function result type '" +
4689 getTypeString(ResType) + "'");
4691 Inst = ReturnInst::Create(Context);
4696 if (ParseValue(Ty, RV, PFS)) return true;
4698 if (ResType != RV->getType())
4699 return Error(TypeLoc, "value doesn't match function result type '" +
4700 getTypeString(ResType) + "'");
4702 Inst = ReturnInst::Create(Context, RV);
4708 /// ::= 'br' TypeAndValue
4709 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4710 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4713 BasicBlock *Op1, *Op2;
4714 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4716 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4717 Inst = BranchInst::Create(BB);
4721 if (Op0->getType() != Type::getInt1Ty(Context))
4722 return Error(Loc, "branch condition must have 'i1' type");
4724 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4725 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4726 ParseToken(lltok::comma, "expected ',' after true destination") ||
4727 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4730 Inst = BranchInst::Create(Op1, Op2, Op0);
4736 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4738 /// ::= (TypeAndValue ',' TypeAndValue)*
4739 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4740 LocTy CondLoc, BBLoc;
4742 BasicBlock *DefaultBB;
4743 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4744 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4745 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4746 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4749 if (!Cond->getType()->isIntegerTy())
4750 return Error(CondLoc, "switch condition must have integer type");
4752 // Parse the jump table pairs.
4753 SmallPtrSet<Value*, 32> SeenCases;
4754 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4755 while (Lex.getKind() != lltok::rsquare) {
4759 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4760 ParseToken(lltok::comma, "expected ',' after case value") ||
4761 ParseTypeAndBasicBlock(DestBB, PFS))
4764 if (!SeenCases.insert(Constant).second)
4765 return Error(CondLoc, "duplicate case value in switch");
4766 if (!isa<ConstantInt>(Constant))
4767 return Error(CondLoc, "case value is not a constant integer");
4769 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4772 Lex.Lex(); // Eat the ']'.
4774 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4775 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4776 SI->addCase(Table[i].first, Table[i].second);
4783 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4784 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4787 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4788 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4789 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4792 if (!Address->getType()->isPointerTy())
4793 return Error(AddrLoc, "indirectbr address must have pointer type");
4795 // Parse the destination list.
4796 SmallVector<BasicBlock*, 16> DestList;
4798 if (Lex.getKind() != lltok::rsquare) {
4800 if (ParseTypeAndBasicBlock(DestBB, PFS))
4802 DestList.push_back(DestBB);
4804 while (EatIfPresent(lltok::comma)) {
4805 if (ParseTypeAndBasicBlock(DestBB, PFS))
4807 DestList.push_back(DestBB);
4811 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4814 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4815 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4816 IBI->addDestination(DestList[i]);
4823 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4824 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4825 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4826 LocTy CallLoc = Lex.getLoc();
4827 AttrBuilder RetAttrs, FnAttrs;
4828 std::vector<unsigned> FwdRefAttrGrps;
4831 Type *RetType = nullptr;
4834 SmallVector<ParamInfo, 16> ArgList;
4836 BasicBlock *NormalBB, *UnwindBB;
4837 if (ParseOptionalCallingConv(CC) ||
4838 ParseOptionalReturnAttrs(RetAttrs) ||
4839 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4840 ParseValID(CalleeID) ||
4841 ParseParameterList(ArgList, PFS) ||
4842 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4844 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4845 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4846 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4847 ParseTypeAndBasicBlock(UnwindBB, PFS))
4850 // If RetType is a non-function pointer type, then this is the short syntax
4851 // for the call, which means that RetType is just the return type. Infer the
4852 // rest of the function argument types from the arguments that are present.
4853 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4855 // Pull out the types of all of the arguments...
4856 std::vector<Type*> ParamTypes;
4857 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4858 ParamTypes.push_back(ArgList[i].V->getType());
4860 if (!FunctionType::isValidReturnType(RetType))
4861 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4863 Ty = FunctionType::get(RetType, ParamTypes, false);
4868 // Look up the callee.
4870 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4873 // Set up the Attribute for the function.
4874 SmallVector<AttributeSet, 8> Attrs;
4875 if (RetAttrs.hasAttributes())
4876 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4877 AttributeSet::ReturnIndex,
4880 SmallVector<Value*, 8> Args;
4882 // Loop through FunctionType's arguments and ensure they are specified
4883 // correctly. Also, gather any parameter attributes.
4884 FunctionType::param_iterator I = Ty->param_begin();
4885 FunctionType::param_iterator E = Ty->param_end();
4886 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4887 Type *ExpectedTy = nullptr;
4890 } else if (!Ty->isVarArg()) {
4891 return Error(ArgList[i].Loc, "too many arguments specified");
4894 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4895 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4896 getTypeString(ExpectedTy) + "'");
4897 Args.push_back(ArgList[i].V);
4898 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4899 AttrBuilder B(ArgList[i].Attrs, i + 1);
4900 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4905 return Error(CallLoc, "not enough parameters specified for call");
4907 if (FnAttrs.hasAttributes()) {
4908 if (FnAttrs.hasAlignmentAttr())
4909 return Error(CallLoc, "invoke instructions may not have an alignment");
4911 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4912 AttributeSet::FunctionIndex,
4916 // Finish off the Attribute and check them
4917 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4919 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4920 II->setCallingConv(CC);
4921 II->setAttributes(PAL);
4922 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4928 /// ::= 'resume' TypeAndValue
4929 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4930 Value *Exn; LocTy ExnLoc;
4931 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4934 ResumeInst *RI = ResumeInst::Create(Exn);
4939 //===----------------------------------------------------------------------===//
4940 // Binary Operators.
4941 //===----------------------------------------------------------------------===//
4944 /// ::= ArithmeticOps TypeAndValue ',' Value
4946 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4947 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4948 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4949 unsigned Opc, unsigned OperandType) {
4950 LocTy Loc; Value *LHS, *RHS;
4951 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4952 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4953 ParseValue(LHS->getType(), RHS, PFS))
4957 switch (OperandType) {
4958 default: llvm_unreachable("Unknown operand type!");
4959 case 0: // int or FP.
4960 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4961 LHS->getType()->isFPOrFPVectorTy();
4963 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4964 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4968 return Error(Loc, "invalid operand type for instruction");
4970 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4975 /// ::= ArithmeticOps TypeAndValue ',' Value {
4976 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4978 LocTy Loc; Value *LHS, *RHS;
4979 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4980 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4981 ParseValue(LHS->getType(), RHS, PFS))
4984 if (!LHS->getType()->isIntOrIntVectorTy())
4985 return Error(Loc,"instruction requires integer or integer vector operands");
4987 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4993 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4994 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4995 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4997 // Parse the integer/fp comparison predicate.
5001 if (ParseCmpPredicate(Pred, Opc) ||
5002 ParseTypeAndValue(LHS, Loc, PFS) ||
5003 ParseToken(lltok::comma, "expected ',' after compare value") ||
5004 ParseValue(LHS->getType(), RHS, PFS))
5007 if (Opc == Instruction::FCmp) {
5008 if (!LHS->getType()->isFPOrFPVectorTy())
5009 return Error(Loc, "fcmp requires floating point operands");
5010 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5012 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5013 if (!LHS->getType()->isIntOrIntVectorTy() &&
5014 !LHS->getType()->getScalarType()->isPointerTy())
5015 return Error(Loc, "icmp requires integer operands");
5016 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5021 //===----------------------------------------------------------------------===//
5022 // Other Instructions.
5023 //===----------------------------------------------------------------------===//
5027 /// ::= CastOpc TypeAndValue 'to' Type
5028 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5032 Type *DestTy = nullptr;
5033 if (ParseTypeAndValue(Op, Loc, PFS) ||
5034 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5038 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5039 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5040 return Error(Loc, "invalid cast opcode for cast from '" +
5041 getTypeString(Op->getType()) + "' to '" +
5042 getTypeString(DestTy) + "'");
5044 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5049 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5050 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5052 Value *Op0, *Op1, *Op2;
5053 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5054 ParseToken(lltok::comma, "expected ',' after select condition") ||
5055 ParseTypeAndValue(Op1, PFS) ||
5056 ParseToken(lltok::comma, "expected ',' after select value") ||
5057 ParseTypeAndValue(Op2, PFS))
5060 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5061 return Error(Loc, Reason);
5063 Inst = SelectInst::Create(Op0, Op1, Op2);
5068 /// ::= 'va_arg' TypeAndValue ',' Type
5069 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5071 Type *EltTy = nullptr;
5073 if (ParseTypeAndValue(Op, PFS) ||
5074 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5075 ParseType(EltTy, TypeLoc))
5078 if (!EltTy->isFirstClassType())
5079 return Error(TypeLoc, "va_arg requires operand with first class type");
5081 Inst = new VAArgInst(Op, EltTy);
5085 /// ParseExtractElement
5086 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5087 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5090 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5091 ParseToken(lltok::comma, "expected ',' after extract value") ||
5092 ParseTypeAndValue(Op1, PFS))
5095 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5096 return Error(Loc, "invalid extractelement operands");
5098 Inst = ExtractElementInst::Create(Op0, Op1);
5102 /// ParseInsertElement
5103 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5104 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5106 Value *Op0, *Op1, *Op2;
5107 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5108 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5109 ParseTypeAndValue(Op1, PFS) ||
5110 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5111 ParseTypeAndValue(Op2, PFS))
5114 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5115 return Error(Loc, "invalid insertelement operands");
5117 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5121 /// ParseShuffleVector
5122 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5123 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5125 Value *Op0, *Op1, *Op2;
5126 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5127 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5128 ParseTypeAndValue(Op1, PFS) ||
5129 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5130 ParseTypeAndValue(Op2, PFS))
5133 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5134 return Error(Loc, "invalid shufflevector operands");
5136 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5141 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5142 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5143 Type *Ty = nullptr; LocTy TypeLoc;
5146 if (ParseType(Ty, TypeLoc) ||
5147 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5148 ParseValue(Ty, Op0, PFS) ||
5149 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5150 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5151 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5154 bool AteExtraComma = false;
5155 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5157 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5159 if (!EatIfPresent(lltok::comma))
5162 if (Lex.getKind() == lltok::MetadataVar) {
5163 AteExtraComma = true;
5167 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5168 ParseValue(Ty, Op0, PFS) ||
5169 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5170 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5171 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5175 if (!Ty->isFirstClassType())
5176 return Error(TypeLoc, "phi node must have first class type");
5178 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5179 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5180 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5182 return AteExtraComma ? InstExtraComma : InstNormal;
5186 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5188 /// ::= 'catch' TypeAndValue
5190 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5191 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5192 Type *Ty = nullptr; LocTy TyLoc;
5194 if (ParseType(Ty, TyLoc))
5197 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5198 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5200 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5201 LandingPadInst::ClauseType CT;
5202 if (EatIfPresent(lltok::kw_catch))
5203 CT = LandingPadInst::Catch;
5204 else if (EatIfPresent(lltok::kw_filter))
5205 CT = LandingPadInst::Filter;
5207 return TokError("expected 'catch' or 'filter' clause type");
5211 if (ParseTypeAndValue(V, VLoc, PFS))
5214 // A 'catch' type expects a non-array constant. A filter clause expects an
5216 if (CT == LandingPadInst::Catch) {
5217 if (isa<ArrayType>(V->getType()))
5218 Error(VLoc, "'catch' clause has an invalid type");
5220 if (!isa<ArrayType>(V->getType()))
5221 Error(VLoc, "'filter' clause has an invalid type");
5224 Constant *CV = dyn_cast<Constant>(V);
5226 return Error(VLoc, "clause argument must be a constant");
5230 Inst = LP.release();
5235 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5236 /// ParameterList OptionalAttrs
5237 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5238 /// ParameterList OptionalAttrs
5239 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5240 /// ParameterList OptionalAttrs
5241 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5242 CallInst::TailCallKind TCK) {
5243 AttrBuilder RetAttrs, FnAttrs;
5244 std::vector<unsigned> FwdRefAttrGrps;
5247 Type *RetType = nullptr;
5250 SmallVector<ParamInfo, 16> ArgList;
5251 LocTy CallLoc = Lex.getLoc();
5253 if ((TCK != CallInst::TCK_None &&
5254 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5255 ParseOptionalCallingConv(CC) ||
5256 ParseOptionalReturnAttrs(RetAttrs) ||
5257 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5258 ParseValID(CalleeID) ||
5259 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5260 PFS.getFunction().isVarArg()) ||
5261 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5265 // If RetType is a non-function pointer type, then this is the short syntax
5266 // for the call, which means that RetType is just the return type. Infer the
5267 // rest of the function argument types from the arguments that are present.
5268 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5270 // Pull out the types of all of the arguments...
5271 std::vector<Type*> ParamTypes;
5272 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5273 ParamTypes.push_back(ArgList[i].V->getType());
5275 if (!FunctionType::isValidReturnType(RetType))
5276 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5278 Ty = FunctionType::get(RetType, ParamTypes, false);
5283 // Look up the callee.
5285 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5288 // Set up the Attribute for the function.
5289 SmallVector<AttributeSet, 8> Attrs;
5290 if (RetAttrs.hasAttributes())
5291 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5292 AttributeSet::ReturnIndex,
5295 SmallVector<Value*, 8> Args;
5297 // Loop through FunctionType's arguments and ensure they are specified
5298 // correctly. Also, gather any parameter attributes.
5299 FunctionType::param_iterator I = Ty->param_begin();
5300 FunctionType::param_iterator E = Ty->param_end();
5301 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5302 Type *ExpectedTy = nullptr;
5305 } else if (!Ty->isVarArg()) {
5306 return Error(ArgList[i].Loc, "too many arguments specified");
5309 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5310 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5311 getTypeString(ExpectedTy) + "'");
5312 Args.push_back(ArgList[i].V);
5313 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5314 AttrBuilder B(ArgList[i].Attrs, i + 1);
5315 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5320 return Error(CallLoc, "not enough parameters specified for call");
5322 if (FnAttrs.hasAttributes()) {
5323 if (FnAttrs.hasAlignmentAttr())
5324 return Error(CallLoc, "call instructions may not have an alignment");
5326 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5327 AttributeSet::FunctionIndex,
5331 // Finish off the Attribute and check them
5332 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5334 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5335 CI->setTailCallKind(TCK);
5336 CI->setCallingConv(CC);
5337 CI->setAttributes(PAL);
5338 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5343 //===----------------------------------------------------------------------===//
5344 // Memory Instructions.
5345 //===----------------------------------------------------------------------===//
5348 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5349 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5350 Value *Size = nullptr;
5351 LocTy SizeLoc, TyLoc;
5352 unsigned Alignment = 0;
5355 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5357 if (ParseType(Ty, TyLoc)) return true;
5359 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5360 return Error(TyLoc, "invalid type for alloca");
5362 bool AteExtraComma = false;
5363 if (EatIfPresent(lltok::comma)) {
5364 if (Lex.getKind() == lltok::kw_align) {
5365 if (ParseOptionalAlignment(Alignment)) return true;
5366 } else if (Lex.getKind() == lltok::MetadataVar) {
5367 AteExtraComma = true;
5369 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5370 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5375 if (Size && !Size->getType()->isIntegerTy())
5376 return Error(SizeLoc, "element count must have integer type");
5378 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5379 AI->setUsedWithInAlloca(IsInAlloca);
5381 return AteExtraComma ? InstExtraComma : InstNormal;
5385 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5386 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5387 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5388 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5389 Value *Val; LocTy Loc;
5390 unsigned Alignment = 0;
5391 bool AteExtraComma = false;
5392 bool isAtomic = false;
5393 AtomicOrdering Ordering = NotAtomic;
5394 SynchronizationScope Scope = CrossThread;
5396 if (Lex.getKind() == lltok::kw_atomic) {
5401 bool isVolatile = false;
5402 if (Lex.getKind() == lltok::kw_volatile) {
5408 LocTy ExplicitTypeLoc = Lex.getLoc();
5409 if (ParseType(Ty) ||
5410 ParseToken(lltok::comma, "expected comma after load's type") ||
5411 ParseTypeAndValue(Val, Loc, PFS) ||
5412 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5413 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5416 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5417 return Error(Loc, "load operand must be a pointer to a first class type");
5418 if (isAtomic && !Alignment)
5419 return Error(Loc, "atomic load must have explicit non-zero alignment");
5420 if (Ordering == Release || Ordering == AcquireRelease)
5421 return Error(Loc, "atomic load cannot use Release ordering");
5423 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5424 return Error(ExplicitTypeLoc,
5425 "explicit pointee type doesn't match operand's pointee type");
5427 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5428 return AteExtraComma ? InstExtraComma : InstNormal;
5433 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5434 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5435 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5436 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5437 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5438 unsigned Alignment = 0;
5439 bool AteExtraComma = false;
5440 bool isAtomic = false;
5441 AtomicOrdering Ordering = NotAtomic;
5442 SynchronizationScope Scope = CrossThread;
5444 if (Lex.getKind() == lltok::kw_atomic) {
5449 bool isVolatile = false;
5450 if (Lex.getKind() == lltok::kw_volatile) {
5455 if (ParseTypeAndValue(Val, Loc, PFS) ||
5456 ParseToken(lltok::comma, "expected ',' after store operand") ||
5457 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5458 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5459 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5462 if (!Ptr->getType()->isPointerTy())
5463 return Error(PtrLoc, "store operand must be a pointer");
5464 if (!Val->getType()->isFirstClassType())
5465 return Error(Loc, "store operand must be a first class value");
5466 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5467 return Error(Loc, "stored value and pointer type do not match");
5468 if (isAtomic && !Alignment)
5469 return Error(Loc, "atomic store must have explicit non-zero alignment");
5470 if (Ordering == Acquire || Ordering == AcquireRelease)
5471 return Error(Loc, "atomic store cannot use Acquire ordering");
5473 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5474 return AteExtraComma ? InstExtraComma : InstNormal;
5478 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5479 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5480 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5481 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5482 bool AteExtraComma = false;
5483 AtomicOrdering SuccessOrdering = NotAtomic;
5484 AtomicOrdering FailureOrdering = NotAtomic;
5485 SynchronizationScope Scope = CrossThread;
5486 bool isVolatile = false;
5487 bool isWeak = false;
5489 if (EatIfPresent(lltok::kw_weak))
5492 if (EatIfPresent(lltok::kw_volatile))
5495 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5496 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5497 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5498 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5499 ParseTypeAndValue(New, NewLoc, PFS) ||
5500 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5501 ParseOrdering(FailureOrdering))
5504 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5505 return TokError("cmpxchg cannot be unordered");
5506 if (SuccessOrdering < FailureOrdering)
5507 return TokError("cmpxchg must be at least as ordered on success as failure");
5508 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5509 return TokError("cmpxchg failure ordering cannot include release semantics");
5510 if (!Ptr->getType()->isPointerTy())
5511 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5512 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5513 return Error(CmpLoc, "compare value and pointer type do not match");
5514 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5515 return Error(NewLoc, "new value and pointer type do not match");
5516 if (!New->getType()->isIntegerTy())
5517 return Error(NewLoc, "cmpxchg operand must be an integer");
5518 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5519 if (Size < 8 || (Size & (Size - 1)))
5520 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5523 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5524 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5525 CXI->setVolatile(isVolatile);
5526 CXI->setWeak(isWeak);
5528 return AteExtraComma ? InstExtraComma : InstNormal;
5532 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5533 /// 'singlethread'? AtomicOrdering
5534 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5535 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5536 bool AteExtraComma = false;
5537 AtomicOrdering Ordering = NotAtomic;
5538 SynchronizationScope Scope = CrossThread;
5539 bool isVolatile = false;
5540 AtomicRMWInst::BinOp Operation;
5542 if (EatIfPresent(lltok::kw_volatile))
5545 switch (Lex.getKind()) {
5546 default: return TokError("expected binary operation in atomicrmw");
5547 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5548 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5549 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5550 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5551 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5552 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5553 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5554 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5555 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5556 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5557 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5559 Lex.Lex(); // Eat the operation.
5561 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5562 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5563 ParseTypeAndValue(Val, ValLoc, PFS) ||
5564 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5567 if (Ordering == Unordered)
5568 return TokError("atomicrmw cannot be unordered");
5569 if (!Ptr->getType()->isPointerTy())
5570 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5571 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5572 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5573 if (!Val->getType()->isIntegerTy())
5574 return Error(ValLoc, "atomicrmw operand must be an integer");
5575 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5576 if (Size < 8 || (Size & (Size - 1)))
5577 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5580 AtomicRMWInst *RMWI =
5581 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5582 RMWI->setVolatile(isVolatile);
5584 return AteExtraComma ? InstExtraComma : InstNormal;
5588 /// ::= 'fence' 'singlethread'? AtomicOrdering
5589 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5590 AtomicOrdering Ordering = NotAtomic;
5591 SynchronizationScope Scope = CrossThread;
5592 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5595 if (Ordering == Unordered)
5596 return TokError("fence cannot be unordered");
5597 if (Ordering == Monotonic)
5598 return TokError("fence cannot be monotonic");
5600 Inst = new FenceInst(Context, Ordering, Scope);
5604 /// ParseGetElementPtr
5605 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5606 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5607 Value *Ptr = nullptr;
5608 Value *Val = nullptr;
5611 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5614 LocTy ExplicitTypeLoc = Lex.getLoc();
5615 if (ParseType(Ty) ||
5616 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5617 ParseTypeAndValue(Ptr, Loc, PFS))
5620 Type *BaseType = Ptr->getType();
5621 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5622 if (!BasePointerType)
5623 return Error(Loc, "base of getelementptr must be a pointer");
5625 if (Ty != BasePointerType->getElementType())
5626 return Error(ExplicitTypeLoc,
5627 "explicit pointee type doesn't match operand's pointee type");
5629 SmallVector<Value*, 16> Indices;
5630 bool AteExtraComma = false;
5631 // GEP returns a vector of pointers if at least one of parameters is a vector.
5632 // All vector parameters should have the same vector width.
5633 unsigned GEPWidth = BaseType->isVectorTy() ?
5634 BaseType->getVectorNumElements() : 0;
5636 while (EatIfPresent(lltok::comma)) {
5637 if (Lex.getKind() == lltok::MetadataVar) {
5638 AteExtraComma = true;
5641 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5642 if (!Val->getType()->getScalarType()->isIntegerTy())
5643 return Error(EltLoc, "getelementptr index must be an integer");
5645 if (Val->getType()->isVectorTy()) {
5646 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5647 if (GEPWidth && GEPWidth != ValNumEl)
5648 return Error(EltLoc,
5649 "getelementptr vector index has a wrong number of elements");
5650 GEPWidth = ValNumEl;
5652 Indices.push_back(Val);
5655 SmallPtrSet<const Type*, 4> Visited;
5656 if (!Indices.empty() && !Ty->isSized(&Visited))
5657 return Error(Loc, "base element of getelementptr must be sized");
5659 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5660 return Error(Loc, "invalid getelementptr indices");
5661 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5663 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5664 return AteExtraComma ? InstExtraComma : InstNormal;
5667 /// ParseExtractValue
5668 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5669 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5670 Value *Val; LocTy Loc;
5671 SmallVector<unsigned, 4> Indices;
5673 if (ParseTypeAndValue(Val, Loc, PFS) ||
5674 ParseIndexList(Indices, AteExtraComma))
5677 if (!Val->getType()->isAggregateType())
5678 return Error(Loc, "extractvalue operand must be aggregate type");
5680 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5681 return Error(Loc, "invalid indices for extractvalue");
5682 Inst = ExtractValueInst::Create(Val, Indices);
5683 return AteExtraComma ? InstExtraComma : InstNormal;
5686 /// ParseInsertValue
5687 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5688 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5689 Value *Val0, *Val1; LocTy Loc0, Loc1;
5690 SmallVector<unsigned, 4> Indices;
5692 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5693 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5694 ParseTypeAndValue(Val1, Loc1, PFS) ||
5695 ParseIndexList(Indices, AteExtraComma))
5698 if (!Val0->getType()->isAggregateType())
5699 return Error(Loc0, "insertvalue operand must be aggregate type");
5701 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5703 return Error(Loc0, "invalid indices for insertvalue");
5704 if (IndexedType != Val1->getType())
5705 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5706 getTypeString(Val1->getType()) + "' instead of '" +
5707 getTypeString(IndexedType) + "'");
5708 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5709 return AteExtraComma ? InstExtraComma : InstNormal;
5712 //===----------------------------------------------------------------------===//
5713 // Embedded metadata.
5714 //===----------------------------------------------------------------------===//
5716 /// ParseMDNodeVector
5717 /// ::= { Element (',' Element)* }
5719 /// ::= 'null' | TypeAndValue
5720 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5721 if (ParseToken(lltok::lbrace, "expected '{' here"))
5724 // Check for an empty list.
5725 if (EatIfPresent(lltok::rbrace))
5729 // Null is a special case since it is typeless.
5730 if (EatIfPresent(lltok::kw_null)) {
5731 Elts.push_back(nullptr);
5736 if (ParseMetadata(MD, nullptr))
5739 } while (EatIfPresent(lltok::comma));
5741 return ParseToken(lltok::rbrace, "expected end of metadata node");
5744 //===----------------------------------------------------------------------===//
5745 // Use-list order directives.
5746 //===----------------------------------------------------------------------===//
5747 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5750 return Error(Loc, "value has no uses");
5752 unsigned NumUses = 0;
5753 SmallDenseMap<const Use *, unsigned, 16> Order;
5754 for (const Use &U : V->uses()) {
5755 if (++NumUses > Indexes.size())
5757 Order[&U] = Indexes[NumUses - 1];
5760 return Error(Loc, "value only has one use");
5761 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5762 return Error(Loc, "wrong number of indexes, expected " +
5763 Twine(std::distance(V->use_begin(), V->use_end())));
5765 V->sortUseList([&](const Use &L, const Use &R) {
5766 return Order.lookup(&L) < Order.lookup(&R);
5771 /// ParseUseListOrderIndexes
5772 /// ::= '{' uint32 (',' uint32)+ '}'
5773 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5774 SMLoc Loc = Lex.getLoc();
5775 if (ParseToken(lltok::lbrace, "expected '{' here"))
5777 if (Lex.getKind() == lltok::rbrace)
5778 return Lex.Error("expected non-empty list of uselistorder indexes");
5780 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5781 // indexes should be distinct numbers in the range [0, size-1], and should
5783 unsigned Offset = 0;
5785 bool IsOrdered = true;
5786 assert(Indexes.empty() && "Expected empty order vector");
5789 if (ParseUInt32(Index))
5792 // Update consistency checks.
5793 Offset += Index - Indexes.size();
5794 Max = std::max(Max, Index);
5795 IsOrdered &= Index == Indexes.size();
5797 Indexes.push_back(Index);
5798 } while (EatIfPresent(lltok::comma));
5800 if (ParseToken(lltok::rbrace, "expected '}' here"))
5803 if (Indexes.size() < 2)
5804 return Error(Loc, "expected >= 2 uselistorder indexes");
5805 if (Offset != 0 || Max >= Indexes.size())
5806 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5808 return Error(Loc, "expected uselistorder indexes to change the order");
5813 /// ParseUseListOrder
5814 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5815 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5816 SMLoc Loc = Lex.getLoc();
5817 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5821 SmallVector<unsigned, 16> Indexes;
5822 if (ParseTypeAndValue(V, PFS) ||
5823 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5824 ParseUseListOrderIndexes(Indexes))
5827 return sortUseListOrder(V, Indexes, Loc);
5830 /// ParseUseListOrderBB
5831 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5832 bool LLParser::ParseUseListOrderBB() {
5833 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5834 SMLoc Loc = Lex.getLoc();
5838 SmallVector<unsigned, 16> Indexes;
5839 if (ParseValID(Fn) ||
5840 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5841 ParseValID(Label) ||
5842 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5843 ParseUseListOrderIndexes(Indexes))
5846 // Check the function.
5848 if (Fn.Kind == ValID::t_GlobalName)
5849 GV = M->getNamedValue(Fn.StrVal);
5850 else if (Fn.Kind == ValID::t_GlobalID)
5851 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5853 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5855 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5856 auto *F = dyn_cast<Function>(GV);
5858 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5859 if (F->isDeclaration())
5860 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5862 // Check the basic block.
5863 if (Label.Kind == ValID::t_LocalID)
5864 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5865 if (Label.Kind != ValID::t_LocalName)
5866 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5867 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5869 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5870 if (!isa<BasicBlock>(V))
5871 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5873 return sortUseListOrder(V, Indexes, Loc);