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(arg: 7, scope: !0, name: "foo",
3777 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3778 /// ::= !DILocalVariable(scope: !0, name: "foo",
3779 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3780 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3781 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3782 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3783 OPTIONAL(name, MDStringField, ); \
3784 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
3785 OPTIONAL(file, MDField, ); \
3786 OPTIONAL(line, LineField, ); \
3787 OPTIONAL(type, MDField, ); \
3788 OPTIONAL(flags, DIFlagField, );
3790 #undef VISIT_MD_FIELDS
3792 Result = GET_OR_DISTINCT(DILocalVariable,
3793 (Context, scope.Val, name.Val, file.Val, line.Val,
3794 type.Val, arg.Val, flags.Val));
3798 /// ParseDIExpression:
3799 /// ::= !DIExpression(0, 7, -1)
3800 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3801 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3804 if (ParseToken(lltok::lparen, "expected '(' here"))
3807 SmallVector<uint64_t, 8> Elements;
3808 if (Lex.getKind() != lltok::rparen)
3810 if (Lex.getKind() == lltok::DwarfOp) {
3811 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3813 Elements.push_back(Op);
3816 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3819 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3820 return TokError("expected unsigned integer");
3822 auto &U = Lex.getAPSIntVal();
3823 if (U.ugt(UINT64_MAX))
3824 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3825 Elements.push_back(U.getZExtValue());
3827 } while (EatIfPresent(lltok::comma));
3829 if (ParseToken(lltok::rparen, "expected ')' here"))
3832 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3836 /// ParseDIObjCProperty:
3837 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3838 /// getter: "getFoo", attributes: 7, type: !2)
3839 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3840 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3841 OPTIONAL(name, MDStringField, ); \
3842 OPTIONAL(file, MDField, ); \
3843 OPTIONAL(line, LineField, ); \
3844 OPTIONAL(setter, MDStringField, ); \
3845 OPTIONAL(getter, MDStringField, ); \
3846 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3847 OPTIONAL(type, MDField, );
3849 #undef VISIT_MD_FIELDS
3851 Result = GET_OR_DISTINCT(DIObjCProperty,
3852 (Context, name.Val, file.Val, line.Val, setter.Val,
3853 getter.Val, attributes.Val, type.Val));
3857 /// ParseDIImportedEntity:
3858 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3859 /// line: 7, name: "foo")
3860 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3861 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3862 REQUIRED(tag, DwarfTagField, ); \
3863 REQUIRED(scope, MDField, ); \
3864 OPTIONAL(entity, MDField, ); \
3865 OPTIONAL(line, LineField, ); \
3866 OPTIONAL(name, MDStringField, );
3868 #undef VISIT_MD_FIELDS
3870 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3871 entity.Val, line.Val, name.Val));
3875 #undef PARSE_MD_FIELD
3877 #undef REQUIRE_FIELD
3878 #undef DECLARE_FIELD
3880 /// ParseMetadataAsValue
3881 /// ::= metadata i32 %local
3882 /// ::= metadata i32 @global
3883 /// ::= metadata i32 7
3885 /// ::= metadata !{...}
3886 /// ::= metadata !"string"
3887 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3888 // Note: the type 'metadata' has already been parsed.
3890 if (ParseMetadata(MD, &PFS))
3893 V = MetadataAsValue::get(Context, MD);
3897 /// ParseValueAsMetadata
3901 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3902 PerFunctionState *PFS) {
3905 if (ParseType(Ty, TypeMsg, Loc))
3907 if (Ty->isMetadataTy())
3908 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3911 if (ParseValue(Ty, V, PFS))
3914 MD = ValueAsMetadata::get(V);
3925 /// ::= !DILocation(...)
3926 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3927 if (Lex.getKind() == lltok::MetadataVar) {
3929 if (ParseSpecializedMDNode(N))
3937 if (Lex.getKind() != lltok::exclaim)
3938 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3941 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3945 // ::= '!' STRINGCONSTANT
3946 if (Lex.getKind() == lltok::StringConstant) {
3948 if (ParseMDString(S))
3958 if (ParseMDNodeTail(N))
3965 //===----------------------------------------------------------------------===//
3966 // Function Parsing.
3967 //===----------------------------------------------------------------------===//
3969 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3970 PerFunctionState *PFS) {
3971 if (Ty->isFunctionTy())
3972 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3975 case ValID::t_LocalID:
3976 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3977 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3978 return V == nullptr;
3979 case ValID::t_LocalName:
3980 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3981 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3982 return V == nullptr;
3983 case ValID::t_InlineAsm: {
3985 if (!InlineAsm::Verify(ID.FTy, ID.StrVal2))
3986 return Error(ID.Loc, "invalid type for inline asm constraint string");
3987 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
3988 (ID.UIntVal >> 1) & 1,
3989 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
3992 case ValID::t_GlobalName:
3993 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3994 return V == nullptr;
3995 case ValID::t_GlobalID:
3996 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3997 return V == nullptr;
3998 case ValID::t_APSInt:
3999 if (!Ty->isIntegerTy())
4000 return Error(ID.Loc, "integer constant must have integer type");
4001 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4002 V = ConstantInt::get(Context, ID.APSIntVal);
4004 case ValID::t_APFloat:
4005 if (!Ty->isFloatingPointTy() ||
4006 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4007 return Error(ID.Loc, "floating point constant invalid for type");
4009 // The lexer has no type info, so builds all half, float, and double FP
4010 // constants as double. Fix this here. Long double does not need this.
4011 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4014 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4016 else if (Ty->isFloatTy())
4017 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4020 V = ConstantFP::get(Context, ID.APFloatVal);
4022 if (V->getType() != Ty)
4023 return Error(ID.Loc, "floating point constant does not have type '" +
4024 getTypeString(Ty) + "'");
4028 if (!Ty->isPointerTy())
4029 return Error(ID.Loc, "null must be a pointer type");
4030 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4032 case ValID::t_Undef:
4033 // FIXME: LabelTy should not be a first-class type.
4034 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4035 return Error(ID.Loc, "invalid type for undef constant");
4036 V = UndefValue::get(Ty);
4038 case ValID::t_EmptyArray:
4039 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4040 return Error(ID.Loc, "invalid empty array initializer");
4041 V = UndefValue::get(Ty);
4044 // FIXME: LabelTy should not be a first-class type.
4045 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4046 return Error(ID.Loc, "invalid type for null constant");
4047 V = Constant::getNullValue(Ty);
4049 case ValID::t_Constant:
4050 if (ID.ConstantVal->getType() != Ty)
4051 return Error(ID.Loc, "constant expression type mismatch");
4055 case ValID::t_ConstantStruct:
4056 case ValID::t_PackedConstantStruct:
4057 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4058 if (ST->getNumElements() != ID.UIntVal)
4059 return Error(ID.Loc,
4060 "initializer with struct type has wrong # elements");
4061 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4062 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4064 // Verify that the elements are compatible with the structtype.
4065 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4066 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4067 return Error(ID.Loc, "element " + Twine(i) +
4068 " of struct initializer doesn't match struct element type");
4070 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4073 return Error(ID.Loc, "constant expression type mismatch");
4076 llvm_unreachable("Invalid ValID");
4079 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4082 auto Loc = Lex.getLoc();
4083 if (ParseValID(ID, /*PFS=*/nullptr))
4086 case ValID::t_APSInt:
4087 case ValID::t_APFloat:
4088 case ValID::t_Constant:
4089 case ValID::t_ConstantStruct:
4090 case ValID::t_PackedConstantStruct: {
4092 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4094 assert(isa<Constant>(V) && "Expected a constant value");
4095 C = cast<Constant>(V);
4099 return Error(Loc, "expected a constant value");
4103 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4106 return ParseValID(ID, PFS) ||
4107 ConvertValIDToValue(Ty, ID, V, PFS);
4110 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4112 return ParseType(Ty) ||
4113 ParseValue(Ty, V, PFS);
4116 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4117 PerFunctionState &PFS) {
4120 if (ParseTypeAndValue(V, PFS)) return true;
4121 if (!isa<BasicBlock>(V))
4122 return Error(Loc, "expected a basic block");
4123 BB = cast<BasicBlock>(V);
4129 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4130 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4131 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4132 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4133 // Parse the linkage.
4134 LocTy LinkageLoc = Lex.getLoc();
4137 unsigned Visibility;
4138 unsigned DLLStorageClass;
4139 AttrBuilder RetAttrs;
4141 Type *RetType = nullptr;
4142 LocTy RetTypeLoc = Lex.getLoc();
4143 if (ParseOptionalLinkage(Linkage) ||
4144 ParseOptionalVisibility(Visibility) ||
4145 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4146 ParseOptionalCallingConv(CC) ||
4147 ParseOptionalReturnAttrs(RetAttrs) ||
4148 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4151 // Verify that the linkage is ok.
4152 switch ((GlobalValue::LinkageTypes)Linkage) {
4153 case GlobalValue::ExternalLinkage:
4154 break; // always ok.
4155 case GlobalValue::ExternalWeakLinkage:
4157 return Error(LinkageLoc, "invalid linkage for function definition");
4159 case GlobalValue::PrivateLinkage:
4160 case GlobalValue::InternalLinkage:
4161 case GlobalValue::AvailableExternallyLinkage:
4162 case GlobalValue::LinkOnceAnyLinkage:
4163 case GlobalValue::LinkOnceODRLinkage:
4164 case GlobalValue::WeakAnyLinkage:
4165 case GlobalValue::WeakODRLinkage:
4167 return Error(LinkageLoc, "invalid linkage for function declaration");
4169 case GlobalValue::AppendingLinkage:
4170 case GlobalValue::CommonLinkage:
4171 return Error(LinkageLoc, "invalid function linkage type");
4174 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4175 return Error(LinkageLoc,
4176 "symbol with local linkage must have default visibility");
4178 if (!FunctionType::isValidReturnType(RetType))
4179 return Error(RetTypeLoc, "invalid function return type");
4181 LocTy NameLoc = Lex.getLoc();
4183 std::string FunctionName;
4184 if (Lex.getKind() == lltok::GlobalVar) {
4185 FunctionName = Lex.getStrVal();
4186 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4187 unsigned NameID = Lex.getUIntVal();
4189 if (NameID != NumberedVals.size())
4190 return TokError("function expected to be numbered '%" +
4191 Twine(NumberedVals.size()) + "'");
4193 return TokError("expected function name");
4198 if (Lex.getKind() != lltok::lparen)
4199 return TokError("expected '(' in function argument list");
4201 SmallVector<ArgInfo, 8> ArgList;
4203 AttrBuilder FuncAttrs;
4204 std::vector<unsigned> FwdRefAttrGrps;
4206 std::string Section;
4210 LocTy UnnamedAddrLoc;
4211 Constant *Prefix = nullptr;
4212 Constant *Prologue = nullptr;
4213 Constant *PersonalityFn = nullptr;
4216 if (ParseArgumentList(ArgList, isVarArg) ||
4217 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4219 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4221 (EatIfPresent(lltok::kw_section) &&
4222 ParseStringConstant(Section)) ||
4223 parseOptionalComdat(FunctionName, C) ||
4224 ParseOptionalAlignment(Alignment) ||
4225 (EatIfPresent(lltok::kw_gc) &&
4226 ParseStringConstant(GC)) ||
4227 (EatIfPresent(lltok::kw_prefix) &&
4228 ParseGlobalTypeAndValue(Prefix)) ||
4229 (EatIfPresent(lltok::kw_prologue) &&
4230 ParseGlobalTypeAndValue(Prologue)) ||
4231 (EatIfPresent(lltok::kw_personality) &&
4232 ParseGlobalTypeAndValue(PersonalityFn)))
4235 if (FuncAttrs.contains(Attribute::Builtin))
4236 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4238 // If the alignment was parsed as an attribute, move to the alignment field.
4239 if (FuncAttrs.hasAlignmentAttr()) {
4240 Alignment = FuncAttrs.getAlignment();
4241 FuncAttrs.removeAttribute(Attribute::Alignment);
4244 // Okay, if we got here, the function is syntactically valid. Convert types
4245 // and do semantic checks.
4246 std::vector<Type*> ParamTypeList;
4247 SmallVector<AttributeSet, 8> Attrs;
4249 if (RetAttrs.hasAttributes())
4250 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4251 AttributeSet::ReturnIndex,
4254 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4255 ParamTypeList.push_back(ArgList[i].Ty);
4256 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4257 AttrBuilder B(ArgList[i].Attrs, i + 1);
4258 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4262 if (FuncAttrs.hasAttributes())
4263 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4264 AttributeSet::FunctionIndex,
4267 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4269 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4270 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4273 FunctionType::get(RetType, ParamTypeList, isVarArg);
4274 PointerType *PFT = PointerType::getUnqual(FT);
4277 if (!FunctionName.empty()) {
4278 // If this was a definition of a forward reference, remove the definition
4279 // from the forward reference table and fill in the forward ref.
4280 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4281 ForwardRefVals.find(FunctionName);
4282 if (FRVI != ForwardRefVals.end()) {
4283 Fn = M->getFunction(FunctionName);
4285 return Error(FRVI->second.second, "invalid forward reference to "
4286 "function as global value!");
4287 if (Fn->getType() != PFT)
4288 return Error(FRVI->second.second, "invalid forward reference to "
4289 "function '" + FunctionName + "' with wrong type!");
4291 ForwardRefVals.erase(FRVI);
4292 } else if ((Fn = M->getFunction(FunctionName))) {
4293 // Reject redefinitions.
4294 return Error(NameLoc, "invalid redefinition of function '" +
4295 FunctionName + "'");
4296 } else if (M->getNamedValue(FunctionName)) {
4297 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4301 // If this is a definition of a forward referenced function, make sure the
4303 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4304 = ForwardRefValIDs.find(NumberedVals.size());
4305 if (I != ForwardRefValIDs.end()) {
4306 Fn = cast<Function>(I->second.first);
4307 if (Fn->getType() != PFT)
4308 return Error(NameLoc, "type of definition and forward reference of '@" +
4309 Twine(NumberedVals.size()) + "' disagree");
4310 ForwardRefValIDs.erase(I);
4315 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4316 else // Move the forward-reference to the correct spot in the module.
4317 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4319 if (FunctionName.empty())
4320 NumberedVals.push_back(Fn);
4322 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4323 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4324 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4325 Fn->setCallingConv(CC);
4326 Fn->setAttributes(PAL);
4327 Fn->setUnnamedAddr(UnnamedAddr);
4328 Fn->setAlignment(Alignment);
4329 Fn->setSection(Section);
4331 Fn->setPersonalityFn(PersonalityFn);
4332 if (!GC.empty()) Fn->setGC(GC.c_str());
4333 Fn->setPrefixData(Prefix);
4334 Fn->setPrologueData(Prologue);
4335 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4337 // Add all of the arguments we parsed to the function.
4338 Function::arg_iterator ArgIt = Fn->arg_begin();
4339 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4340 // If the argument has a name, insert it into the argument symbol table.
4341 if (ArgList[i].Name.empty()) continue;
4343 // Set the name, if it conflicted, it will be auto-renamed.
4344 ArgIt->setName(ArgList[i].Name);
4346 if (ArgIt->getName() != ArgList[i].Name)
4347 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4348 ArgList[i].Name + "'");
4354 // Check the declaration has no block address forward references.
4356 if (FunctionName.empty()) {
4357 ID.Kind = ValID::t_GlobalID;
4358 ID.UIntVal = NumberedVals.size() - 1;
4360 ID.Kind = ValID::t_GlobalName;
4361 ID.StrVal = FunctionName;
4363 auto Blocks = ForwardRefBlockAddresses.find(ID);
4364 if (Blocks != ForwardRefBlockAddresses.end())
4365 return Error(Blocks->first.Loc,
4366 "cannot take blockaddress inside a declaration");
4370 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4372 if (FunctionNumber == -1) {
4373 ID.Kind = ValID::t_GlobalName;
4374 ID.StrVal = F.getName();
4376 ID.Kind = ValID::t_GlobalID;
4377 ID.UIntVal = FunctionNumber;
4380 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4381 if (Blocks == P.ForwardRefBlockAddresses.end())
4384 for (const auto &I : Blocks->second) {
4385 const ValID &BBID = I.first;
4386 GlobalValue *GV = I.second;
4388 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4389 "Expected local id or name");
4391 if (BBID.Kind == ValID::t_LocalName)
4392 BB = GetBB(BBID.StrVal, BBID.Loc);
4394 BB = GetBB(BBID.UIntVal, BBID.Loc);
4396 return P.Error(BBID.Loc, "referenced value is not a basic block");
4398 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4399 GV->eraseFromParent();
4402 P.ForwardRefBlockAddresses.erase(Blocks);
4406 /// ParseFunctionBody
4407 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4408 bool LLParser::ParseFunctionBody(Function &Fn) {
4409 if (Lex.getKind() != lltok::lbrace)
4410 return TokError("expected '{' in function body");
4411 Lex.Lex(); // eat the {.
4413 int FunctionNumber = -1;
4414 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4416 PerFunctionState PFS(*this, Fn, FunctionNumber);
4418 // Resolve block addresses and allow basic blocks to be forward-declared
4419 // within this function.
4420 if (PFS.resolveForwardRefBlockAddresses())
4422 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4424 // We need at least one basic block.
4425 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4426 return TokError("function body requires at least one basic block");
4428 while (Lex.getKind() != lltok::rbrace &&
4429 Lex.getKind() != lltok::kw_uselistorder)
4430 if (ParseBasicBlock(PFS)) return true;
4432 while (Lex.getKind() != lltok::rbrace)
4433 if (ParseUseListOrder(&PFS))
4439 // Verify function is ok.
4440 return PFS.FinishFunction();
4444 /// ::= LabelStr? Instruction*
4445 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4446 // If this basic block starts out with a name, remember it.
4448 LocTy NameLoc = Lex.getLoc();
4449 if (Lex.getKind() == lltok::LabelStr) {
4450 Name = Lex.getStrVal();
4454 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4456 return Error(NameLoc,
4457 "unable to create block named '" + Name + "'");
4459 std::string NameStr;
4461 // Parse the instructions in this block until we get a terminator.
4464 // This instruction may have three possibilities for a name: a) none
4465 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4466 LocTy NameLoc = Lex.getLoc();
4470 if (Lex.getKind() == lltok::LocalVarID) {
4471 NameID = Lex.getUIntVal();
4473 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4475 } else if (Lex.getKind() == lltok::LocalVar) {
4476 NameStr = Lex.getStrVal();
4478 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4482 switch (ParseInstruction(Inst, BB, PFS)) {
4483 default: llvm_unreachable("Unknown ParseInstruction result!");
4484 case InstError: return true;
4486 BB->getInstList().push_back(Inst);
4488 // With a normal result, we check to see if the instruction is followed by
4489 // a comma and metadata.
4490 if (EatIfPresent(lltok::comma))
4491 if (ParseInstructionMetadata(*Inst))
4494 case InstExtraComma:
4495 BB->getInstList().push_back(Inst);
4497 // If the instruction parser ate an extra comma at the end of it, it
4498 // *must* be followed by metadata.
4499 if (ParseInstructionMetadata(*Inst))
4504 // Set the name on the instruction.
4505 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4506 } while (!isa<TerminatorInst>(Inst));
4511 //===----------------------------------------------------------------------===//
4512 // Instruction Parsing.
4513 //===----------------------------------------------------------------------===//
4515 /// ParseInstruction - Parse one of the many different instructions.
4517 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4518 PerFunctionState &PFS) {
4519 lltok::Kind Token = Lex.getKind();
4520 if (Token == lltok::Eof)
4521 return TokError("found end of file when expecting more instructions");
4522 LocTy Loc = Lex.getLoc();
4523 unsigned KeywordVal = Lex.getUIntVal();
4524 Lex.Lex(); // Eat the keyword.
4527 default: return Error(Loc, "expected instruction opcode");
4528 // Terminator Instructions.
4529 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4530 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4531 case lltok::kw_br: return ParseBr(Inst, PFS);
4532 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4533 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4534 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4535 case lltok::kw_resume: return ParseResume(Inst, PFS);
4536 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4537 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4538 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4539 case lltok::kw_terminatepad: return ParseTerminatePad(Inst, PFS);
4540 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4541 case lltok::kw_catchendpad: return ParseCatchEndPad(Inst, PFS);
4542 // Binary Operators.
4546 case lltok::kw_shl: {
4547 bool NUW = EatIfPresent(lltok::kw_nuw);
4548 bool NSW = EatIfPresent(lltok::kw_nsw);
4549 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4551 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4553 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4554 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4557 case lltok::kw_fadd:
4558 case lltok::kw_fsub:
4559 case lltok::kw_fmul:
4560 case lltok::kw_fdiv:
4561 case lltok::kw_frem: {
4562 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4563 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4567 Inst->setFastMathFlags(FMF);
4571 case lltok::kw_sdiv:
4572 case lltok::kw_udiv:
4573 case lltok::kw_lshr:
4574 case lltok::kw_ashr: {
4575 bool Exact = EatIfPresent(lltok::kw_exact);
4577 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4578 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4582 case lltok::kw_urem:
4583 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4586 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4587 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4588 case lltok::kw_fcmp: {
4589 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4590 int Res = ParseCompare(Inst, PFS, KeywordVal);
4594 Inst->setFastMathFlags(FMF);
4599 case lltok::kw_trunc:
4600 case lltok::kw_zext:
4601 case lltok::kw_sext:
4602 case lltok::kw_fptrunc:
4603 case lltok::kw_fpext:
4604 case lltok::kw_bitcast:
4605 case lltok::kw_addrspacecast:
4606 case lltok::kw_uitofp:
4607 case lltok::kw_sitofp:
4608 case lltok::kw_fptoui:
4609 case lltok::kw_fptosi:
4610 case lltok::kw_inttoptr:
4611 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4613 case lltok::kw_select: return ParseSelect(Inst, PFS);
4614 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4615 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4616 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4617 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4618 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4619 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4621 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4622 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4623 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4625 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4626 case lltok::kw_load: return ParseLoad(Inst, PFS);
4627 case lltok::kw_store: return ParseStore(Inst, PFS);
4628 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4629 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4630 case lltok::kw_fence: return ParseFence(Inst, PFS);
4631 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4632 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4633 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4637 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4638 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4639 if (Opc == Instruction::FCmp) {
4640 switch (Lex.getKind()) {
4641 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4642 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4643 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4644 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4645 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4646 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4647 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4648 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4649 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4650 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4651 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4652 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4653 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4654 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4655 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4656 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4657 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4660 switch (Lex.getKind()) {
4661 default: return TokError("expected icmp predicate (e.g. 'eq')");
4662 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4663 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4664 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4665 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4666 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4667 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4668 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4669 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4670 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4671 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4678 //===----------------------------------------------------------------------===//
4679 // Terminator Instructions.
4680 //===----------------------------------------------------------------------===//
4682 /// ParseRet - Parse a return instruction.
4683 /// ::= 'ret' void (',' !dbg, !1)*
4684 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4685 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4686 PerFunctionState &PFS) {
4687 SMLoc TypeLoc = Lex.getLoc();
4689 if (ParseType(Ty, true /*void allowed*/)) return true;
4691 Type *ResType = PFS.getFunction().getReturnType();
4693 if (Ty->isVoidTy()) {
4694 if (!ResType->isVoidTy())
4695 return Error(TypeLoc, "value doesn't match function result type '" +
4696 getTypeString(ResType) + "'");
4698 Inst = ReturnInst::Create(Context);
4703 if (ParseValue(Ty, RV, PFS)) return true;
4705 if (ResType != RV->getType())
4706 return Error(TypeLoc, "value doesn't match function result type '" +
4707 getTypeString(ResType) + "'");
4709 Inst = ReturnInst::Create(Context, RV);
4715 /// ::= 'br' TypeAndValue
4716 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4717 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4720 BasicBlock *Op1, *Op2;
4721 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4723 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4724 Inst = BranchInst::Create(BB);
4728 if (Op0->getType() != Type::getInt1Ty(Context))
4729 return Error(Loc, "branch condition must have 'i1' type");
4731 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4732 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4733 ParseToken(lltok::comma, "expected ',' after true destination") ||
4734 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4737 Inst = BranchInst::Create(Op1, Op2, Op0);
4743 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4745 /// ::= (TypeAndValue ',' TypeAndValue)*
4746 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4747 LocTy CondLoc, BBLoc;
4749 BasicBlock *DefaultBB;
4750 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4751 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4752 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4753 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4756 if (!Cond->getType()->isIntegerTy())
4757 return Error(CondLoc, "switch condition must have integer type");
4759 // Parse the jump table pairs.
4760 SmallPtrSet<Value*, 32> SeenCases;
4761 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4762 while (Lex.getKind() != lltok::rsquare) {
4766 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4767 ParseToken(lltok::comma, "expected ',' after case value") ||
4768 ParseTypeAndBasicBlock(DestBB, PFS))
4771 if (!SeenCases.insert(Constant).second)
4772 return Error(CondLoc, "duplicate case value in switch");
4773 if (!isa<ConstantInt>(Constant))
4774 return Error(CondLoc, "case value is not a constant integer");
4776 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4779 Lex.Lex(); // Eat the ']'.
4781 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4782 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4783 SI->addCase(Table[i].first, Table[i].second);
4790 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4791 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4794 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4795 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4796 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4799 if (!Address->getType()->isPointerTy())
4800 return Error(AddrLoc, "indirectbr address must have pointer type");
4802 // Parse the destination list.
4803 SmallVector<BasicBlock*, 16> DestList;
4805 if (Lex.getKind() != lltok::rsquare) {
4807 if (ParseTypeAndBasicBlock(DestBB, PFS))
4809 DestList.push_back(DestBB);
4811 while (EatIfPresent(lltok::comma)) {
4812 if (ParseTypeAndBasicBlock(DestBB, PFS))
4814 DestList.push_back(DestBB);
4818 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4821 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4822 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4823 IBI->addDestination(DestList[i]);
4830 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4831 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4832 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4833 LocTy CallLoc = Lex.getLoc();
4834 AttrBuilder RetAttrs, FnAttrs;
4835 std::vector<unsigned> FwdRefAttrGrps;
4838 Type *RetType = nullptr;
4841 SmallVector<ParamInfo, 16> ArgList;
4843 BasicBlock *NormalBB, *UnwindBB;
4844 if (ParseOptionalCallingConv(CC) ||
4845 ParseOptionalReturnAttrs(RetAttrs) ||
4846 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4847 ParseValID(CalleeID) ||
4848 ParseParameterList(ArgList, PFS) ||
4849 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4851 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4852 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4853 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4854 ParseTypeAndBasicBlock(UnwindBB, PFS))
4857 // If RetType is a non-function pointer type, then this is the short syntax
4858 // for the call, which means that RetType is just the return type. Infer the
4859 // rest of the function argument types from the arguments that are present.
4860 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4862 // Pull out the types of all of the arguments...
4863 std::vector<Type*> ParamTypes;
4864 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4865 ParamTypes.push_back(ArgList[i].V->getType());
4867 if (!FunctionType::isValidReturnType(RetType))
4868 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4870 Ty = FunctionType::get(RetType, ParamTypes, false);
4875 // Look up the callee.
4877 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4880 // Set up the Attribute for the function.
4881 SmallVector<AttributeSet, 8> Attrs;
4882 if (RetAttrs.hasAttributes())
4883 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4884 AttributeSet::ReturnIndex,
4887 SmallVector<Value*, 8> Args;
4889 // Loop through FunctionType's arguments and ensure they are specified
4890 // correctly. Also, gather any parameter attributes.
4891 FunctionType::param_iterator I = Ty->param_begin();
4892 FunctionType::param_iterator E = Ty->param_end();
4893 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4894 Type *ExpectedTy = nullptr;
4897 } else if (!Ty->isVarArg()) {
4898 return Error(ArgList[i].Loc, "too many arguments specified");
4901 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4902 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4903 getTypeString(ExpectedTy) + "'");
4904 Args.push_back(ArgList[i].V);
4905 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4906 AttrBuilder B(ArgList[i].Attrs, i + 1);
4907 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4912 return Error(CallLoc, "not enough parameters specified for call");
4914 if (FnAttrs.hasAttributes()) {
4915 if (FnAttrs.hasAlignmentAttr())
4916 return Error(CallLoc, "invoke instructions may not have an alignment");
4918 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4919 AttributeSet::FunctionIndex,
4923 // Finish off the Attribute and check them
4924 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4926 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4927 II->setCallingConv(CC);
4928 II->setAttributes(PAL);
4929 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4935 /// ::= 'resume' TypeAndValue
4936 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4937 Value *Exn; LocTy ExnLoc;
4938 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4941 ResumeInst *RI = ResumeInst::Create(Exn);
4946 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
4947 PerFunctionState &PFS) {
4948 if (ParseToken(lltok::lsquare, "expected '[' in cleanuppad"))
4951 while (Lex.getKind() != lltok::rsquare) {
4952 // If this isn't the first argument, we need a comma.
4953 if (!Args.empty() &&
4954 ParseToken(lltok::comma, "expected ',' in argument list"))
4957 // Parse the argument.
4959 Type *ArgTy = nullptr;
4960 if (ParseType(ArgTy, ArgLoc))
4964 if (ArgTy->isMetadataTy()) {
4965 if (ParseMetadataAsValue(V, PFS))
4968 if (ParseValue(ArgTy, V, PFS))
4974 Lex.Lex(); // Lex the ']'.
4979 /// ::= 'cleanupret' ('void' | TypeAndValue) unwind ('to' 'caller' | TypeAndValue)
4980 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
4981 Type *RetTy = nullptr;
4982 Value *RetVal = nullptr;
4983 if (ParseType(RetTy, /*AllowVoid=*/true))
4986 if (!RetTy->isVoidTy())
4987 if (ParseValue(RetTy, RetVal, PFS))
4990 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
4993 BasicBlock *UnwindBB = nullptr;
4994 if (Lex.getKind() == lltok::kw_to) {
4996 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
4999 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5004 Inst = CleanupReturnInst::Create(Context, RetVal, UnwindBB);
5009 /// ::= 'catchret' TypeAndValue
5010 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5012 if (ParseTypeAndBasicBlock(BB, PFS))
5015 Inst = CatchReturnInst::Create(BB);
5020 /// ::= 'catchpad' Type ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5021 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5022 Type *RetType = nullptr;
5024 SmallVector<Value *, 8> Args;
5025 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5028 BasicBlock *NormalBB, *UnwindBB;
5029 if (ParseToken(lltok::kw_to, "expected 'to' in catchpad") ||
5030 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5031 ParseToken(lltok::kw_unwind, "expected 'unwind' in catchpad") ||
5032 ParseTypeAndBasicBlock(UnwindBB, PFS))
5035 Inst = CatchPadInst::Create(RetType, NormalBB, UnwindBB, Args);
5039 /// ParseTerminatePad
5040 /// ::= 'terminatepad' ParamList 'to' TypeAndValue
5041 bool LLParser::ParseTerminatePad(Instruction *&Inst, PerFunctionState &PFS) {
5042 SmallVector<Value *, 8> Args;
5043 if (ParseExceptionArgs(Args, PFS))
5046 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in terminatepad"))
5049 BasicBlock *UnwindBB = nullptr;
5050 if (Lex.getKind() == lltok::kw_to) {
5052 if (ParseToken(lltok::kw_caller, "expected 'caller' in terminatepad"))
5055 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5060 Inst = TerminatePadInst::Create(Context, UnwindBB, Args);
5065 /// ::= 'cleanuppad' ParamList
5066 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5067 Type *RetType = nullptr;
5069 SmallVector<Value *, 8> Args;
5070 if (ParseType(RetType, /*AllowVoid=*/true) || ParseExceptionArgs(Args, PFS))
5073 Inst = CleanupPadInst::Create(RetType, Args);
5077 /// ParseCatchEndPad
5078 /// ::= 'catchendpad' unwind ('to' 'caller' | TypeAndValue)
5079 bool LLParser::ParseCatchEndPad(Instruction *&Inst, PerFunctionState &PFS) {
5080 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in catchendpad"))
5083 BasicBlock *UnwindBB = nullptr;
5084 if (Lex.getKind() == lltok::kw_to) {
5086 if (Lex.getKind() == lltok::kw_caller) {
5092 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5097 Inst = CatchEndPadInst::Create(Context, UnwindBB);
5101 //===----------------------------------------------------------------------===//
5102 // Binary Operators.
5103 //===----------------------------------------------------------------------===//
5106 /// ::= ArithmeticOps TypeAndValue ',' Value
5108 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5109 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5110 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5111 unsigned Opc, unsigned OperandType) {
5112 LocTy Loc; Value *LHS, *RHS;
5113 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5114 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5115 ParseValue(LHS->getType(), RHS, PFS))
5119 switch (OperandType) {
5120 default: llvm_unreachable("Unknown operand type!");
5121 case 0: // int or FP.
5122 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5123 LHS->getType()->isFPOrFPVectorTy();
5125 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5126 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5130 return Error(Loc, "invalid operand type for instruction");
5132 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5137 /// ::= ArithmeticOps TypeAndValue ',' Value {
5138 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5140 LocTy Loc; Value *LHS, *RHS;
5141 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5142 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5143 ParseValue(LHS->getType(), RHS, PFS))
5146 if (!LHS->getType()->isIntOrIntVectorTy())
5147 return Error(Loc,"instruction requires integer or integer vector operands");
5149 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5155 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5156 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5157 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5159 // Parse the integer/fp comparison predicate.
5163 if (ParseCmpPredicate(Pred, Opc) ||
5164 ParseTypeAndValue(LHS, Loc, PFS) ||
5165 ParseToken(lltok::comma, "expected ',' after compare value") ||
5166 ParseValue(LHS->getType(), RHS, PFS))
5169 if (Opc == Instruction::FCmp) {
5170 if (!LHS->getType()->isFPOrFPVectorTy())
5171 return Error(Loc, "fcmp requires floating point operands");
5172 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5174 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5175 if (!LHS->getType()->isIntOrIntVectorTy() &&
5176 !LHS->getType()->getScalarType()->isPointerTy())
5177 return Error(Loc, "icmp requires integer operands");
5178 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5183 //===----------------------------------------------------------------------===//
5184 // Other Instructions.
5185 //===----------------------------------------------------------------------===//
5189 /// ::= CastOpc TypeAndValue 'to' Type
5190 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5194 Type *DestTy = nullptr;
5195 if (ParseTypeAndValue(Op, Loc, PFS) ||
5196 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5200 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5201 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5202 return Error(Loc, "invalid cast opcode for cast from '" +
5203 getTypeString(Op->getType()) + "' to '" +
5204 getTypeString(DestTy) + "'");
5206 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5211 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5212 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5214 Value *Op0, *Op1, *Op2;
5215 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5216 ParseToken(lltok::comma, "expected ',' after select condition") ||
5217 ParseTypeAndValue(Op1, PFS) ||
5218 ParseToken(lltok::comma, "expected ',' after select value") ||
5219 ParseTypeAndValue(Op2, PFS))
5222 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5223 return Error(Loc, Reason);
5225 Inst = SelectInst::Create(Op0, Op1, Op2);
5230 /// ::= 'va_arg' TypeAndValue ',' Type
5231 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5233 Type *EltTy = nullptr;
5235 if (ParseTypeAndValue(Op, PFS) ||
5236 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5237 ParseType(EltTy, TypeLoc))
5240 if (!EltTy->isFirstClassType())
5241 return Error(TypeLoc, "va_arg requires operand with first class type");
5243 Inst = new VAArgInst(Op, EltTy);
5247 /// ParseExtractElement
5248 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5249 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5252 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5253 ParseToken(lltok::comma, "expected ',' after extract value") ||
5254 ParseTypeAndValue(Op1, PFS))
5257 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5258 return Error(Loc, "invalid extractelement operands");
5260 Inst = ExtractElementInst::Create(Op0, Op1);
5264 /// ParseInsertElement
5265 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5266 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5268 Value *Op0, *Op1, *Op2;
5269 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5270 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5271 ParseTypeAndValue(Op1, PFS) ||
5272 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5273 ParseTypeAndValue(Op2, PFS))
5276 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5277 return Error(Loc, "invalid insertelement operands");
5279 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5283 /// ParseShuffleVector
5284 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5285 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5287 Value *Op0, *Op1, *Op2;
5288 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5289 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5290 ParseTypeAndValue(Op1, PFS) ||
5291 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5292 ParseTypeAndValue(Op2, PFS))
5295 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5296 return Error(Loc, "invalid shufflevector operands");
5298 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5303 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5304 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5305 Type *Ty = nullptr; LocTy TypeLoc;
5308 if (ParseType(Ty, TypeLoc) ||
5309 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5310 ParseValue(Ty, Op0, PFS) ||
5311 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5312 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5313 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5316 bool AteExtraComma = false;
5317 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5319 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5321 if (!EatIfPresent(lltok::comma))
5324 if (Lex.getKind() == lltok::MetadataVar) {
5325 AteExtraComma = true;
5329 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5330 ParseValue(Ty, Op0, PFS) ||
5331 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5332 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5333 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5337 if (!Ty->isFirstClassType())
5338 return Error(TypeLoc, "phi node must have first class type");
5340 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5341 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5342 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5344 return AteExtraComma ? InstExtraComma : InstNormal;
5348 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5350 /// ::= 'catch' TypeAndValue
5352 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5353 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5354 Type *Ty = nullptr; LocTy TyLoc;
5356 if (ParseType(Ty, TyLoc))
5359 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5360 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5362 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5363 LandingPadInst::ClauseType CT;
5364 if (EatIfPresent(lltok::kw_catch))
5365 CT = LandingPadInst::Catch;
5366 else if (EatIfPresent(lltok::kw_filter))
5367 CT = LandingPadInst::Filter;
5369 return TokError("expected 'catch' or 'filter' clause type");
5373 if (ParseTypeAndValue(V, VLoc, PFS))
5376 // A 'catch' type expects a non-array constant. A filter clause expects an
5378 if (CT == LandingPadInst::Catch) {
5379 if (isa<ArrayType>(V->getType()))
5380 Error(VLoc, "'catch' clause has an invalid type");
5382 if (!isa<ArrayType>(V->getType()))
5383 Error(VLoc, "'filter' clause has an invalid type");
5386 Constant *CV = dyn_cast<Constant>(V);
5388 return Error(VLoc, "clause argument must be a constant");
5392 Inst = LP.release();
5397 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5398 /// ParameterList OptionalAttrs
5399 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5400 /// ParameterList OptionalAttrs
5401 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5402 /// ParameterList OptionalAttrs
5403 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5404 CallInst::TailCallKind TCK) {
5405 AttrBuilder RetAttrs, FnAttrs;
5406 std::vector<unsigned> FwdRefAttrGrps;
5409 Type *RetType = nullptr;
5412 SmallVector<ParamInfo, 16> ArgList;
5413 LocTy CallLoc = Lex.getLoc();
5415 if ((TCK != CallInst::TCK_None &&
5416 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5417 ParseOptionalCallingConv(CC) ||
5418 ParseOptionalReturnAttrs(RetAttrs) ||
5419 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5420 ParseValID(CalleeID) ||
5421 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5422 PFS.getFunction().isVarArg()) ||
5423 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5427 // If RetType is a non-function pointer type, then this is the short syntax
5428 // for the call, which means that RetType is just the return type. Infer the
5429 // rest of the function argument types from the arguments that are present.
5430 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5432 // Pull out the types of all of the arguments...
5433 std::vector<Type*> ParamTypes;
5434 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5435 ParamTypes.push_back(ArgList[i].V->getType());
5437 if (!FunctionType::isValidReturnType(RetType))
5438 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5440 Ty = FunctionType::get(RetType, ParamTypes, false);
5445 // Look up the callee.
5447 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5450 // Set up the Attribute for the function.
5451 SmallVector<AttributeSet, 8> Attrs;
5452 if (RetAttrs.hasAttributes())
5453 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5454 AttributeSet::ReturnIndex,
5457 SmallVector<Value*, 8> Args;
5459 // Loop through FunctionType's arguments and ensure they are specified
5460 // correctly. Also, gather any parameter attributes.
5461 FunctionType::param_iterator I = Ty->param_begin();
5462 FunctionType::param_iterator E = Ty->param_end();
5463 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5464 Type *ExpectedTy = nullptr;
5467 } else if (!Ty->isVarArg()) {
5468 return Error(ArgList[i].Loc, "too many arguments specified");
5471 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5472 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5473 getTypeString(ExpectedTy) + "'");
5474 Args.push_back(ArgList[i].V);
5475 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5476 AttrBuilder B(ArgList[i].Attrs, i + 1);
5477 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5482 return Error(CallLoc, "not enough parameters specified for call");
5484 if (FnAttrs.hasAttributes()) {
5485 if (FnAttrs.hasAlignmentAttr())
5486 return Error(CallLoc, "call instructions may not have an alignment");
5488 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5489 AttributeSet::FunctionIndex,
5493 // Finish off the Attribute and check them
5494 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5496 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5497 CI->setTailCallKind(TCK);
5498 CI->setCallingConv(CC);
5499 CI->setAttributes(PAL);
5500 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5505 //===----------------------------------------------------------------------===//
5506 // Memory Instructions.
5507 //===----------------------------------------------------------------------===//
5510 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5511 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5512 Value *Size = nullptr;
5513 LocTy SizeLoc, TyLoc;
5514 unsigned Alignment = 0;
5517 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5519 if (ParseType(Ty, TyLoc)) return true;
5521 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5522 return Error(TyLoc, "invalid type for alloca");
5524 bool AteExtraComma = false;
5525 if (EatIfPresent(lltok::comma)) {
5526 if (Lex.getKind() == lltok::kw_align) {
5527 if (ParseOptionalAlignment(Alignment)) return true;
5528 } else if (Lex.getKind() == lltok::MetadataVar) {
5529 AteExtraComma = true;
5531 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5532 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5537 if (Size && !Size->getType()->isIntegerTy())
5538 return Error(SizeLoc, "element count must have integer type");
5540 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5541 AI->setUsedWithInAlloca(IsInAlloca);
5543 return AteExtraComma ? InstExtraComma : InstNormal;
5547 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5548 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5549 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5550 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5551 Value *Val; LocTy Loc;
5552 unsigned Alignment = 0;
5553 bool AteExtraComma = false;
5554 bool isAtomic = false;
5555 AtomicOrdering Ordering = NotAtomic;
5556 SynchronizationScope Scope = CrossThread;
5558 if (Lex.getKind() == lltok::kw_atomic) {
5563 bool isVolatile = false;
5564 if (Lex.getKind() == lltok::kw_volatile) {
5570 LocTy ExplicitTypeLoc = Lex.getLoc();
5571 if (ParseType(Ty) ||
5572 ParseToken(lltok::comma, "expected comma after load's type") ||
5573 ParseTypeAndValue(Val, Loc, PFS) ||
5574 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5575 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5578 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5579 return Error(Loc, "load operand must be a pointer to a first class type");
5580 if (isAtomic && !Alignment)
5581 return Error(Loc, "atomic load must have explicit non-zero alignment");
5582 if (Ordering == Release || Ordering == AcquireRelease)
5583 return Error(Loc, "atomic load cannot use Release ordering");
5585 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5586 return Error(ExplicitTypeLoc,
5587 "explicit pointee type doesn't match operand's pointee type");
5589 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5590 return AteExtraComma ? InstExtraComma : InstNormal;
5595 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5596 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5597 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5598 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5599 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5600 unsigned Alignment = 0;
5601 bool AteExtraComma = false;
5602 bool isAtomic = false;
5603 AtomicOrdering Ordering = NotAtomic;
5604 SynchronizationScope Scope = CrossThread;
5606 if (Lex.getKind() == lltok::kw_atomic) {
5611 bool isVolatile = false;
5612 if (Lex.getKind() == lltok::kw_volatile) {
5617 if (ParseTypeAndValue(Val, Loc, PFS) ||
5618 ParseToken(lltok::comma, "expected ',' after store operand") ||
5619 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5620 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5621 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5624 if (!Ptr->getType()->isPointerTy())
5625 return Error(PtrLoc, "store operand must be a pointer");
5626 if (!Val->getType()->isFirstClassType())
5627 return Error(Loc, "store operand must be a first class value");
5628 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5629 return Error(Loc, "stored value and pointer type do not match");
5630 if (isAtomic && !Alignment)
5631 return Error(Loc, "atomic store must have explicit non-zero alignment");
5632 if (Ordering == Acquire || Ordering == AcquireRelease)
5633 return Error(Loc, "atomic store cannot use Acquire ordering");
5635 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5636 return AteExtraComma ? InstExtraComma : InstNormal;
5640 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5641 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5642 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5643 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5644 bool AteExtraComma = false;
5645 AtomicOrdering SuccessOrdering = NotAtomic;
5646 AtomicOrdering FailureOrdering = NotAtomic;
5647 SynchronizationScope Scope = CrossThread;
5648 bool isVolatile = false;
5649 bool isWeak = false;
5651 if (EatIfPresent(lltok::kw_weak))
5654 if (EatIfPresent(lltok::kw_volatile))
5657 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5658 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5659 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5660 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5661 ParseTypeAndValue(New, NewLoc, PFS) ||
5662 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5663 ParseOrdering(FailureOrdering))
5666 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5667 return TokError("cmpxchg cannot be unordered");
5668 if (SuccessOrdering < FailureOrdering)
5669 return TokError("cmpxchg must be at least as ordered on success as failure");
5670 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5671 return TokError("cmpxchg failure ordering cannot include release semantics");
5672 if (!Ptr->getType()->isPointerTy())
5673 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5674 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5675 return Error(CmpLoc, "compare value and pointer type do not match");
5676 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5677 return Error(NewLoc, "new value and pointer type do not match");
5678 if (!New->getType()->isIntegerTy())
5679 return Error(NewLoc, "cmpxchg operand must be an integer");
5680 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5681 if (Size < 8 || (Size & (Size - 1)))
5682 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5685 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5686 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5687 CXI->setVolatile(isVolatile);
5688 CXI->setWeak(isWeak);
5690 return AteExtraComma ? InstExtraComma : InstNormal;
5694 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5695 /// 'singlethread'? AtomicOrdering
5696 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5697 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5698 bool AteExtraComma = false;
5699 AtomicOrdering Ordering = NotAtomic;
5700 SynchronizationScope Scope = CrossThread;
5701 bool isVolatile = false;
5702 AtomicRMWInst::BinOp Operation;
5704 if (EatIfPresent(lltok::kw_volatile))
5707 switch (Lex.getKind()) {
5708 default: return TokError("expected binary operation in atomicrmw");
5709 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5710 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5711 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5712 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5713 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5714 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5715 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5716 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5717 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5718 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5719 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5721 Lex.Lex(); // Eat the operation.
5723 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5724 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5725 ParseTypeAndValue(Val, ValLoc, PFS) ||
5726 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5729 if (Ordering == Unordered)
5730 return TokError("atomicrmw cannot be unordered");
5731 if (!Ptr->getType()->isPointerTy())
5732 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5733 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5734 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5735 if (!Val->getType()->isIntegerTy())
5736 return Error(ValLoc, "atomicrmw operand must be an integer");
5737 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5738 if (Size < 8 || (Size & (Size - 1)))
5739 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5742 AtomicRMWInst *RMWI =
5743 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5744 RMWI->setVolatile(isVolatile);
5746 return AteExtraComma ? InstExtraComma : InstNormal;
5750 /// ::= 'fence' 'singlethread'? AtomicOrdering
5751 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5752 AtomicOrdering Ordering = NotAtomic;
5753 SynchronizationScope Scope = CrossThread;
5754 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5757 if (Ordering == Unordered)
5758 return TokError("fence cannot be unordered");
5759 if (Ordering == Monotonic)
5760 return TokError("fence cannot be monotonic");
5762 Inst = new FenceInst(Context, Ordering, Scope);
5766 /// ParseGetElementPtr
5767 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5768 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5769 Value *Ptr = nullptr;
5770 Value *Val = nullptr;
5773 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5776 LocTy ExplicitTypeLoc = Lex.getLoc();
5777 if (ParseType(Ty) ||
5778 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5779 ParseTypeAndValue(Ptr, Loc, PFS))
5782 Type *BaseType = Ptr->getType();
5783 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5784 if (!BasePointerType)
5785 return Error(Loc, "base of getelementptr must be a pointer");
5787 if (Ty != BasePointerType->getElementType())
5788 return Error(ExplicitTypeLoc,
5789 "explicit pointee type doesn't match operand's pointee type");
5791 SmallVector<Value*, 16> Indices;
5792 bool AteExtraComma = false;
5793 // GEP returns a vector of pointers if at least one of parameters is a vector.
5794 // All vector parameters should have the same vector width.
5795 unsigned GEPWidth = BaseType->isVectorTy() ?
5796 BaseType->getVectorNumElements() : 0;
5798 while (EatIfPresent(lltok::comma)) {
5799 if (Lex.getKind() == lltok::MetadataVar) {
5800 AteExtraComma = true;
5803 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5804 if (!Val->getType()->getScalarType()->isIntegerTy())
5805 return Error(EltLoc, "getelementptr index must be an integer");
5807 if (Val->getType()->isVectorTy()) {
5808 unsigned ValNumEl = Val->getType()->getVectorNumElements();
5809 if (GEPWidth && GEPWidth != ValNumEl)
5810 return Error(EltLoc,
5811 "getelementptr vector index has a wrong number of elements");
5812 GEPWidth = ValNumEl;
5814 Indices.push_back(Val);
5817 SmallPtrSet<const Type*, 4> Visited;
5818 if (!Indices.empty() && !Ty->isSized(&Visited))
5819 return Error(Loc, "base element of getelementptr must be sized");
5821 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5822 return Error(Loc, "invalid getelementptr indices");
5823 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5825 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5826 return AteExtraComma ? InstExtraComma : InstNormal;
5829 /// ParseExtractValue
5830 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5831 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5832 Value *Val; LocTy Loc;
5833 SmallVector<unsigned, 4> Indices;
5835 if (ParseTypeAndValue(Val, Loc, PFS) ||
5836 ParseIndexList(Indices, AteExtraComma))
5839 if (!Val->getType()->isAggregateType())
5840 return Error(Loc, "extractvalue operand must be aggregate type");
5842 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5843 return Error(Loc, "invalid indices for extractvalue");
5844 Inst = ExtractValueInst::Create(Val, Indices);
5845 return AteExtraComma ? InstExtraComma : InstNormal;
5848 /// ParseInsertValue
5849 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5850 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5851 Value *Val0, *Val1; LocTy Loc0, Loc1;
5852 SmallVector<unsigned, 4> Indices;
5854 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5855 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5856 ParseTypeAndValue(Val1, Loc1, PFS) ||
5857 ParseIndexList(Indices, AteExtraComma))
5860 if (!Val0->getType()->isAggregateType())
5861 return Error(Loc0, "insertvalue operand must be aggregate type");
5863 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5865 return Error(Loc0, "invalid indices for insertvalue");
5866 if (IndexedType != Val1->getType())
5867 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5868 getTypeString(Val1->getType()) + "' instead of '" +
5869 getTypeString(IndexedType) + "'");
5870 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5871 return AteExtraComma ? InstExtraComma : InstNormal;
5874 //===----------------------------------------------------------------------===//
5875 // Embedded metadata.
5876 //===----------------------------------------------------------------------===//
5878 /// ParseMDNodeVector
5879 /// ::= { Element (',' Element)* }
5881 /// ::= 'null' | TypeAndValue
5882 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5883 if (ParseToken(lltok::lbrace, "expected '{' here"))
5886 // Check for an empty list.
5887 if (EatIfPresent(lltok::rbrace))
5891 // Null is a special case since it is typeless.
5892 if (EatIfPresent(lltok::kw_null)) {
5893 Elts.push_back(nullptr);
5898 if (ParseMetadata(MD, nullptr))
5901 } while (EatIfPresent(lltok::comma));
5903 return ParseToken(lltok::rbrace, "expected end of metadata node");
5906 //===----------------------------------------------------------------------===//
5907 // Use-list order directives.
5908 //===----------------------------------------------------------------------===//
5909 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5912 return Error(Loc, "value has no uses");
5914 unsigned NumUses = 0;
5915 SmallDenseMap<const Use *, unsigned, 16> Order;
5916 for (const Use &U : V->uses()) {
5917 if (++NumUses > Indexes.size())
5919 Order[&U] = Indexes[NumUses - 1];
5922 return Error(Loc, "value only has one use");
5923 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5924 return Error(Loc, "wrong number of indexes, expected " +
5925 Twine(std::distance(V->use_begin(), V->use_end())));
5927 V->sortUseList([&](const Use &L, const Use &R) {
5928 return Order.lookup(&L) < Order.lookup(&R);
5933 /// ParseUseListOrderIndexes
5934 /// ::= '{' uint32 (',' uint32)+ '}'
5935 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5936 SMLoc Loc = Lex.getLoc();
5937 if (ParseToken(lltok::lbrace, "expected '{' here"))
5939 if (Lex.getKind() == lltok::rbrace)
5940 return Lex.Error("expected non-empty list of uselistorder indexes");
5942 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5943 // indexes should be distinct numbers in the range [0, size-1], and should
5945 unsigned Offset = 0;
5947 bool IsOrdered = true;
5948 assert(Indexes.empty() && "Expected empty order vector");
5951 if (ParseUInt32(Index))
5954 // Update consistency checks.
5955 Offset += Index - Indexes.size();
5956 Max = std::max(Max, Index);
5957 IsOrdered &= Index == Indexes.size();
5959 Indexes.push_back(Index);
5960 } while (EatIfPresent(lltok::comma));
5962 if (ParseToken(lltok::rbrace, "expected '}' here"))
5965 if (Indexes.size() < 2)
5966 return Error(Loc, "expected >= 2 uselistorder indexes");
5967 if (Offset != 0 || Max >= Indexes.size())
5968 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5970 return Error(Loc, "expected uselistorder indexes to change the order");
5975 /// ParseUseListOrder
5976 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5977 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5978 SMLoc Loc = Lex.getLoc();
5979 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5983 SmallVector<unsigned, 16> Indexes;
5984 if (ParseTypeAndValue(V, PFS) ||
5985 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5986 ParseUseListOrderIndexes(Indexes))
5989 return sortUseListOrder(V, Indexes, Loc);
5992 /// ParseUseListOrderBB
5993 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5994 bool LLParser::ParseUseListOrderBB() {
5995 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5996 SMLoc Loc = Lex.getLoc();
6000 SmallVector<unsigned, 16> Indexes;
6001 if (ParseValID(Fn) ||
6002 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6003 ParseValID(Label) ||
6004 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6005 ParseUseListOrderIndexes(Indexes))
6008 // Check the function.
6010 if (Fn.Kind == ValID::t_GlobalName)
6011 GV = M->getNamedValue(Fn.StrVal);
6012 else if (Fn.Kind == ValID::t_GlobalID)
6013 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6015 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6017 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6018 auto *F = dyn_cast<Function>(GV);
6020 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6021 if (F->isDeclaration())
6022 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6024 // Check the basic block.
6025 if (Label.Kind == ValID::t_LocalID)
6026 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6027 if (Label.Kind != ValID::t_LocalName)
6028 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6029 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6031 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6032 if (!isa<BasicBlock>(V))
6033 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6035 return sortUseListOrder(V, Indexes, Loc);