1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/AsmParser/SlotMapping.h"
19 #include "llvm/IR/AutoUpgrade.h"
20 #include "llvm/IR/CallingConv.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DebugInfo.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/ValueSymbolTable.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/SaveAndRestore.h"
37 #include "llvm/Support/raw_ostream.h"
40 static std::string getTypeString(Type *T) {
42 raw_string_ostream Tmp(Result);
47 /// Run: module ::= toplevelentity*
48 bool LLParser::Run() {
52 if (Context.shouldDiscardValueNames())
55 "Can't read textual IR with a Context that discards named Values");
57 return ParseTopLevelEntities() ||
58 ValidateEndOfModule();
61 bool LLParser::parseStandaloneConstantValue(Constant *&C,
62 const SlotMapping *Slots) {
63 restoreParsingState(Slots);
67 if (ParseType(Ty) || parseConstantValue(Ty, C))
69 if (Lex.getKind() != lltok::Eof)
70 return Error(Lex.getLoc(), "expected end of string");
74 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
75 const SlotMapping *Slots) {
76 restoreParsingState(Slots);
80 SMLoc Start = Lex.getLoc();
84 SMLoc End = Lex.getLoc();
85 Read = End.getPointer() - Start.getPointer();
90 void LLParser::restoreParsingState(const SlotMapping *Slots) {
93 NumberedVals = Slots->GlobalValues;
94 NumberedMetadata = Slots->MetadataNodes;
95 for (const auto &I : Slots->NamedTypes)
97 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
98 for (const auto &I : Slots->Types)
100 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
103 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
105 bool LLParser::ValidateEndOfModule() {
106 // Handle any function attribute group forward references.
107 for (std::map<Value*, std::vector<unsigned> >::iterator
108 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
111 std::vector<unsigned> &Vec = I->second;
114 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
116 B.merge(NumberedAttrBuilders[*VI]);
118 if (Function *Fn = dyn_cast<Function>(V)) {
119 AttributeSet AS = Fn->getAttributes();
120 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
121 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
122 AS.getFnAttributes());
126 // If the alignment was parsed as an attribute, move to the alignment
128 if (FnAttrs.hasAlignmentAttr()) {
129 Fn->setAlignment(FnAttrs.getAlignment());
130 FnAttrs.removeAttribute(Attribute::Alignment);
133 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
134 AttributeSet::get(Context,
135 AttributeSet::FunctionIndex,
137 Fn->setAttributes(AS);
138 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
139 AttributeSet AS = CI->getAttributes();
140 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
141 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
142 AS.getFnAttributes());
144 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
145 AttributeSet::get(Context,
146 AttributeSet::FunctionIndex,
148 CI->setAttributes(AS);
149 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
150 AttributeSet AS = II->getAttributes();
151 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
152 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
153 AS.getFnAttributes());
155 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
156 AttributeSet::get(Context,
157 AttributeSet::FunctionIndex,
159 II->setAttributes(AS);
161 llvm_unreachable("invalid object with forward attribute group reference");
165 // If there are entries in ForwardRefBlockAddresses at this point, the
166 // function was never defined.
167 if (!ForwardRefBlockAddresses.empty())
168 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
169 "expected function name in blockaddress");
171 for (const auto &NT : NumberedTypes)
172 if (NT.second.second.isValid())
173 return Error(NT.second.second,
174 "use of undefined type '%" + Twine(NT.first) + "'");
176 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
177 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
178 if (I->second.second.isValid())
179 return Error(I->second.second,
180 "use of undefined type named '" + I->getKey() + "'");
182 if (!ForwardRefComdats.empty())
183 return Error(ForwardRefComdats.begin()->second,
184 "use of undefined comdat '$" +
185 ForwardRefComdats.begin()->first + "'");
187 if (!ForwardRefVals.empty())
188 return Error(ForwardRefVals.begin()->second.second,
189 "use of undefined value '@" + ForwardRefVals.begin()->first +
192 if (!ForwardRefValIDs.empty())
193 return Error(ForwardRefValIDs.begin()->second.second,
194 "use of undefined value '@" +
195 Twine(ForwardRefValIDs.begin()->first) + "'");
197 if (!ForwardRefMDNodes.empty())
198 return Error(ForwardRefMDNodes.begin()->second.second,
199 "use of undefined metadata '!" +
200 Twine(ForwardRefMDNodes.begin()->first) + "'");
202 // Resolve metadata cycles.
203 for (auto &N : NumberedMetadata) {
204 if (N.second && !N.second->isResolved())
205 N.second->resolveCycles();
208 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
209 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
211 // Look for intrinsic functions and CallInst that need to be upgraded
212 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
213 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
215 // Some types could be renamed during loading if several modules are
216 // loaded in the same LLVMContext (LTO scenario). In this case we should
217 // remangle intrinsics names as well.
218 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
219 Function *F = &*FI++;
220 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
221 F->replaceAllUsesWith(Remangled.getValue());
222 F->eraseFromParent();
226 UpgradeDebugInfo(*M);
228 UpgradeModuleFlags(*M);
232 // Initialize the slot mapping.
233 // Because by this point we've parsed and validated everything, we can "steal"
234 // the mapping from LLParser as it doesn't need it anymore.
235 Slots->GlobalValues = std::move(NumberedVals);
236 Slots->MetadataNodes = std::move(NumberedMetadata);
237 for (const auto &I : NamedTypes)
238 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
239 for (const auto &I : NumberedTypes)
240 Slots->Types.insert(std::make_pair(I.first, I.second.first));
245 //===----------------------------------------------------------------------===//
246 // Top-Level Entities
247 //===----------------------------------------------------------------------===//
249 bool LLParser::ParseTopLevelEntities() {
251 switch (Lex.getKind()) {
252 default: return TokError("expected top-level entity");
253 case lltok::Eof: return false;
254 case lltok::kw_declare: if (ParseDeclare()) return true; break;
255 case lltok::kw_define: if (ParseDefine()) return true; break;
256 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
257 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
258 case lltok::kw_source_filename:
259 if (ParseSourceFileName())
262 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
263 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
264 case lltok::LocalVar: if (ParseNamedType()) return true; break;
265 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
266 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
267 case lltok::ComdatVar: if (parseComdat()) return true; break;
268 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
269 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
270 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
271 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
272 case lltok::kw_uselistorder_bb:
273 if (ParseUseListOrderBB()) return true; break;
280 /// ::= 'module' 'asm' STRINGCONSTANT
281 bool LLParser::ParseModuleAsm() {
282 assert(Lex.getKind() == lltok::kw_module);
286 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
287 ParseStringConstant(AsmStr)) return true;
289 M->appendModuleInlineAsm(AsmStr);
294 /// ::= 'target' 'triple' '=' STRINGCONSTANT
295 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
296 bool LLParser::ParseTargetDefinition() {
297 assert(Lex.getKind() == lltok::kw_target);
300 default: return TokError("unknown target property");
301 case lltok::kw_triple:
303 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
304 ParseStringConstant(Str))
306 M->setTargetTriple(Str);
308 case lltok::kw_datalayout:
310 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
311 ParseStringConstant(Str))
313 M->setDataLayout(Str);
319 /// ::= 'source_filename' '=' STRINGCONSTANT
320 bool LLParser::ParseSourceFileName() {
321 assert(Lex.getKind() == lltok::kw_source_filename);
324 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
325 ParseStringConstant(Str))
327 M->setSourceFileName(Str);
332 /// ::= 'deplibs' '=' '[' ']'
333 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334 /// FIXME: Remove in 4.0. Currently parse, but ignore.
335 bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
342 if (EatIfPresent(lltok::rsquare))
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
353 /// ParseUnnamedType:
354 /// ::= LocalVarID '=' 'type' type
355 bool LLParser::ParseUnnamedType() {
356 LocTy TypeLoc = Lex.getLoc();
357 unsigned TypeID = Lex.getUIntVal();
358 Lex.Lex(); // eat LocalVarID;
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
364 Type *Result = nullptr;
365 if (ParseStructDefinition(TypeLoc, "",
366 NumberedTypes[TypeID], Result)) return true;
368 if (!isa<StructType>(Result)) {
369 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
371 return Error(TypeLoc, "non-struct types may not be recursive");
372 Entry.first = Result;
373 Entry.second = SMLoc();
381 /// ::= LocalVar '=' 'type' type
382 bool LLParser::ParseNamedType() {
383 std::string Name = Lex.getStrVal();
384 LocTy NameLoc = Lex.getLoc();
385 Lex.Lex(); // eat LocalVar.
387 if (ParseToken(lltok::equal, "expected '=' after name") ||
388 ParseToken(lltok::kw_type, "expected 'type' after name"))
391 Type *Result = nullptr;
392 if (ParseStructDefinition(NameLoc, Name,
393 NamedTypes[Name], Result)) return true;
395 if (!isa<StructType>(Result)) {
396 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
398 return Error(NameLoc, "non-struct types may not be recursive");
399 Entry.first = Result;
400 Entry.second = SMLoc();
408 /// ::= 'declare' FunctionHeader
409 bool LLParser::ParseDeclare() {
410 assert(Lex.getKind() == lltok::kw_declare);
413 std::vector<std::pair<unsigned, MDNode *>> MDs;
414 while (Lex.getKind() == lltok::MetadataVar) {
417 if (ParseMetadataAttachment(MDK, N))
419 MDs.push_back({MDK, N});
423 if (ParseFunctionHeader(F, false))
426 F->addMetadata(MD.first, *MD.second);
431 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
432 bool LLParser::ParseDefine() {
433 assert(Lex.getKind() == lltok::kw_define);
437 return ParseFunctionHeader(F, true) ||
438 ParseOptionalFunctionMetadata(*F) ||
439 ParseFunctionBody(*F);
445 bool LLParser::ParseGlobalType(bool &IsConstant) {
446 if (Lex.getKind() == lltok::kw_constant)
448 else if (Lex.getKind() == lltok::kw_global)
452 return TokError("expected 'global' or 'constant'");
458 bool LLParser::ParseOptionalUnnamedAddr(
459 GlobalVariable::UnnamedAddr &UnnamedAddr) {
460 if (EatIfPresent(lltok::kw_unnamed_addr))
461 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
462 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
463 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
465 UnnamedAddr = GlobalValue::UnnamedAddr::None;
469 /// ParseUnnamedGlobal:
470 /// OptionalVisibility (ALIAS | IFUNC) ...
471 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
472 /// ... -> global variable
473 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
474 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
475 /// ... -> global variable
476 bool LLParser::ParseUnnamedGlobal() {
477 unsigned VarID = NumberedVals.size();
479 LocTy NameLoc = Lex.getLoc();
481 // Handle the GlobalID form.
482 if (Lex.getKind() == lltok::GlobalID) {
483 if (Lex.getUIntVal() != VarID)
484 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
486 Lex.Lex(); // eat GlobalID;
488 if (ParseToken(lltok::equal, "expected '=' after name"))
493 unsigned Linkage, Visibility, DLLStorageClass;
494 GlobalVariable::ThreadLocalMode TLM;
495 GlobalVariable::UnnamedAddr UnnamedAddr;
496 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
497 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
500 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
501 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
502 DLLStorageClass, TLM, UnnamedAddr);
504 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
505 DLLStorageClass, TLM, UnnamedAddr);
508 /// ParseNamedGlobal:
509 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
510 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
511 /// ... -> global variable
512 bool LLParser::ParseNamedGlobal() {
513 assert(Lex.getKind() == lltok::GlobalVar);
514 LocTy NameLoc = Lex.getLoc();
515 std::string Name = Lex.getStrVal();
519 unsigned Linkage, Visibility, DLLStorageClass;
520 GlobalVariable::ThreadLocalMode TLM;
521 GlobalVariable::UnnamedAddr UnnamedAddr;
522 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
523 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
524 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
527 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
528 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
529 DLLStorageClass, TLM, UnnamedAddr);
531 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
532 DLLStorageClass, TLM, UnnamedAddr);
535 bool LLParser::parseComdat() {
536 assert(Lex.getKind() == lltok::ComdatVar);
537 std::string Name = Lex.getStrVal();
538 LocTy NameLoc = Lex.getLoc();
541 if (ParseToken(lltok::equal, "expected '=' here"))
544 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
545 return TokError("expected comdat type");
547 Comdat::SelectionKind SK;
548 switch (Lex.getKind()) {
550 return TokError("unknown selection kind");
554 case lltok::kw_exactmatch:
555 SK = Comdat::ExactMatch;
557 case lltok::kw_largest:
558 SK = Comdat::Largest;
560 case lltok::kw_noduplicates:
561 SK = Comdat::NoDuplicates;
563 case lltok::kw_samesize:
564 SK = Comdat::SameSize;
569 // See if the comdat was forward referenced, if so, use the comdat.
570 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
571 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
572 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
573 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
576 if (I != ComdatSymTab.end())
579 C = M->getOrInsertComdat(Name);
580 C->setSelectionKind(SK);
586 // ::= '!' STRINGCONSTANT
587 bool LLParser::ParseMDString(MDString *&Result) {
589 if (ParseStringConstant(Str)) return true;
590 Result = MDString::get(Context, Str);
595 // ::= '!' MDNodeNumber
596 bool LLParser::ParseMDNodeID(MDNode *&Result) {
597 // !{ ..., !42, ... }
598 LocTy IDLoc = Lex.getLoc();
600 if (ParseUInt32(MID))
603 // If not a forward reference, just return it now.
604 if (NumberedMetadata.count(MID)) {
605 Result = NumberedMetadata[MID];
609 // Otherwise, create MDNode forward reference.
610 auto &FwdRef = ForwardRefMDNodes[MID];
611 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
613 Result = FwdRef.first.get();
614 NumberedMetadata[MID].reset(Result);
618 /// ParseNamedMetadata:
619 /// !foo = !{ !1, !2 }
620 bool LLParser::ParseNamedMetadata() {
621 assert(Lex.getKind() == lltok::MetadataVar);
622 std::string Name = Lex.getStrVal();
625 if (ParseToken(lltok::equal, "expected '=' here") ||
626 ParseToken(lltok::exclaim, "Expected '!' here") ||
627 ParseToken(lltok::lbrace, "Expected '{' here"))
630 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
631 if (Lex.getKind() != lltok::rbrace)
633 if (ParseToken(lltok::exclaim, "Expected '!' here"))
637 if (ParseMDNodeID(N)) return true;
639 } while (EatIfPresent(lltok::comma));
641 return ParseToken(lltok::rbrace, "expected end of metadata node");
644 /// ParseStandaloneMetadata:
646 bool LLParser::ParseStandaloneMetadata() {
647 assert(Lex.getKind() == lltok::exclaim);
649 unsigned MetadataID = 0;
652 if (ParseUInt32(MetadataID) ||
653 ParseToken(lltok::equal, "expected '=' here"))
656 // Detect common error, from old metadata syntax.
657 if (Lex.getKind() == lltok::Type)
658 return TokError("unexpected type in metadata definition");
660 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
661 if (Lex.getKind() == lltok::MetadataVar) {
662 if (ParseSpecializedMDNode(Init, IsDistinct))
664 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
665 ParseMDTuple(Init, IsDistinct))
668 // See if this was forward referenced, if so, handle it.
669 auto FI = ForwardRefMDNodes.find(MetadataID);
670 if (FI != ForwardRefMDNodes.end()) {
671 FI->second.first->replaceAllUsesWith(Init);
672 ForwardRefMDNodes.erase(FI);
674 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
676 if (NumberedMetadata.count(MetadataID))
677 return TokError("Metadata id is already used");
678 NumberedMetadata[MetadataID].reset(Init);
684 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
685 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
686 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
689 /// parseIndirectSymbol:
690 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
691 /// OptionalDLLStorageClass OptionalThreadLocal
692 /// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
697 /// Everything through OptionalUnnamedAddr has already been parsed.
699 bool LLParser::parseIndirectSymbol(
700 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
701 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
702 GlobalVariable::UnnamedAddr UnnamedAddr) {
704 if (Lex.getKind() == lltok::kw_alias)
706 else if (Lex.getKind() == lltok::kw_ifunc)
709 llvm_unreachable("Not an alias or ifunc!");
712 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
714 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
715 return Error(NameLoc, "invalid linkage type for alias");
717 if (!isValidVisibilityForLinkage(Visibility, L))
718 return Error(NameLoc,
719 "symbol with local linkage must have default visibility");
722 LocTy ExplicitTypeLoc = Lex.getLoc();
724 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
728 LocTy AliaseeLoc = Lex.getLoc();
729 if (Lex.getKind() != lltok::kw_bitcast &&
730 Lex.getKind() != lltok::kw_getelementptr &&
731 Lex.getKind() != lltok::kw_addrspacecast &&
732 Lex.getKind() != lltok::kw_inttoptr) {
733 if (ParseGlobalTypeAndValue(Aliasee))
736 // The bitcast dest type is not present, it is implied by the dest type.
740 if (ID.Kind != ValID::t_Constant)
741 return Error(AliaseeLoc, "invalid aliasee");
742 Aliasee = ID.ConstantVal;
745 Type *AliaseeType = Aliasee->getType();
746 auto *PTy = dyn_cast<PointerType>(AliaseeType);
748 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
749 unsigned AddrSpace = PTy->getAddressSpace();
751 if (IsAlias && Ty != PTy->getElementType())
754 "explicit pointee type doesn't match operand's pointee type");
756 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
759 "explicit pointee type should be a function type");
761 GlobalValue *GVal = nullptr;
763 // See if the alias was forward referenced, if so, prepare to replace the
764 // forward reference.
766 GVal = M->getNamedValue(Name);
768 if (!ForwardRefVals.erase(Name))
769 return Error(NameLoc, "redefinition of global '@" + Name + "'");
772 auto I = ForwardRefValIDs.find(NumberedVals.size());
773 if (I != ForwardRefValIDs.end()) {
774 GVal = I->second.first;
775 ForwardRefValIDs.erase(I);
779 // Okay, create the alias but do not insert it into the module yet.
780 std::unique_ptr<GlobalIndirectSymbol> GA;
782 GA.reset(GlobalAlias::create(Ty, AddrSpace,
783 (GlobalValue::LinkageTypes)Linkage, Name,
784 Aliasee, /*Parent*/ nullptr));
786 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
787 (GlobalValue::LinkageTypes)Linkage, Name,
788 Aliasee, /*Parent*/ nullptr));
789 GA->setThreadLocalMode(TLM);
790 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
791 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
792 GA->setUnnamedAddr(UnnamedAddr);
795 NumberedVals.push_back(GA.get());
798 // Verify that types agree.
799 if (GVal->getType() != GA->getType())
802 "forward reference and definition of alias have different types");
804 // If they agree, just RAUW the old value with the alias and remove the
806 GVal->replaceAllUsesWith(GA.get());
807 GVal->eraseFromParent();
810 // Insert into the module, we know its name won't collide now.
812 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
814 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
815 assert(GA->getName() == Name && "Should not be a name conflict!");
817 // The module owns this now
824 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
825 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
826 /// OptionalExternallyInitialized GlobalType Type Const
827 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
828 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
829 /// OptionalExternallyInitialized GlobalType Type Const
831 /// Everything up to and including OptionalUnnamedAddr has been parsed
834 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
835 unsigned Linkage, bool HasLinkage,
836 unsigned Visibility, unsigned DLLStorageClass,
837 GlobalVariable::ThreadLocalMode TLM,
838 GlobalVariable::UnnamedAddr UnnamedAddr) {
839 if (!isValidVisibilityForLinkage(Visibility, Linkage))
840 return Error(NameLoc,
841 "symbol with local linkage must have default visibility");
844 bool IsConstant, IsExternallyInitialized;
845 LocTy IsExternallyInitializedLoc;
849 if (ParseOptionalAddrSpace(AddrSpace) ||
850 ParseOptionalToken(lltok::kw_externally_initialized,
851 IsExternallyInitialized,
852 &IsExternallyInitializedLoc) ||
853 ParseGlobalType(IsConstant) ||
854 ParseType(Ty, TyLoc))
857 // If the linkage is specified and is external, then no initializer is
859 Constant *Init = nullptr;
861 !GlobalValue::isValidDeclarationLinkage(
862 (GlobalValue::LinkageTypes)Linkage)) {
863 if (ParseGlobalValue(Ty, Init))
867 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
868 return Error(TyLoc, "invalid type for global variable");
870 GlobalValue *GVal = nullptr;
872 // See if the global was forward referenced, if so, use the global.
874 GVal = M->getNamedValue(Name);
876 if (!ForwardRefVals.erase(Name))
877 return Error(NameLoc, "redefinition of global '@" + Name + "'");
880 auto I = ForwardRefValIDs.find(NumberedVals.size());
881 if (I != ForwardRefValIDs.end()) {
882 GVal = I->second.first;
883 ForwardRefValIDs.erase(I);
889 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
890 Name, nullptr, GlobalVariable::NotThreadLocal,
893 if (GVal->getValueType() != Ty)
895 "forward reference and definition of global have different types");
897 GV = cast<GlobalVariable>(GVal);
899 // Move the forward-reference to the correct spot in the module.
900 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
904 NumberedVals.push_back(GV);
906 // Set the parsed properties on the global.
908 GV->setInitializer(Init);
909 GV->setConstant(IsConstant);
910 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
911 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
912 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
913 GV->setExternallyInitialized(IsExternallyInitialized);
914 GV->setThreadLocalMode(TLM);
915 GV->setUnnamedAddr(UnnamedAddr);
917 // Parse attributes on the global.
918 while (Lex.getKind() == lltok::comma) {
921 if (Lex.getKind() == lltok::kw_section) {
923 GV->setSection(Lex.getStrVal());
924 if (ParseToken(lltok::StringConstant, "expected global section string"))
926 } else if (Lex.getKind() == lltok::kw_align) {
928 if (ParseOptionalAlignment(Alignment)) return true;
929 GV->setAlignment(Alignment);
930 } else if (Lex.getKind() == lltok::MetadataVar) {
931 if (ParseGlobalObjectMetadataAttachment(*GV))
935 if (parseOptionalComdat(Name, C))
940 return TokError("unknown global variable property!");
947 /// ParseUnnamedAttrGrp
948 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
949 bool LLParser::ParseUnnamedAttrGrp() {
950 assert(Lex.getKind() == lltok::kw_attributes);
951 LocTy AttrGrpLoc = Lex.getLoc();
954 if (Lex.getKind() != lltok::AttrGrpID)
955 return TokError("expected attribute group id");
957 unsigned VarID = Lex.getUIntVal();
958 std::vector<unsigned> unused;
962 if (ParseToken(lltok::equal, "expected '=' here") ||
963 ParseToken(lltok::lbrace, "expected '{' here") ||
964 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
966 ParseToken(lltok::rbrace, "expected end of attribute group"))
969 if (!NumberedAttrBuilders[VarID].hasAttributes())
970 return Error(AttrGrpLoc, "attribute group has no attributes");
975 /// ParseFnAttributeValuePairs
976 /// ::= <attr> | <attr> '=' <value>
977 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
978 std::vector<unsigned> &FwdRefAttrGrps,
979 bool inAttrGrp, LocTy &BuiltinLoc) {
980 bool HaveError = false;
985 lltok::Kind Token = Lex.getKind();
986 if (Token == lltok::kw_builtin)
987 BuiltinLoc = Lex.getLoc();
990 if (!inAttrGrp) return HaveError;
991 return Error(Lex.getLoc(), "unterminated attribute group");
996 case lltok::AttrGrpID: {
997 // Allow a function to reference an attribute group:
999 // define void @foo() #1 { ... }
1003 "cannot have an attribute group reference in an attribute group");
1005 unsigned AttrGrpNum = Lex.getUIntVal();
1006 if (inAttrGrp) break;
1008 // Save the reference to the attribute group. We'll fill it in later.
1009 FwdRefAttrGrps.push_back(AttrGrpNum);
1012 // Target-dependent attributes:
1013 case lltok::StringConstant: {
1014 if (ParseStringAttribute(B))
1019 // Target-independent attributes:
1020 case lltok::kw_align: {
1021 // As a hack, we allow function alignment to be initially parsed as an
1022 // attribute on a function declaration/definition or added to an attribute
1023 // group and later moved to the alignment field.
1027 if (ParseToken(lltok::equal, "expected '=' here") ||
1028 ParseUInt32(Alignment))
1031 if (ParseOptionalAlignment(Alignment))
1034 B.addAlignmentAttr(Alignment);
1037 case lltok::kw_alignstack: {
1041 if (ParseToken(lltok::equal, "expected '=' here") ||
1042 ParseUInt32(Alignment))
1045 if (ParseOptionalStackAlignment(Alignment))
1048 B.addStackAlignmentAttr(Alignment);
1051 case lltok::kw_allocsize: {
1052 unsigned ElemSizeArg;
1053 Optional<unsigned> NumElemsArg;
1054 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1055 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1057 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1060 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1061 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1062 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1063 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1064 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1065 case lltok::kw_inaccessiblememonly:
1066 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1067 case lltok::kw_inaccessiblemem_or_argmemonly:
1068 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1069 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1070 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1071 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1072 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1073 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1074 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1075 case lltok::kw_noimplicitfloat:
1076 B.addAttribute(Attribute::NoImplicitFloat); break;
1077 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1078 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1079 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1080 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1081 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1082 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1083 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1084 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1085 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1086 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1087 case lltok::kw_returns_twice:
1088 B.addAttribute(Attribute::ReturnsTwice); break;
1089 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1090 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1091 case lltok::kw_sspstrong:
1092 B.addAttribute(Attribute::StackProtectStrong); break;
1093 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1094 case lltok::kw_sanitize_address:
1095 B.addAttribute(Attribute::SanitizeAddress); break;
1096 case lltok::kw_sanitize_thread:
1097 B.addAttribute(Attribute::SanitizeThread); break;
1098 case lltok::kw_sanitize_memory:
1099 B.addAttribute(Attribute::SanitizeMemory); break;
1100 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1101 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1104 case lltok::kw_inreg:
1105 case lltok::kw_signext:
1106 case lltok::kw_zeroext:
1109 "invalid use of attribute on a function");
1111 case lltok::kw_byval:
1112 case lltok::kw_dereferenceable:
1113 case lltok::kw_dereferenceable_or_null:
1114 case lltok::kw_inalloca:
1115 case lltok::kw_nest:
1116 case lltok::kw_noalias:
1117 case lltok::kw_nocapture:
1118 case lltok::kw_nonnull:
1119 case lltok::kw_returned:
1120 case lltok::kw_sret:
1121 case lltok::kw_swifterror:
1122 case lltok::kw_swiftself:
1125 "invalid use of parameter-only attribute on a function");
1133 //===----------------------------------------------------------------------===//
1134 // GlobalValue Reference/Resolution Routines.
1135 //===----------------------------------------------------------------------===//
1137 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1138 const std::string &Name) {
1139 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1140 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1142 return new GlobalVariable(*M, PTy->getElementType(), false,
1143 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1144 nullptr, GlobalVariable::NotThreadLocal,
1145 PTy->getAddressSpace());
1148 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1149 /// forward reference record if needed. This can return null if the value
1150 /// exists but does not have the right type.
1151 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1153 PointerType *PTy = dyn_cast<PointerType>(Ty);
1155 Error(Loc, "global variable reference must have pointer type");
1159 // Look this name up in the normal function symbol table.
1161 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1163 // If this is a forward reference for the value, see if we already created a
1164 // forward ref record.
1166 auto I = ForwardRefVals.find(Name);
1167 if (I != ForwardRefVals.end())
1168 Val = I->second.first;
1171 // If we have the value in the symbol table or fwd-ref table, return it.
1173 if (Val->getType() == Ty) return Val;
1174 Error(Loc, "'@" + Name + "' defined with type '" +
1175 getTypeString(Val->getType()) + "'");
1179 // Otherwise, create a new forward reference for this value and remember it.
1180 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1181 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1185 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1186 PointerType *PTy = dyn_cast<PointerType>(Ty);
1188 Error(Loc, "global variable reference must have pointer type");
1192 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1194 // If this is a forward reference for the value, see if we already created a
1195 // forward ref record.
1197 auto I = ForwardRefValIDs.find(ID);
1198 if (I != ForwardRefValIDs.end())
1199 Val = I->second.first;
1202 // If we have the value in the symbol table or fwd-ref table, return it.
1204 if (Val->getType() == Ty) return Val;
1205 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1206 getTypeString(Val->getType()) + "'");
1210 // Otherwise, create a new forward reference for this value and remember it.
1211 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1212 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1217 //===----------------------------------------------------------------------===//
1218 // Comdat Reference/Resolution Routines.
1219 //===----------------------------------------------------------------------===//
1221 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1222 // Look this name up in the comdat symbol table.
1223 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1224 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1225 if (I != ComdatSymTab.end())
1228 // Otherwise, create a new forward reference for this value and remember it.
1229 Comdat *C = M->getOrInsertComdat(Name);
1230 ForwardRefComdats[Name] = Loc;
1235 //===----------------------------------------------------------------------===//
1237 //===----------------------------------------------------------------------===//
1239 /// ParseToken - If the current token has the specified kind, eat it and return
1240 /// success. Otherwise, emit the specified error and return failure.
1241 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1242 if (Lex.getKind() != T)
1243 return TokError(ErrMsg);
1248 /// ParseStringConstant
1249 /// ::= StringConstant
1250 bool LLParser::ParseStringConstant(std::string &Result) {
1251 if (Lex.getKind() != lltok::StringConstant)
1252 return TokError("expected string constant");
1253 Result = Lex.getStrVal();
1260 bool LLParser::ParseUInt32(unsigned &Val) {
1261 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1262 return TokError("expected integer");
1263 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1264 if (Val64 != unsigned(Val64))
1265 return TokError("expected 32-bit integer (too large)");
1273 bool LLParser::ParseUInt64(uint64_t &Val) {
1274 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1275 return TokError("expected integer");
1276 Val = Lex.getAPSIntVal().getLimitedValue();
1282 /// := 'localdynamic'
1283 /// := 'initialexec'
1285 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1286 switch (Lex.getKind()) {
1288 return TokError("expected localdynamic, initialexec or localexec");
1289 case lltok::kw_localdynamic:
1290 TLM = GlobalVariable::LocalDynamicTLSModel;
1292 case lltok::kw_initialexec:
1293 TLM = GlobalVariable::InitialExecTLSModel;
1295 case lltok::kw_localexec:
1296 TLM = GlobalVariable::LocalExecTLSModel;
1304 /// ParseOptionalThreadLocal
1306 /// := 'thread_local'
1307 /// := 'thread_local' '(' tlsmodel ')'
1308 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1309 TLM = GlobalVariable::NotThreadLocal;
1310 if (!EatIfPresent(lltok::kw_thread_local))
1313 TLM = GlobalVariable::GeneralDynamicTLSModel;
1314 if (Lex.getKind() == lltok::lparen) {
1316 return ParseTLSModel(TLM) ||
1317 ParseToken(lltok::rparen, "expected ')' after thread local model");
1322 /// ParseOptionalAddrSpace
1324 /// := 'addrspace' '(' uint32 ')'
1325 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1327 if (!EatIfPresent(lltok::kw_addrspace))
1329 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1330 ParseUInt32(AddrSpace) ||
1331 ParseToken(lltok::rparen, "expected ')' in address space");
1334 /// ParseStringAttribute
1335 /// := StringConstant
1336 /// := StringConstant '=' StringConstant
1337 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1338 std::string Attr = Lex.getStrVal();
1341 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1343 B.addAttribute(Attr, Val);
1347 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1348 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1349 bool HaveError = false;
1354 lltok::Kind Token = Lex.getKind();
1356 default: // End of attributes.
1358 case lltok::StringConstant: {
1359 if (ParseStringAttribute(B))
1363 case lltok::kw_align: {
1365 if (ParseOptionalAlignment(Alignment))
1367 B.addAlignmentAttr(Alignment);
1370 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1371 case lltok::kw_dereferenceable: {
1373 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1375 B.addDereferenceableAttr(Bytes);
1378 case lltok::kw_dereferenceable_or_null: {
1380 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1382 B.addDereferenceableOrNullAttr(Bytes);
1385 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1386 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1387 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1388 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1389 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1390 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1391 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1392 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1393 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1394 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1395 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1396 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1397 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1398 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1399 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1401 case lltok::kw_alignstack:
1402 case lltok::kw_alwaysinline:
1403 case lltok::kw_argmemonly:
1404 case lltok::kw_builtin:
1405 case lltok::kw_inlinehint:
1406 case lltok::kw_jumptable:
1407 case lltok::kw_minsize:
1408 case lltok::kw_naked:
1409 case lltok::kw_nobuiltin:
1410 case lltok::kw_noduplicate:
1411 case lltok::kw_noimplicitfloat:
1412 case lltok::kw_noinline:
1413 case lltok::kw_nonlazybind:
1414 case lltok::kw_noredzone:
1415 case lltok::kw_noreturn:
1416 case lltok::kw_nounwind:
1417 case lltok::kw_optnone:
1418 case lltok::kw_optsize:
1419 case lltok::kw_returns_twice:
1420 case lltok::kw_sanitize_address:
1421 case lltok::kw_sanitize_memory:
1422 case lltok::kw_sanitize_thread:
1424 case lltok::kw_sspreq:
1425 case lltok::kw_sspstrong:
1426 case lltok::kw_safestack:
1427 case lltok::kw_uwtable:
1428 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1436 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1437 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1438 bool HaveError = false;
1443 lltok::Kind Token = Lex.getKind();
1445 default: // End of attributes.
1447 case lltok::StringConstant: {
1448 if (ParseStringAttribute(B))
1452 case lltok::kw_dereferenceable: {
1454 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1456 B.addDereferenceableAttr(Bytes);
1459 case lltok::kw_dereferenceable_or_null: {
1461 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1463 B.addDereferenceableOrNullAttr(Bytes);
1466 case lltok::kw_align: {
1468 if (ParseOptionalAlignment(Alignment))
1470 B.addAlignmentAttr(Alignment);
1473 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1474 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1475 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1476 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1477 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1480 case lltok::kw_byval:
1481 case lltok::kw_inalloca:
1482 case lltok::kw_nest:
1483 case lltok::kw_nocapture:
1484 case lltok::kw_returned:
1485 case lltok::kw_sret:
1486 case lltok::kw_swifterror:
1487 case lltok::kw_swiftself:
1488 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1491 case lltok::kw_alignstack:
1492 case lltok::kw_alwaysinline:
1493 case lltok::kw_argmemonly:
1494 case lltok::kw_builtin:
1495 case lltok::kw_cold:
1496 case lltok::kw_inlinehint:
1497 case lltok::kw_jumptable:
1498 case lltok::kw_minsize:
1499 case lltok::kw_naked:
1500 case lltok::kw_nobuiltin:
1501 case lltok::kw_noduplicate:
1502 case lltok::kw_noimplicitfloat:
1503 case lltok::kw_noinline:
1504 case lltok::kw_nonlazybind:
1505 case lltok::kw_noredzone:
1506 case lltok::kw_noreturn:
1507 case lltok::kw_nounwind:
1508 case lltok::kw_optnone:
1509 case lltok::kw_optsize:
1510 case lltok::kw_returns_twice:
1511 case lltok::kw_sanitize_address:
1512 case lltok::kw_sanitize_memory:
1513 case lltok::kw_sanitize_thread:
1515 case lltok::kw_sspreq:
1516 case lltok::kw_sspstrong:
1517 case lltok::kw_safestack:
1518 case lltok::kw_uwtable:
1519 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1522 case lltok::kw_readnone:
1523 case lltok::kw_readonly:
1524 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1531 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1536 return GlobalValue::ExternalLinkage;
1537 case lltok::kw_private:
1538 return GlobalValue::PrivateLinkage;
1539 case lltok::kw_internal:
1540 return GlobalValue::InternalLinkage;
1541 case lltok::kw_weak:
1542 return GlobalValue::WeakAnyLinkage;
1543 case lltok::kw_weak_odr:
1544 return GlobalValue::WeakODRLinkage;
1545 case lltok::kw_linkonce:
1546 return GlobalValue::LinkOnceAnyLinkage;
1547 case lltok::kw_linkonce_odr:
1548 return GlobalValue::LinkOnceODRLinkage;
1549 case lltok::kw_available_externally:
1550 return GlobalValue::AvailableExternallyLinkage;
1551 case lltok::kw_appending:
1552 return GlobalValue::AppendingLinkage;
1553 case lltok::kw_common:
1554 return GlobalValue::CommonLinkage;
1555 case lltok::kw_extern_weak:
1556 return GlobalValue::ExternalWeakLinkage;
1557 case lltok::kw_external:
1558 return GlobalValue::ExternalLinkage;
1562 /// ParseOptionalLinkage
1569 /// ::= 'linkonce_odr'
1570 /// ::= 'available_externally'
1573 /// ::= 'extern_weak'
1575 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1576 unsigned &Visibility,
1577 unsigned &DLLStorageClass) {
1578 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1581 ParseOptionalVisibility(Visibility);
1582 ParseOptionalDLLStorageClass(DLLStorageClass);
1586 /// ParseOptionalVisibility
1592 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1593 switch (Lex.getKind()) {
1595 Res = GlobalValue::DefaultVisibility;
1597 case lltok::kw_default:
1598 Res = GlobalValue::DefaultVisibility;
1600 case lltok::kw_hidden:
1601 Res = GlobalValue::HiddenVisibility;
1603 case lltok::kw_protected:
1604 Res = GlobalValue::ProtectedVisibility;
1610 /// ParseOptionalDLLStorageClass
1615 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1616 switch (Lex.getKind()) {
1618 Res = GlobalValue::DefaultStorageClass;
1620 case lltok::kw_dllimport:
1621 Res = GlobalValue::DLLImportStorageClass;
1623 case lltok::kw_dllexport:
1624 Res = GlobalValue::DLLExportStorageClass;
1630 /// ParseOptionalCallingConv
1634 /// ::= 'intel_ocl_bicc'
1636 /// ::= 'x86_stdcallcc'
1637 /// ::= 'x86_fastcallcc'
1638 /// ::= 'x86_thiscallcc'
1639 /// ::= 'x86_vectorcallcc'
1640 /// ::= 'arm_apcscc'
1641 /// ::= 'arm_aapcscc'
1642 /// ::= 'arm_aapcs_vfpcc'
1643 /// ::= 'msp430_intrcc'
1644 /// ::= 'avr_intrcc'
1645 /// ::= 'avr_signalcc'
1646 /// ::= 'ptx_kernel'
1647 /// ::= 'ptx_device'
1649 /// ::= 'spir_kernel'
1650 /// ::= 'x86_64_sysvcc'
1651 /// ::= 'x86_64_win64cc'
1652 /// ::= 'webkit_jscc'
1654 /// ::= 'preserve_mostcc'
1655 /// ::= 'preserve_allcc'
1658 /// ::= 'x86_intrcc'
1661 /// ::= 'cxx_fast_tlscc'
1663 /// ::= 'amdgpu_tcs'
1664 /// ::= 'amdgpu_tes'
1668 /// ::= 'amdgpu_kernel'
1671 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1672 switch (Lex.getKind()) {
1673 default: CC = CallingConv::C; return false;
1674 case lltok::kw_ccc: CC = CallingConv::C; break;
1675 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1676 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1677 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1678 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1679 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1680 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1681 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1682 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1683 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1684 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1685 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1686 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1687 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1688 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1689 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1690 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1691 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1692 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1693 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1694 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1695 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1696 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1697 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1698 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1699 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1700 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1701 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1702 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1703 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1704 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1705 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1706 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1707 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1708 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1709 case lltok::kw_cc: {
1711 return ParseUInt32(CC);
1719 /// ParseMetadataAttachment
1721 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1722 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1724 std::string Name = Lex.getStrVal();
1725 Kind = M->getMDKindID(Name);
1728 return ParseMDNode(MD);
1731 /// ParseInstructionMetadata
1732 /// ::= !dbg !42 (',' !dbg !57)*
1733 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1735 if (Lex.getKind() != lltok::MetadataVar)
1736 return TokError("expected metadata after comma");
1740 if (ParseMetadataAttachment(MDK, N))
1743 Inst.setMetadata(MDK, N);
1744 if (MDK == LLVMContext::MD_tbaa)
1745 InstsWithTBAATag.push_back(&Inst);
1747 // If this is the end of the list, we're done.
1748 } while (EatIfPresent(lltok::comma));
1752 /// ParseGlobalObjectMetadataAttachment
1754 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1757 if (ParseMetadataAttachment(MDK, N))
1760 GO.addMetadata(MDK, *N);
1764 /// ParseOptionalFunctionMetadata
1766 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1767 while (Lex.getKind() == lltok::MetadataVar)
1768 if (ParseGlobalObjectMetadataAttachment(F))
1773 /// ParseOptionalAlignment
1776 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1778 if (!EatIfPresent(lltok::kw_align))
1780 LocTy AlignLoc = Lex.getLoc();
1781 if (ParseUInt32(Alignment)) return true;
1782 if (!isPowerOf2_32(Alignment))
1783 return Error(AlignLoc, "alignment is not a power of two");
1784 if (Alignment > Value::MaximumAlignment)
1785 return Error(AlignLoc, "huge alignments are not supported yet");
1789 /// ParseOptionalDerefAttrBytes
1791 /// ::= AttrKind '(' 4 ')'
1793 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1794 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1796 assert((AttrKind == lltok::kw_dereferenceable ||
1797 AttrKind == lltok::kw_dereferenceable_or_null) &&
1801 if (!EatIfPresent(AttrKind))
1803 LocTy ParenLoc = Lex.getLoc();
1804 if (!EatIfPresent(lltok::lparen))
1805 return Error(ParenLoc, "expected '('");
1806 LocTy DerefLoc = Lex.getLoc();
1807 if (ParseUInt64(Bytes)) return true;
1808 ParenLoc = Lex.getLoc();
1809 if (!EatIfPresent(lltok::rparen))
1810 return Error(ParenLoc, "expected ')'");
1812 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1816 /// ParseOptionalCommaAlign
1820 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1822 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1823 bool &AteExtraComma) {
1824 AteExtraComma = false;
1825 while (EatIfPresent(lltok::comma)) {
1826 // Metadata at the end is an early exit.
1827 if (Lex.getKind() == lltok::MetadataVar) {
1828 AteExtraComma = true;
1832 if (Lex.getKind() != lltok::kw_align)
1833 return Error(Lex.getLoc(), "expected metadata or 'align'");
1835 if (ParseOptionalAlignment(Alignment)) return true;
1841 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1842 Optional<unsigned> &HowManyArg) {
1845 auto StartParen = Lex.getLoc();
1846 if (!EatIfPresent(lltok::lparen))
1847 return Error(StartParen, "expected '('");
1849 if (ParseUInt32(BaseSizeArg))
1852 if (EatIfPresent(lltok::comma)) {
1853 auto HowManyAt = Lex.getLoc();
1855 if (ParseUInt32(HowMany))
1857 if (HowMany == BaseSizeArg)
1858 return Error(HowManyAt,
1859 "'allocsize' indices can't refer to the same parameter");
1860 HowManyArg = HowMany;
1864 auto EndParen = Lex.getLoc();
1865 if (!EatIfPresent(lltok::rparen))
1866 return Error(EndParen, "expected ')'");
1870 /// ParseScopeAndOrdering
1871 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1874 /// This sets Scope and Ordering to the parsed values.
1875 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1876 AtomicOrdering &Ordering) {
1880 Scope = CrossThread;
1881 if (EatIfPresent(lltok::kw_singlethread))
1882 Scope = SingleThread;
1884 return ParseOrdering(Ordering);
1888 /// ::= AtomicOrdering
1890 /// This sets Ordering to the parsed value.
1891 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1892 switch (Lex.getKind()) {
1893 default: return TokError("Expected ordering on atomic instruction");
1894 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1895 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1896 // Not specified yet:
1897 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1898 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1899 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1900 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1901 case lltok::kw_seq_cst:
1902 Ordering = AtomicOrdering::SequentiallyConsistent;
1909 /// ParseOptionalStackAlignment
1911 /// ::= 'alignstack' '(' 4 ')'
1912 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1914 if (!EatIfPresent(lltok::kw_alignstack))
1916 LocTy ParenLoc = Lex.getLoc();
1917 if (!EatIfPresent(lltok::lparen))
1918 return Error(ParenLoc, "expected '('");
1919 LocTy AlignLoc = Lex.getLoc();
1920 if (ParseUInt32(Alignment)) return true;
1921 ParenLoc = Lex.getLoc();
1922 if (!EatIfPresent(lltok::rparen))
1923 return Error(ParenLoc, "expected ')'");
1924 if (!isPowerOf2_32(Alignment))
1925 return Error(AlignLoc, "stack alignment is not a power of two");
1929 /// ParseIndexList - This parses the index list for an insert/extractvalue
1930 /// instruction. This sets AteExtraComma in the case where we eat an extra
1931 /// comma at the end of the line and find that it is followed by metadata.
1932 /// Clients that don't allow metadata can call the version of this function that
1933 /// only takes one argument.
1936 /// ::= (',' uint32)+
1938 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1939 bool &AteExtraComma) {
1940 AteExtraComma = false;
1942 if (Lex.getKind() != lltok::comma)
1943 return TokError("expected ',' as start of index list");
1945 while (EatIfPresent(lltok::comma)) {
1946 if (Lex.getKind() == lltok::MetadataVar) {
1947 if (Indices.empty()) return TokError("expected index");
1948 AteExtraComma = true;
1952 if (ParseUInt32(Idx)) return true;
1953 Indices.push_back(Idx);
1959 //===----------------------------------------------------------------------===//
1961 //===----------------------------------------------------------------------===//
1963 /// ParseType - Parse a type.
1964 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1965 SMLoc TypeLoc = Lex.getLoc();
1966 switch (Lex.getKind()) {
1968 return TokError(Msg);
1970 // Type ::= 'float' | 'void' (etc)
1971 Result = Lex.getTyVal();
1975 // Type ::= StructType
1976 if (ParseAnonStructType(Result, false))
1979 case lltok::lsquare:
1980 // Type ::= '[' ... ']'
1981 Lex.Lex(); // eat the lsquare.
1982 if (ParseArrayVectorType(Result, false))
1985 case lltok::less: // Either vector or packed struct.
1986 // Type ::= '<' ... '>'
1988 if (Lex.getKind() == lltok::lbrace) {
1989 if (ParseAnonStructType(Result, true) ||
1990 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1992 } else if (ParseArrayVectorType(Result, true))
1995 case lltok::LocalVar: {
1997 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1999 // If the type hasn't been defined yet, create a forward definition and
2000 // remember where that forward def'n was seen (in case it never is defined).
2002 Entry.first = StructType::create(Context, Lex.getStrVal());
2003 Entry.second = Lex.getLoc();
2005 Result = Entry.first;
2010 case lltok::LocalVarID: {
2012 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2014 // If the type hasn't been defined yet, create a forward definition and
2015 // remember where that forward def'n was seen (in case it never is defined).
2017 Entry.first = StructType::create(Context);
2018 Entry.second = Lex.getLoc();
2020 Result = Entry.first;
2026 // Parse the type suffixes.
2028 switch (Lex.getKind()) {
2031 if (!AllowVoid && Result->isVoidTy())
2032 return Error(TypeLoc, "void type only allowed for function results");
2035 // Type ::= Type '*'
2037 if (Result->isLabelTy())
2038 return TokError("basic block pointers are invalid");
2039 if (Result->isVoidTy())
2040 return TokError("pointers to void are invalid - use i8* instead");
2041 if (!PointerType::isValidElementType(Result))
2042 return TokError("pointer to this type is invalid");
2043 Result = PointerType::getUnqual(Result);
2047 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2048 case lltok::kw_addrspace: {
2049 if (Result->isLabelTy())
2050 return TokError("basic block pointers are invalid");
2051 if (Result->isVoidTy())
2052 return TokError("pointers to void are invalid; use i8* instead");
2053 if (!PointerType::isValidElementType(Result))
2054 return TokError("pointer to this type is invalid");
2056 if (ParseOptionalAddrSpace(AddrSpace) ||
2057 ParseToken(lltok::star, "expected '*' in address space"))
2060 Result = PointerType::get(Result, AddrSpace);
2064 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2066 if (ParseFunctionType(Result))
2073 /// ParseParameterList
2075 /// ::= '(' Arg (',' Arg)* ')'
2077 /// ::= Type OptionalAttributes Value OptionalAttributes
2078 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2079 PerFunctionState &PFS, bool IsMustTailCall,
2080 bool InVarArgsFunc) {
2081 if (ParseToken(lltok::lparen, "expected '(' in call"))
2084 unsigned AttrIndex = 1;
2085 while (Lex.getKind() != lltok::rparen) {
2086 // If this isn't the first argument, we need a comma.
2087 if (!ArgList.empty() &&
2088 ParseToken(lltok::comma, "expected ',' in argument list"))
2091 // Parse an ellipsis if this is a musttail call in a variadic function.
2092 if (Lex.getKind() == lltok::dotdotdot) {
2093 const char *Msg = "unexpected ellipsis in argument list for ";
2094 if (!IsMustTailCall)
2095 return TokError(Twine(Msg) + "non-musttail call");
2097 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2098 Lex.Lex(); // Lex the '...', it is purely for readability.
2099 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2102 // Parse the argument.
2104 Type *ArgTy = nullptr;
2105 AttrBuilder ArgAttrs;
2107 if (ParseType(ArgTy, ArgLoc))
2110 if (ArgTy->isMetadataTy()) {
2111 if (ParseMetadataAsValue(V, PFS))
2114 // Otherwise, handle normal operands.
2115 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2118 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2123 if (IsMustTailCall && InVarArgsFunc)
2124 return TokError("expected '...' at end of argument list for musttail call "
2125 "in varargs function");
2127 Lex.Lex(); // Lex the ')'.
2131 /// ParseOptionalOperandBundles
2133 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2136 /// ::= bundle-tag '(' ')'
2137 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2139 /// bundle-tag ::= String Constant
2140 bool LLParser::ParseOptionalOperandBundles(
2141 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2142 LocTy BeginLoc = Lex.getLoc();
2143 if (!EatIfPresent(lltok::lsquare))
2146 while (Lex.getKind() != lltok::rsquare) {
2147 // If this isn't the first operand bundle, we need a comma.
2148 if (!BundleList.empty() &&
2149 ParseToken(lltok::comma, "expected ',' in input list"))
2153 if (ParseStringConstant(Tag))
2156 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2159 std::vector<Value *> Inputs;
2160 while (Lex.getKind() != lltok::rparen) {
2161 // If this isn't the first input, we need a comma.
2162 if (!Inputs.empty() &&
2163 ParseToken(lltok::comma, "expected ',' in input list"))
2167 Value *Input = nullptr;
2168 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2170 Inputs.push_back(Input);
2173 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2175 Lex.Lex(); // Lex the ')'.
2178 if (BundleList.empty())
2179 return Error(BeginLoc, "operand bundle set must not be empty");
2181 Lex.Lex(); // Lex the ']'.
2185 /// ParseArgumentList - Parse the argument list for a function type or function
2187 /// ::= '(' ArgTypeListI ')'
2191 /// ::= ArgTypeList ',' '...'
2192 /// ::= ArgType (',' ArgType)*
2194 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2197 assert(Lex.getKind() == lltok::lparen);
2198 Lex.Lex(); // eat the (.
2200 if (Lex.getKind() == lltok::rparen) {
2202 } else if (Lex.getKind() == lltok::dotdotdot) {
2206 LocTy TypeLoc = Lex.getLoc();
2207 Type *ArgTy = nullptr;
2211 if (ParseType(ArgTy) ||
2212 ParseOptionalParamAttrs(Attrs)) return true;
2214 if (ArgTy->isVoidTy())
2215 return Error(TypeLoc, "argument can not have void type");
2217 if (Lex.getKind() == lltok::LocalVar) {
2218 Name = Lex.getStrVal();
2222 if (!FunctionType::isValidArgumentType(ArgTy))
2223 return Error(TypeLoc, "invalid type for function argument");
2225 unsigned AttrIndex = 1;
2226 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2227 AttrIndex++, Attrs),
2230 while (EatIfPresent(lltok::comma)) {
2231 // Handle ... at end of arg list.
2232 if (EatIfPresent(lltok::dotdotdot)) {
2237 // Otherwise must be an argument type.
2238 TypeLoc = Lex.getLoc();
2239 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2241 if (ArgTy->isVoidTy())
2242 return Error(TypeLoc, "argument can not have void type");
2244 if (Lex.getKind() == lltok::LocalVar) {
2245 Name = Lex.getStrVal();
2251 if (!ArgTy->isFirstClassType())
2252 return Error(TypeLoc, "invalid type for function argument");
2254 ArgList.emplace_back(
2256 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2261 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2264 /// ParseFunctionType
2265 /// ::= Type ArgumentList OptionalAttrs
2266 bool LLParser::ParseFunctionType(Type *&Result) {
2267 assert(Lex.getKind() == lltok::lparen);
2269 if (!FunctionType::isValidReturnType(Result))
2270 return TokError("invalid function return type");
2272 SmallVector<ArgInfo, 8> ArgList;
2274 if (ParseArgumentList(ArgList, isVarArg))
2277 // Reject names on the arguments lists.
2278 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2279 if (!ArgList[i].Name.empty())
2280 return Error(ArgList[i].Loc, "argument name invalid in function type");
2281 if (ArgList[i].Attrs.hasAttributes(i + 1))
2282 return Error(ArgList[i].Loc,
2283 "argument attributes invalid in function type");
2286 SmallVector<Type*, 16> ArgListTy;
2287 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2288 ArgListTy.push_back(ArgList[i].Ty);
2290 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2294 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2296 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2297 SmallVector<Type*, 8> Elts;
2298 if (ParseStructBody(Elts)) return true;
2300 Result = StructType::get(Context, Elts, Packed);
2304 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2305 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2306 std::pair<Type*, LocTy> &Entry,
2308 // If the type was already defined, diagnose the redefinition.
2309 if (Entry.first && !Entry.second.isValid())
2310 return Error(TypeLoc, "redefinition of type");
2312 // If we have opaque, just return without filling in the definition for the
2313 // struct. This counts as a definition as far as the .ll file goes.
2314 if (EatIfPresent(lltok::kw_opaque)) {
2315 // This type is being defined, so clear the location to indicate this.
2316 Entry.second = SMLoc();
2318 // If this type number has never been uttered, create it.
2320 Entry.first = StructType::create(Context, Name);
2321 ResultTy = Entry.first;
2325 // If the type starts with '<', then it is either a packed struct or a vector.
2326 bool isPacked = EatIfPresent(lltok::less);
2328 // If we don't have a struct, then we have a random type alias, which we
2329 // accept for compatibility with old files. These types are not allowed to be
2330 // forward referenced and not allowed to be recursive.
2331 if (Lex.getKind() != lltok::lbrace) {
2333 return Error(TypeLoc, "forward references to non-struct type");
2337 return ParseArrayVectorType(ResultTy, true);
2338 return ParseType(ResultTy);
2341 // This type is being defined, so clear the location to indicate this.
2342 Entry.second = SMLoc();
2344 // If this type number has never been uttered, create it.
2346 Entry.first = StructType::create(Context, Name);
2348 StructType *STy = cast<StructType>(Entry.first);
2350 SmallVector<Type*, 8> Body;
2351 if (ParseStructBody(Body) ||
2352 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2355 STy->setBody(Body, isPacked);
2361 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2364 /// ::= '{' Type (',' Type)* '}'
2365 /// ::= '<' '{' '}' '>'
2366 /// ::= '<' '{' Type (',' Type)* '}' '>'
2367 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2368 assert(Lex.getKind() == lltok::lbrace);
2369 Lex.Lex(); // Consume the '{'
2371 // Handle the empty struct.
2372 if (EatIfPresent(lltok::rbrace))
2375 LocTy EltTyLoc = Lex.getLoc();
2377 if (ParseType(Ty)) return true;
2380 if (!StructType::isValidElementType(Ty))
2381 return Error(EltTyLoc, "invalid element type for struct");
2383 while (EatIfPresent(lltok::comma)) {
2384 EltTyLoc = Lex.getLoc();
2385 if (ParseType(Ty)) return true;
2387 if (!StructType::isValidElementType(Ty))
2388 return Error(EltTyLoc, "invalid element type for struct");
2393 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2396 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2397 /// token has already been consumed.
2399 /// ::= '[' APSINTVAL 'x' Types ']'
2400 /// ::= '<' APSINTVAL 'x' Types '>'
2401 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2402 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2403 Lex.getAPSIntVal().getBitWidth() > 64)
2404 return TokError("expected number in address space");
2406 LocTy SizeLoc = Lex.getLoc();
2407 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2410 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2413 LocTy TypeLoc = Lex.getLoc();
2414 Type *EltTy = nullptr;
2415 if (ParseType(EltTy)) return true;
2417 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2418 "expected end of sequential type"))
2423 return Error(SizeLoc, "zero element vector is illegal");
2424 if ((unsigned)Size != Size)
2425 return Error(SizeLoc, "size too large for vector");
2426 if (!VectorType::isValidElementType(EltTy))
2427 return Error(TypeLoc, "invalid vector element type");
2428 Result = VectorType::get(EltTy, unsigned(Size));
2430 if (!ArrayType::isValidElementType(EltTy))
2431 return Error(TypeLoc, "invalid array element type");
2432 Result = ArrayType::get(EltTy, Size);
2437 //===----------------------------------------------------------------------===//
2438 // Function Semantic Analysis.
2439 //===----------------------------------------------------------------------===//
2441 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2443 : P(p), F(f), FunctionNumber(functionNumber) {
2445 // Insert unnamed arguments into the NumberedVals list.
2446 for (Argument &A : F.args())
2448 NumberedVals.push_back(&A);
2451 LLParser::PerFunctionState::~PerFunctionState() {
2452 // If there were any forward referenced non-basicblock values, delete them.
2454 for (const auto &P : ForwardRefVals) {
2455 if (isa<BasicBlock>(P.second.first))
2457 P.second.first->replaceAllUsesWith(
2458 UndefValue::get(P.second.first->getType()));
2459 delete P.second.first;
2462 for (const auto &P : ForwardRefValIDs) {
2463 if (isa<BasicBlock>(P.second.first))
2465 P.second.first->replaceAllUsesWith(
2466 UndefValue::get(P.second.first->getType()));
2467 delete P.second.first;
2471 bool LLParser::PerFunctionState::FinishFunction() {
2472 if (!ForwardRefVals.empty())
2473 return P.Error(ForwardRefVals.begin()->second.second,
2474 "use of undefined value '%" + ForwardRefVals.begin()->first +
2476 if (!ForwardRefValIDs.empty())
2477 return P.Error(ForwardRefValIDs.begin()->second.second,
2478 "use of undefined value '%" +
2479 Twine(ForwardRefValIDs.begin()->first) + "'");
2484 /// GetVal - Get a value with the specified name or ID, creating a
2485 /// forward reference record if needed. This can return null if the value
2486 /// exists but does not have the right type.
2487 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2489 // Look this name up in the normal function symbol table.
2490 Value *Val = F.getValueSymbolTable().lookup(Name);
2492 // If this is a forward reference for the value, see if we already created a
2493 // forward ref record.
2495 auto I = ForwardRefVals.find(Name);
2496 if (I != ForwardRefVals.end())
2497 Val = I->second.first;
2500 // If we have the value in the symbol table or fwd-ref table, return it.
2502 if (Val->getType() == Ty) return Val;
2503 if (Ty->isLabelTy())
2504 P.Error(Loc, "'%" + Name + "' is not a basic block");
2506 P.Error(Loc, "'%" + Name + "' defined with type '" +
2507 getTypeString(Val->getType()) + "'");
2511 // Don't make placeholders with invalid type.
2512 if (!Ty->isFirstClassType()) {
2513 P.Error(Loc, "invalid use of a non-first-class type");
2517 // Otherwise, create a new forward reference for this value and remember it.
2519 if (Ty->isLabelTy()) {
2520 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2522 FwdVal = new Argument(Ty, Name);
2525 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2529 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2530 // Look this name up in the normal function symbol table.
2531 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2533 // If this is a forward reference for the value, see if we already created a
2534 // forward ref record.
2536 auto I = ForwardRefValIDs.find(ID);
2537 if (I != ForwardRefValIDs.end())
2538 Val = I->second.first;
2541 // If we have the value in the symbol table or fwd-ref table, return it.
2543 if (Val->getType() == Ty) return Val;
2544 if (Ty->isLabelTy())
2545 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2547 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2548 getTypeString(Val->getType()) + "'");
2552 if (!Ty->isFirstClassType()) {
2553 P.Error(Loc, "invalid use of a non-first-class type");
2557 // Otherwise, create a new forward reference for this value and remember it.
2559 if (Ty->isLabelTy()) {
2560 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2562 FwdVal = new Argument(Ty);
2565 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2569 /// SetInstName - After an instruction is parsed and inserted into its
2570 /// basic block, this installs its name.
2571 bool LLParser::PerFunctionState::SetInstName(int NameID,
2572 const std::string &NameStr,
2573 LocTy NameLoc, Instruction *Inst) {
2574 // If this instruction has void type, it cannot have a name or ID specified.
2575 if (Inst->getType()->isVoidTy()) {
2576 if (NameID != -1 || !NameStr.empty())
2577 return P.Error(NameLoc, "instructions returning void cannot have a name");
2581 // If this was a numbered instruction, verify that the instruction is the
2582 // expected value and resolve any forward references.
2583 if (NameStr.empty()) {
2584 // If neither a name nor an ID was specified, just use the next ID.
2586 NameID = NumberedVals.size();
2588 if (unsigned(NameID) != NumberedVals.size())
2589 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2590 Twine(NumberedVals.size()) + "'");
2592 auto FI = ForwardRefValIDs.find(NameID);
2593 if (FI != ForwardRefValIDs.end()) {
2594 Value *Sentinel = FI->second.first;
2595 if (Sentinel->getType() != Inst->getType())
2596 return P.Error(NameLoc, "instruction forward referenced with type '" +
2597 getTypeString(FI->second.first->getType()) + "'");
2599 Sentinel->replaceAllUsesWith(Inst);
2601 ForwardRefValIDs.erase(FI);
2604 NumberedVals.push_back(Inst);
2608 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2609 auto FI = ForwardRefVals.find(NameStr);
2610 if (FI != ForwardRefVals.end()) {
2611 Value *Sentinel = FI->second.first;
2612 if (Sentinel->getType() != Inst->getType())
2613 return P.Error(NameLoc, "instruction forward referenced with type '" +
2614 getTypeString(FI->second.first->getType()) + "'");
2616 Sentinel->replaceAllUsesWith(Inst);
2618 ForwardRefVals.erase(FI);
2621 // Set the name on the instruction.
2622 Inst->setName(NameStr);
2624 if (Inst->getName() != NameStr)
2625 return P.Error(NameLoc, "multiple definition of local value named '" +
2630 /// GetBB - Get a basic block with the specified name or ID, creating a
2631 /// forward reference record if needed.
2632 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2634 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2635 Type::getLabelTy(F.getContext()), Loc));
2638 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2639 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2640 Type::getLabelTy(F.getContext()), Loc));
2643 /// DefineBB - Define the specified basic block, which is either named or
2644 /// unnamed. If there is an error, this returns null otherwise it returns
2645 /// the block being defined.
2646 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2650 BB = GetBB(NumberedVals.size(), Loc);
2652 BB = GetBB(Name, Loc);
2653 if (!BB) return nullptr; // Already diagnosed error.
2655 // Move the block to the end of the function. Forward ref'd blocks are
2656 // inserted wherever they happen to be referenced.
2657 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2659 // Remove the block from forward ref sets.
2661 ForwardRefValIDs.erase(NumberedVals.size());
2662 NumberedVals.push_back(BB);
2664 // BB forward references are already in the function symbol table.
2665 ForwardRefVals.erase(Name);
2671 //===----------------------------------------------------------------------===//
2673 //===----------------------------------------------------------------------===//
2675 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2676 /// type implied. For example, if we parse "4" we don't know what integer type
2677 /// it has. The value will later be combined with its type and checked for
2678 /// sanity. PFS is used to convert function-local operands of metadata (since
2679 /// metadata operands are not just parsed here but also converted to values).
2680 /// PFS can be null when we are not parsing metadata values inside a function.
2681 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2682 ID.Loc = Lex.getLoc();
2683 switch (Lex.getKind()) {
2684 default: return TokError("expected value token");
2685 case lltok::GlobalID: // @42
2686 ID.UIntVal = Lex.getUIntVal();
2687 ID.Kind = ValID::t_GlobalID;
2689 case lltok::GlobalVar: // @foo
2690 ID.StrVal = Lex.getStrVal();
2691 ID.Kind = ValID::t_GlobalName;
2693 case lltok::LocalVarID: // %42
2694 ID.UIntVal = Lex.getUIntVal();
2695 ID.Kind = ValID::t_LocalID;
2697 case lltok::LocalVar: // %foo
2698 ID.StrVal = Lex.getStrVal();
2699 ID.Kind = ValID::t_LocalName;
2702 ID.APSIntVal = Lex.getAPSIntVal();
2703 ID.Kind = ValID::t_APSInt;
2705 case lltok::APFloat:
2706 ID.APFloatVal = Lex.getAPFloatVal();
2707 ID.Kind = ValID::t_APFloat;
2709 case lltok::kw_true:
2710 ID.ConstantVal = ConstantInt::getTrue(Context);
2711 ID.Kind = ValID::t_Constant;
2713 case lltok::kw_false:
2714 ID.ConstantVal = ConstantInt::getFalse(Context);
2715 ID.Kind = ValID::t_Constant;
2717 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2718 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2719 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2720 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2722 case lltok::lbrace: {
2723 // ValID ::= '{' ConstVector '}'
2725 SmallVector<Constant*, 16> Elts;
2726 if (ParseGlobalValueVector(Elts) ||
2727 ParseToken(lltok::rbrace, "expected end of struct constant"))
2730 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2731 ID.UIntVal = Elts.size();
2732 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2733 Elts.size() * sizeof(Elts[0]));
2734 ID.Kind = ValID::t_ConstantStruct;
2738 // ValID ::= '<' ConstVector '>' --> Vector.
2739 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2741 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2743 SmallVector<Constant*, 16> Elts;
2744 LocTy FirstEltLoc = Lex.getLoc();
2745 if (ParseGlobalValueVector(Elts) ||
2747 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2748 ParseToken(lltok::greater, "expected end of constant"))
2751 if (isPackedStruct) {
2752 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2753 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2754 Elts.size() * sizeof(Elts[0]));
2755 ID.UIntVal = Elts.size();
2756 ID.Kind = ValID::t_PackedConstantStruct;
2761 return Error(ID.Loc, "constant vector must not be empty");
2763 if (!Elts[0]->getType()->isIntegerTy() &&
2764 !Elts[0]->getType()->isFloatingPointTy() &&
2765 !Elts[0]->getType()->isPointerTy())
2766 return Error(FirstEltLoc,
2767 "vector elements must have integer, pointer or floating point type");
2769 // Verify that all the vector elements have the same type.
2770 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2771 if (Elts[i]->getType() != Elts[0]->getType())
2772 return Error(FirstEltLoc,
2773 "vector element #" + Twine(i) +
2774 " is not of type '" + getTypeString(Elts[0]->getType()));
2776 ID.ConstantVal = ConstantVector::get(Elts);
2777 ID.Kind = ValID::t_Constant;
2780 case lltok::lsquare: { // Array Constant
2782 SmallVector<Constant*, 16> Elts;
2783 LocTy FirstEltLoc = Lex.getLoc();
2784 if (ParseGlobalValueVector(Elts) ||
2785 ParseToken(lltok::rsquare, "expected end of array constant"))
2788 // Handle empty element.
2790 // Use undef instead of an array because it's inconvenient to determine
2791 // the element type at this point, there being no elements to examine.
2792 ID.Kind = ValID::t_EmptyArray;
2796 if (!Elts[0]->getType()->isFirstClassType())
2797 return Error(FirstEltLoc, "invalid array element type: " +
2798 getTypeString(Elts[0]->getType()));
2800 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2802 // Verify all elements are correct type!
2803 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2804 if (Elts[i]->getType() != Elts[0]->getType())
2805 return Error(FirstEltLoc,
2806 "array element #" + Twine(i) +
2807 " is not of type '" + getTypeString(Elts[0]->getType()));
2810 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2811 ID.Kind = ValID::t_Constant;
2814 case lltok::kw_c: // c "foo"
2816 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2818 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2819 ID.Kind = ValID::t_Constant;
2822 case lltok::kw_asm: {
2823 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2825 bool HasSideEffect, AlignStack, AsmDialect;
2827 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2828 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2829 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2830 ParseStringConstant(ID.StrVal) ||
2831 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2832 ParseToken(lltok::StringConstant, "expected constraint string"))
2834 ID.StrVal2 = Lex.getStrVal();
2835 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2836 (unsigned(AsmDialect)<<2);
2837 ID.Kind = ValID::t_InlineAsm;
2841 case lltok::kw_blockaddress: {
2842 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2847 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2849 ParseToken(lltok::comma, "expected comma in block address expression")||
2850 ParseValID(Label) ||
2851 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2854 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2855 return Error(Fn.Loc, "expected function name in blockaddress");
2856 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2857 return Error(Label.Loc, "expected basic block name in blockaddress");
2859 // Try to find the function (but skip it if it's forward-referenced).
2860 GlobalValue *GV = nullptr;
2861 if (Fn.Kind == ValID::t_GlobalID) {
2862 if (Fn.UIntVal < NumberedVals.size())
2863 GV = NumberedVals[Fn.UIntVal];
2864 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2865 GV = M->getNamedValue(Fn.StrVal);
2867 Function *F = nullptr;
2869 // Confirm that it's actually a function with a definition.
2870 if (!isa<Function>(GV))
2871 return Error(Fn.Loc, "expected function name in blockaddress");
2872 F = cast<Function>(GV);
2873 if (F->isDeclaration())
2874 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2878 // Make a global variable as a placeholder for this reference.
2879 GlobalValue *&FwdRef =
2880 ForwardRefBlockAddresses.insert(std::make_pair(
2882 std::map<ValID, GlobalValue *>()))
2883 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2886 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2887 GlobalValue::InternalLinkage, nullptr, "");
2888 ID.ConstantVal = FwdRef;
2889 ID.Kind = ValID::t_Constant;
2893 // We found the function; now find the basic block. Don't use PFS, since we
2894 // might be inside a constant expression.
2896 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2897 if (Label.Kind == ValID::t_LocalID)
2898 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2900 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2902 return Error(Label.Loc, "referenced value is not a basic block");
2904 if (Label.Kind == ValID::t_LocalID)
2905 return Error(Label.Loc, "cannot take address of numeric label after "
2906 "the function is defined");
2907 BB = dyn_cast_or_null<BasicBlock>(
2908 F->getValueSymbolTable().lookup(Label.StrVal));
2910 return Error(Label.Loc, "referenced value is not a basic block");
2913 ID.ConstantVal = BlockAddress::get(F, BB);
2914 ID.Kind = ValID::t_Constant;
2918 case lltok::kw_trunc:
2919 case lltok::kw_zext:
2920 case lltok::kw_sext:
2921 case lltok::kw_fptrunc:
2922 case lltok::kw_fpext:
2923 case lltok::kw_bitcast:
2924 case lltok::kw_addrspacecast:
2925 case lltok::kw_uitofp:
2926 case lltok::kw_sitofp:
2927 case lltok::kw_fptoui:
2928 case lltok::kw_fptosi:
2929 case lltok::kw_inttoptr:
2930 case lltok::kw_ptrtoint: {
2931 unsigned Opc = Lex.getUIntVal();
2932 Type *DestTy = nullptr;
2935 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2936 ParseGlobalTypeAndValue(SrcVal) ||
2937 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2938 ParseType(DestTy) ||
2939 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2941 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2942 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2943 getTypeString(SrcVal->getType()) + "' to '" +
2944 getTypeString(DestTy) + "'");
2945 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2947 ID.Kind = ValID::t_Constant;
2950 case lltok::kw_extractvalue: {
2953 SmallVector<unsigned, 4> Indices;
2954 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2955 ParseGlobalTypeAndValue(Val) ||
2956 ParseIndexList(Indices) ||
2957 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2960 if (!Val->getType()->isAggregateType())
2961 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2962 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2963 return Error(ID.Loc, "invalid indices for extractvalue");
2964 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2965 ID.Kind = ValID::t_Constant;
2968 case lltok::kw_insertvalue: {
2970 Constant *Val0, *Val1;
2971 SmallVector<unsigned, 4> Indices;
2972 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2973 ParseGlobalTypeAndValue(Val0) ||
2974 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2975 ParseGlobalTypeAndValue(Val1) ||
2976 ParseIndexList(Indices) ||
2977 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2979 if (!Val0->getType()->isAggregateType())
2980 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2982 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2984 return Error(ID.Loc, "invalid indices for insertvalue");
2985 if (IndexedType != Val1->getType())
2986 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2987 getTypeString(Val1->getType()) +
2988 "' instead of '" + getTypeString(IndexedType) +
2990 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2991 ID.Kind = ValID::t_Constant;
2994 case lltok::kw_icmp:
2995 case lltok::kw_fcmp: {
2996 unsigned PredVal, Opc = Lex.getUIntVal();
2997 Constant *Val0, *Val1;
2999 if (ParseCmpPredicate(PredVal, Opc) ||
3000 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3001 ParseGlobalTypeAndValue(Val0) ||
3002 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3003 ParseGlobalTypeAndValue(Val1) ||
3004 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3007 if (Val0->getType() != Val1->getType())
3008 return Error(ID.Loc, "compare operands must have the same type");
3010 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3012 if (Opc == Instruction::FCmp) {
3013 if (!Val0->getType()->isFPOrFPVectorTy())
3014 return Error(ID.Loc, "fcmp requires floating point operands");
3015 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3017 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3018 if (!Val0->getType()->isIntOrIntVectorTy() &&
3019 !Val0->getType()->getScalarType()->isPointerTy())
3020 return Error(ID.Loc, "icmp requires pointer or integer operands");
3021 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3023 ID.Kind = ValID::t_Constant;
3027 // Binary Operators.
3029 case lltok::kw_fadd:
3031 case lltok::kw_fsub:
3033 case lltok::kw_fmul:
3034 case lltok::kw_udiv:
3035 case lltok::kw_sdiv:
3036 case lltok::kw_fdiv:
3037 case lltok::kw_urem:
3038 case lltok::kw_srem:
3039 case lltok::kw_frem:
3041 case lltok::kw_lshr:
3042 case lltok::kw_ashr: {
3046 unsigned Opc = Lex.getUIntVal();
3047 Constant *Val0, *Val1;
3049 LocTy ModifierLoc = Lex.getLoc();
3050 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3051 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3052 if (EatIfPresent(lltok::kw_nuw))
3054 if (EatIfPresent(lltok::kw_nsw)) {
3056 if (EatIfPresent(lltok::kw_nuw))
3059 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3060 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3061 if (EatIfPresent(lltok::kw_exact))
3064 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3065 ParseGlobalTypeAndValue(Val0) ||
3066 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3067 ParseGlobalTypeAndValue(Val1) ||
3068 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3070 if (Val0->getType() != Val1->getType())
3071 return Error(ID.Loc, "operands of constexpr must have same type");
3072 if (!Val0->getType()->isIntOrIntVectorTy()) {
3074 return Error(ModifierLoc, "nuw only applies to integer operations");
3076 return Error(ModifierLoc, "nsw only applies to integer operations");
3078 // Check that the type is valid for the operator.
3080 case Instruction::Add:
3081 case Instruction::Sub:
3082 case Instruction::Mul:
3083 case Instruction::UDiv:
3084 case Instruction::SDiv:
3085 case Instruction::URem:
3086 case Instruction::SRem:
3087 case Instruction::Shl:
3088 case Instruction::AShr:
3089 case Instruction::LShr:
3090 if (!Val0->getType()->isIntOrIntVectorTy())
3091 return Error(ID.Loc, "constexpr requires integer operands");
3093 case Instruction::FAdd:
3094 case Instruction::FSub:
3095 case Instruction::FMul:
3096 case Instruction::FDiv:
3097 case Instruction::FRem:
3098 if (!Val0->getType()->isFPOrFPVectorTy())
3099 return Error(ID.Loc, "constexpr requires fp operands");
3101 default: llvm_unreachable("Unknown binary operator!");
3104 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3105 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3106 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3107 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3109 ID.Kind = ValID::t_Constant;
3113 // Logical Operations
3116 case lltok::kw_xor: {
3117 unsigned Opc = Lex.getUIntVal();
3118 Constant *Val0, *Val1;
3120 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3121 ParseGlobalTypeAndValue(Val0) ||
3122 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3123 ParseGlobalTypeAndValue(Val1) ||
3124 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3126 if (Val0->getType() != Val1->getType())
3127 return Error(ID.Loc, "operands of constexpr must have same type");
3128 if (!Val0->getType()->isIntOrIntVectorTy())
3129 return Error(ID.Loc,
3130 "constexpr requires integer or integer vector operands");
3131 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3132 ID.Kind = ValID::t_Constant;
3136 case lltok::kw_getelementptr:
3137 case lltok::kw_shufflevector:
3138 case lltok::kw_insertelement:
3139 case lltok::kw_extractelement:
3140 case lltok::kw_select: {
3141 unsigned Opc = Lex.getUIntVal();
3142 SmallVector<Constant*, 16> Elts;
3143 bool InBounds = false;
3147 if (Opc == Instruction::GetElementPtr)
3148 InBounds = EatIfPresent(lltok::kw_inbounds);
3150 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3153 LocTy ExplicitTypeLoc = Lex.getLoc();
3154 if (Opc == Instruction::GetElementPtr) {
3155 if (ParseType(Ty) ||
3156 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3160 if (ParseGlobalValueVector(Elts) ||
3161 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3164 if (Opc == Instruction::GetElementPtr) {
3165 if (Elts.size() == 0 ||
3166 !Elts[0]->getType()->getScalarType()->isPointerTy())
3167 return Error(ID.Loc, "base of getelementptr must be a pointer");
3169 Type *BaseType = Elts[0]->getType();
3170 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3171 if (Ty != BasePointerType->getElementType())
3174 "explicit pointee type doesn't match operand's pointee type");
3176 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3177 for (Constant *Val : Indices) {
3178 Type *ValTy = Val->getType();
3179 if (!ValTy->getScalarType()->isIntegerTy())
3180 return Error(ID.Loc, "getelementptr index must be an integer");
3181 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3182 return Error(ID.Loc, "getelementptr index type missmatch");
3183 if (ValTy->isVectorTy()) {
3184 unsigned ValNumEl = ValTy->getVectorNumElements();
3185 unsigned PtrNumEl = BaseType->getVectorNumElements();
3186 if (ValNumEl != PtrNumEl)
3189 "getelementptr vector index has a wrong number of elements");
3193 SmallPtrSet<Type*, 4> Visited;
3194 if (!Indices.empty() && !Ty->isSized(&Visited))
3195 return Error(ID.Loc, "base element of getelementptr must be sized");
3197 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3198 return Error(ID.Loc, "invalid getelementptr indices");
3200 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
3201 } else if (Opc == Instruction::Select) {
3202 if (Elts.size() != 3)
3203 return Error(ID.Loc, "expected three operands to select");
3204 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3206 return Error(ID.Loc, Reason);
3207 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3208 } else if (Opc == Instruction::ShuffleVector) {
3209 if (Elts.size() != 3)
3210 return Error(ID.Loc, "expected three operands to shufflevector");
3211 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3212 return Error(ID.Loc, "invalid operands to shufflevector");
3214 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3215 } else if (Opc == Instruction::ExtractElement) {
3216 if (Elts.size() != 2)
3217 return Error(ID.Loc, "expected two operands to extractelement");
3218 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3219 return Error(ID.Loc, "invalid extractelement operands");
3220 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3222 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3223 if (Elts.size() != 3)
3224 return Error(ID.Loc, "expected three operands to insertelement");
3225 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3226 return Error(ID.Loc, "invalid insertelement operands");
3228 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3231 ID.Kind = ValID::t_Constant;
3240 /// ParseGlobalValue - Parse a global value with the specified type.
3241 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3245 bool Parsed = ParseValID(ID) ||
3246 ConvertValIDToValue(Ty, ID, V, nullptr);
3247 if (V && !(C = dyn_cast<Constant>(V)))
3248 return Error(ID.Loc, "global values must be constants");
3252 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3254 return ParseType(Ty) ||
3255 ParseGlobalValue(Ty, V);
3258 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3261 LocTy KwLoc = Lex.getLoc();
3262 if (!EatIfPresent(lltok::kw_comdat))
3265 if (EatIfPresent(lltok::lparen)) {
3266 if (Lex.getKind() != lltok::ComdatVar)
3267 return TokError("expected comdat variable");
3268 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3270 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3273 if (GlobalName.empty())
3274 return TokError("comdat cannot be unnamed");
3275 C = getComdat(GlobalName, KwLoc);
3281 /// ParseGlobalValueVector
3283 /// ::= TypeAndValue (',' TypeAndValue)*
3284 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3286 if (Lex.getKind() == lltok::rbrace ||
3287 Lex.getKind() == lltok::rsquare ||
3288 Lex.getKind() == lltok::greater ||
3289 Lex.getKind() == lltok::rparen)
3293 if (ParseGlobalTypeAndValue(C)) return true;
3296 while (EatIfPresent(lltok::comma)) {
3297 if (ParseGlobalTypeAndValue(C)) return true;
3304 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3305 SmallVector<Metadata *, 16> Elts;
3306 if (ParseMDNodeVector(Elts))
3309 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3316 /// ::= !DILocation(...)
3317 bool LLParser::ParseMDNode(MDNode *&N) {
3318 if (Lex.getKind() == lltok::MetadataVar)
3319 return ParseSpecializedMDNode(N);
3321 return ParseToken(lltok::exclaim, "expected '!' here") ||
3325 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3327 if (Lex.getKind() == lltok::lbrace)
3328 return ParseMDTuple(N);
3331 return ParseMDNodeID(N);
3336 /// Structure to represent an optional metadata field.
3337 template <class FieldTy> struct MDFieldImpl {
3338 typedef MDFieldImpl ImplTy;
3342 void assign(FieldTy Val) {
3344 this->Val = std::move(Val);
3347 explicit MDFieldImpl(FieldTy Default)
3348 : Val(std::move(Default)), Seen(false) {}
3351 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3354 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3355 : ImplTy(Default), Max(Max) {}
3357 struct LineField : public MDUnsignedField {
3358 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3360 struct ColumnField : public MDUnsignedField {
3361 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3363 struct DwarfTagField : public MDUnsignedField {
3364 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3365 DwarfTagField(dwarf::Tag DefaultTag)
3366 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3368 struct DwarfMacinfoTypeField : public MDUnsignedField {
3369 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3370 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3371 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3373 struct DwarfAttEncodingField : public MDUnsignedField {
3374 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3376 struct DwarfVirtualityField : public MDUnsignedField {
3377 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3379 struct DwarfLangField : public MDUnsignedField {
3380 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3382 struct DwarfCCField : public MDUnsignedField {
3383 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3385 struct EmissionKindField : public MDUnsignedField {
3386 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3389 struct DIFlagField : public MDUnsignedField {
3390 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3393 struct MDSignedField : public MDFieldImpl<int64_t> {
3397 MDSignedField(int64_t Default = 0)
3398 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3399 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3400 : ImplTy(Default), Min(Min), Max(Max) {}
3403 struct MDBoolField : public MDFieldImpl<bool> {
3404 MDBoolField(bool Default = false) : ImplTy(Default) {}
3406 struct MDField : public MDFieldImpl<Metadata *> {
3409 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3411 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3412 MDConstant() : ImplTy(nullptr) {}
3414 struct MDStringField : public MDFieldImpl<MDString *> {
3416 MDStringField(bool AllowEmpty = true)
3417 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3419 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3420 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3428 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3429 MDUnsignedField &Result) {
3430 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3431 return TokError("expected unsigned integer");
3433 auto &U = Lex.getAPSIntVal();
3434 if (U.ugt(Result.Max))
3435 return TokError("value for '" + Name + "' too large, limit is " +
3437 Result.assign(U.getZExtValue());
3438 assert(Result.Val <= Result.Max && "Expected value in range");
3444 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3445 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3448 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3449 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3453 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3454 if (Lex.getKind() == lltok::APSInt)
3455 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3457 if (Lex.getKind() != lltok::DwarfTag)
3458 return TokError("expected DWARF tag");
3460 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3461 if (Tag == dwarf::DW_TAG_invalid)
3462 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3463 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3471 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3472 DwarfMacinfoTypeField &Result) {
3473 if (Lex.getKind() == lltok::APSInt)
3474 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3476 if (Lex.getKind() != lltok::DwarfMacinfo)
3477 return TokError("expected DWARF macinfo type");
3479 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3480 if (Macinfo == dwarf::DW_MACINFO_invalid)
3482 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3483 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3485 Result.assign(Macinfo);
3491 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3492 DwarfVirtualityField &Result) {
3493 if (Lex.getKind() == lltok::APSInt)
3494 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3496 if (Lex.getKind() != lltok::DwarfVirtuality)
3497 return TokError("expected DWARF virtuality code");
3499 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3500 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3501 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3502 Lex.getStrVal() + "'");
3503 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3504 Result.assign(Virtuality);
3510 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3511 if (Lex.getKind() == lltok::APSInt)
3512 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3514 if (Lex.getKind() != lltok::DwarfLang)
3515 return TokError("expected DWARF language");
3517 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3519 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3521 assert(Lang <= Result.Max && "Expected valid DWARF language");
3522 Result.assign(Lang);
3528 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3529 if (Lex.getKind() == lltok::APSInt)
3530 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3532 if (Lex.getKind() != lltok::DwarfCC)
3533 return TokError("expected DWARF calling convention");
3535 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3537 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3539 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3546 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3547 if (Lex.getKind() == lltok::APSInt)
3548 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3550 if (Lex.getKind() != lltok::EmissionKind)
3551 return TokError("expected emission kind");
3553 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3555 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3557 assert(*Kind <= Result.Max && "Expected valid emission kind");
3558 Result.assign(*Kind);
3564 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3565 DwarfAttEncodingField &Result) {
3566 if (Lex.getKind() == lltok::APSInt)
3567 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3569 if (Lex.getKind() != lltok::DwarfAttEncoding)
3570 return TokError("expected DWARF type attribute encoding");
3572 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3574 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3575 Lex.getStrVal() + "'");
3576 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3577 Result.assign(Encoding);
3584 /// ::= DIFlagVector
3585 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3587 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3588 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3590 // Parser for a single flag.
3591 auto parseFlag = [&](unsigned &Val) {
3592 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3593 return ParseUInt32(Val);
3595 if (Lex.getKind() != lltok::DIFlag)
3596 return TokError("expected debug info flag");
3598 Val = DINode::getFlag(Lex.getStrVal());
3600 return TokError(Twine("invalid debug info flag flag '") +
3601 Lex.getStrVal() + "'");
3606 // Parse the flags and combine them together.
3607 unsigned Combined = 0;
3613 } while (EatIfPresent(lltok::bar));
3615 Result.assign(Combined);
3620 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3621 MDSignedField &Result) {
3622 if (Lex.getKind() != lltok::APSInt)
3623 return TokError("expected signed integer");
3625 auto &S = Lex.getAPSIntVal();
3627 return TokError("value for '" + Name + "' too small, limit is " +
3630 return TokError("value for '" + Name + "' too large, limit is " +
3632 Result.assign(S.getExtValue());
3633 assert(Result.Val >= Result.Min && "Expected value in range");
3634 assert(Result.Val <= Result.Max && "Expected value in range");
3640 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3641 switch (Lex.getKind()) {
3643 return TokError("expected 'true' or 'false'");
3644 case lltok::kw_true:
3645 Result.assign(true);
3647 case lltok::kw_false:
3648 Result.assign(false);
3656 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3657 if (Lex.getKind() == lltok::kw_null) {
3658 if (!Result.AllowNull)
3659 return TokError("'" + Name + "' cannot be null");
3661 Result.assign(nullptr);
3666 if (ParseMetadata(MD, nullptr))
3674 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3676 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3679 Result.assign(cast<ConstantAsMetadata>(MD));
3684 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3685 LocTy ValueLoc = Lex.getLoc();
3687 if (ParseStringConstant(S))
3690 if (!Result.AllowEmpty && S.empty())
3691 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3693 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3698 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3699 SmallVector<Metadata *, 4> MDs;
3700 if (ParseMDNodeVector(MDs))
3703 Result.assign(std::move(MDs));
3707 } // end namespace llvm
3709 template <class ParserTy>
3710 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3712 if (Lex.getKind() != lltok::LabelStr)
3713 return TokError("expected field label here");
3717 } while (EatIfPresent(lltok::comma));
3722 template <class ParserTy>
3723 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3724 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3727 if (ParseToken(lltok::lparen, "expected '(' here"))
3729 if (Lex.getKind() != lltok::rparen)
3730 if (ParseMDFieldsImplBody(parseField))
3733 ClosingLoc = Lex.getLoc();
3734 return ParseToken(lltok::rparen, "expected ')' here");
3737 template <class FieldTy>
3738 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3740 return TokError("field '" + Name + "' cannot be specified more than once");
3742 LocTy Loc = Lex.getLoc();
3744 return ParseMDField(Loc, Name, Result);
3747 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3748 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3750 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3751 if (Lex.getStrVal() == #CLASS) \
3752 return Parse##CLASS(N, IsDistinct);
3753 #include "llvm/IR/Metadata.def"
3755 return TokError("expected metadata type");
3758 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3759 #define NOP_FIELD(NAME, TYPE, INIT)
3760 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3762 return Error(ClosingLoc, "missing required field '" #NAME "'");
3763 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3764 if (Lex.getStrVal() == #NAME) \
3765 return ParseMDField(#NAME, NAME);
3766 #define PARSE_MD_FIELDS() \
3767 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3770 if (ParseMDFieldsImpl([&]() -> bool { \
3771 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3772 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3775 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3777 #define GET_OR_DISTINCT(CLASS, ARGS) \
3778 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3780 /// ParseDILocationFields:
3781 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3782 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3783 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3784 OPTIONAL(line, LineField, ); \
3785 OPTIONAL(column, ColumnField, ); \
3786 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3787 OPTIONAL(inlinedAt, MDField, );
3789 #undef VISIT_MD_FIELDS
3791 Result = GET_OR_DISTINCT(
3792 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3796 /// ParseGenericDINode:
3797 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3798 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3799 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3800 REQUIRED(tag, DwarfTagField, ); \
3801 OPTIONAL(header, MDStringField, ); \
3802 OPTIONAL(operands, MDFieldList, );
3804 #undef VISIT_MD_FIELDS
3806 Result = GET_OR_DISTINCT(GenericDINode,
3807 (Context, tag.Val, header.Val, operands.Val));
3811 /// ParseDISubrange:
3812 /// ::= !DISubrange(count: 30, lowerBound: 2)
3813 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3814 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3815 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3816 OPTIONAL(lowerBound, MDSignedField, );
3818 #undef VISIT_MD_FIELDS
3820 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3824 /// ParseDIEnumerator:
3825 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3826 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3827 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3828 REQUIRED(name, MDStringField, ); \
3829 REQUIRED(value, MDSignedField, );
3831 #undef VISIT_MD_FIELDS
3833 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3837 /// ParseDIBasicType:
3838 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3839 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3840 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3841 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3842 OPTIONAL(name, MDStringField, ); \
3843 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3844 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3845 OPTIONAL(encoding, DwarfAttEncodingField, );
3847 #undef VISIT_MD_FIELDS
3849 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3850 align.Val, encoding.Val));
3854 /// ParseDIDerivedType:
3855 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3856 /// line: 7, scope: !1, baseType: !2, size: 32,
3857 /// align: 32, offset: 0, flags: 0, extraData: !3)
3858 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3859 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3860 REQUIRED(tag, DwarfTagField, ); \
3861 OPTIONAL(name, MDStringField, ); \
3862 OPTIONAL(file, MDField, ); \
3863 OPTIONAL(line, LineField, ); \
3864 OPTIONAL(scope, MDField, ); \
3865 REQUIRED(baseType, MDField, ); \
3866 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3867 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3868 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3869 OPTIONAL(flags, DIFlagField, ); \
3870 OPTIONAL(extraData, MDField, );
3872 #undef VISIT_MD_FIELDS
3874 Result = GET_OR_DISTINCT(DIDerivedType,
3875 (Context, tag.Val, name.Val, file.Val, line.Val,
3876 scope.Val, baseType.Val, size.Val, align.Val,
3877 offset.Val, flags.Val, extraData.Val));
3881 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3882 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3883 REQUIRED(tag, DwarfTagField, ); \
3884 OPTIONAL(name, MDStringField, ); \
3885 OPTIONAL(file, MDField, ); \
3886 OPTIONAL(line, LineField, ); \
3887 OPTIONAL(scope, MDField, ); \
3888 OPTIONAL(baseType, MDField, ); \
3889 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3890 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3891 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3892 OPTIONAL(flags, DIFlagField, ); \
3893 OPTIONAL(elements, MDField, ); \
3894 OPTIONAL(runtimeLang, DwarfLangField, ); \
3895 OPTIONAL(vtableHolder, MDField, ); \
3896 OPTIONAL(templateParams, MDField, ); \
3897 OPTIONAL(identifier, MDStringField, );
3899 #undef VISIT_MD_FIELDS
3901 // If this has an identifier try to build an ODR type.
3903 if (auto *CT = DICompositeType::buildODRType(
3904 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3905 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3906 elements.Val, runtimeLang.Val, vtableHolder.Val,
3907 templateParams.Val)) {
3912 // Create a new node, and save it in the context if it belongs in the type
3914 Result = GET_OR_DISTINCT(
3916 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3917 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3918 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3922 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3923 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3924 OPTIONAL(flags, DIFlagField, ); \
3925 OPTIONAL(cc, DwarfCCField, ); \
3926 REQUIRED(types, MDField, );
3928 #undef VISIT_MD_FIELDS
3930 Result = GET_OR_DISTINCT(DISubroutineType,
3931 (Context, flags.Val, cc.Val, types.Val));
3935 /// ParseDIFileType:
3936 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3937 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3938 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3939 REQUIRED(filename, MDStringField, ); \
3940 REQUIRED(directory, MDStringField, );
3942 #undef VISIT_MD_FIELDS
3944 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3948 /// ParseDICompileUnit:
3949 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3950 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3951 /// splitDebugFilename: "abc.debug",
3952 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
3953 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
3954 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3956 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3958 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3959 REQUIRED(language, DwarfLangField, ); \
3960 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3961 OPTIONAL(producer, MDStringField, ); \
3962 OPTIONAL(isOptimized, MDBoolField, ); \
3963 OPTIONAL(flags, MDStringField, ); \
3964 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3965 OPTIONAL(splitDebugFilename, MDStringField, ); \
3966 OPTIONAL(emissionKind, EmissionKindField, ); \
3967 OPTIONAL(enums, MDField, ); \
3968 OPTIONAL(retainedTypes, MDField, ); \
3969 OPTIONAL(globals, MDField, ); \
3970 OPTIONAL(imports, MDField, ); \
3971 OPTIONAL(macros, MDField, ); \
3972 OPTIONAL(dwoId, MDUnsignedField, );
3974 #undef VISIT_MD_FIELDS
3976 Result = DICompileUnit::getDistinct(
3977 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
3978 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
3979 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val);
3983 /// ParseDISubprogram:
3984 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3985 /// file: !1, line: 7, type: !2, isLocal: false,
3986 /// isDefinition: true, scopeLine: 8, containingType: !3,
3987 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3988 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
3989 /// isOptimized: false, templateParams: !4, declaration: !5,
3991 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3992 auto Loc = Lex.getLoc();
3993 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3994 OPTIONAL(scope, MDField, ); \
3995 OPTIONAL(name, MDStringField, ); \
3996 OPTIONAL(linkageName, MDStringField, ); \
3997 OPTIONAL(file, MDField, ); \
3998 OPTIONAL(line, LineField, ); \
3999 OPTIONAL(type, MDField, ); \
4000 OPTIONAL(isLocal, MDBoolField, ); \
4001 OPTIONAL(isDefinition, MDBoolField, (true)); \
4002 OPTIONAL(scopeLine, LineField, ); \
4003 OPTIONAL(containingType, MDField, ); \
4004 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4005 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4006 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4007 OPTIONAL(flags, DIFlagField, ); \
4008 OPTIONAL(isOptimized, MDBoolField, ); \
4009 OPTIONAL(unit, MDField, ); \
4010 OPTIONAL(templateParams, MDField, ); \
4011 OPTIONAL(declaration, MDField, ); \
4012 OPTIONAL(variables, MDField, );
4014 #undef VISIT_MD_FIELDS
4016 if (isDefinition.Val && !IsDistinct)
4019 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4021 Result = GET_OR_DISTINCT(
4022 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4023 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4024 scopeLine.Val, containingType.Val, virtuality.Val,
4025 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4026 isOptimized.Val, unit.Val, templateParams.Val,
4027 declaration.Val, variables.Val));
4031 /// ParseDILexicalBlock:
4032 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4033 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4034 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4035 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4036 OPTIONAL(file, MDField, ); \
4037 OPTIONAL(line, LineField, ); \
4038 OPTIONAL(column, ColumnField, );
4040 #undef VISIT_MD_FIELDS
4042 Result = GET_OR_DISTINCT(
4043 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4047 /// ParseDILexicalBlockFile:
4048 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4049 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4050 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4051 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4052 OPTIONAL(file, MDField, ); \
4053 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4055 #undef VISIT_MD_FIELDS
4057 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4058 (Context, scope.Val, file.Val, discriminator.Val));
4062 /// ParseDINamespace:
4063 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4064 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4065 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4066 REQUIRED(scope, MDField, ); \
4067 OPTIONAL(file, MDField, ); \
4068 OPTIONAL(name, MDStringField, ); \
4069 OPTIONAL(line, LineField, );
4071 #undef VISIT_MD_FIELDS
4073 Result = GET_OR_DISTINCT(DINamespace,
4074 (Context, scope.Val, file.Val, name.Val, line.Val));
4079 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4080 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4081 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4082 REQUIRED(type, DwarfMacinfoTypeField, ); \
4083 REQUIRED(line, LineField, ); \
4084 REQUIRED(name, MDStringField, ); \
4085 OPTIONAL(value, MDStringField, );
4087 #undef VISIT_MD_FIELDS
4089 Result = GET_OR_DISTINCT(DIMacro,
4090 (Context, type.Val, line.Val, name.Val, value.Val));
4094 /// ParseDIMacroFile:
4095 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4096 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4097 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4098 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4099 REQUIRED(line, LineField, ); \
4100 REQUIRED(file, MDField, ); \
4101 OPTIONAL(nodes, MDField, );
4103 #undef VISIT_MD_FIELDS
4105 Result = GET_OR_DISTINCT(DIMacroFile,
4106 (Context, type.Val, line.Val, file.Val, nodes.Val));
4112 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4113 /// includePath: "/usr/include", isysroot: "/")
4114 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4115 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4116 REQUIRED(scope, MDField, ); \
4117 REQUIRED(name, MDStringField, ); \
4118 OPTIONAL(configMacros, MDStringField, ); \
4119 OPTIONAL(includePath, MDStringField, ); \
4120 OPTIONAL(isysroot, MDStringField, );
4122 #undef VISIT_MD_FIELDS
4124 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4125 configMacros.Val, includePath.Val, isysroot.Val));
4129 /// ParseDITemplateTypeParameter:
4130 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4131 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4132 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4133 OPTIONAL(name, MDStringField, ); \
4134 REQUIRED(type, MDField, );
4136 #undef VISIT_MD_FIELDS
4139 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4143 /// ParseDITemplateValueParameter:
4144 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4145 /// name: "V", type: !1, value: i32 7)
4146 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4147 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4148 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4149 OPTIONAL(name, MDStringField, ); \
4150 OPTIONAL(type, MDField, ); \
4151 REQUIRED(value, MDField, );
4153 #undef VISIT_MD_FIELDS
4155 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4156 (Context, tag.Val, name.Val, type.Val, value.Val));
4160 /// ParseDIGlobalVariable:
4161 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4162 /// file: !1, line: 7, type: !2, isLocal: false,
4163 /// isDefinition: true, variable: i32* @foo,
4164 /// declaration: !3)
4165 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4166 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4167 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4168 OPTIONAL(scope, MDField, ); \
4169 OPTIONAL(linkageName, MDStringField, ); \
4170 OPTIONAL(file, MDField, ); \
4171 OPTIONAL(line, LineField, ); \
4172 OPTIONAL(type, MDField, ); \
4173 OPTIONAL(isLocal, MDBoolField, ); \
4174 OPTIONAL(isDefinition, MDBoolField, (true)); \
4175 OPTIONAL(variable, MDConstant, ); \
4176 OPTIONAL(declaration, MDField, );
4178 #undef VISIT_MD_FIELDS
4180 Result = GET_OR_DISTINCT(DIGlobalVariable,
4181 (Context, scope.Val, name.Val, linkageName.Val,
4182 file.Val, line.Val, type.Val, isLocal.Val,
4183 isDefinition.Val, variable.Val, declaration.Val));
4187 /// ParseDILocalVariable:
4188 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4189 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4190 /// ::= !DILocalVariable(scope: !0, name: "foo",
4191 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4192 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4193 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4194 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4195 OPTIONAL(name, MDStringField, ); \
4196 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4197 OPTIONAL(file, MDField, ); \
4198 OPTIONAL(line, LineField, ); \
4199 OPTIONAL(type, MDField, ); \
4200 OPTIONAL(flags, DIFlagField, );
4202 #undef VISIT_MD_FIELDS
4204 Result = GET_OR_DISTINCT(DILocalVariable,
4205 (Context, scope.Val, name.Val, file.Val, line.Val,
4206 type.Val, arg.Val, flags.Val));
4210 /// ParseDIExpression:
4211 /// ::= !DIExpression(0, 7, -1)
4212 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4213 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4216 if (ParseToken(lltok::lparen, "expected '(' here"))
4219 SmallVector<uint64_t, 8> Elements;
4220 if (Lex.getKind() != lltok::rparen)
4222 if (Lex.getKind() == lltok::DwarfOp) {
4223 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4225 Elements.push_back(Op);
4228 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4231 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4232 return TokError("expected unsigned integer");
4234 auto &U = Lex.getAPSIntVal();
4235 if (U.ugt(UINT64_MAX))
4236 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4237 Elements.push_back(U.getZExtValue());
4239 } while (EatIfPresent(lltok::comma));
4241 if (ParseToken(lltok::rparen, "expected ')' here"))
4244 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4248 /// ParseDIObjCProperty:
4249 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4250 /// getter: "getFoo", attributes: 7, type: !2)
4251 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4252 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4253 OPTIONAL(name, MDStringField, ); \
4254 OPTIONAL(file, MDField, ); \
4255 OPTIONAL(line, LineField, ); \
4256 OPTIONAL(setter, MDStringField, ); \
4257 OPTIONAL(getter, MDStringField, ); \
4258 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4259 OPTIONAL(type, MDField, );
4261 #undef VISIT_MD_FIELDS
4263 Result = GET_OR_DISTINCT(DIObjCProperty,
4264 (Context, name.Val, file.Val, line.Val, setter.Val,
4265 getter.Val, attributes.Val, type.Val));
4269 /// ParseDIImportedEntity:
4270 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4271 /// line: 7, name: "foo")
4272 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4273 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4274 REQUIRED(tag, DwarfTagField, ); \
4275 REQUIRED(scope, MDField, ); \
4276 OPTIONAL(entity, MDField, ); \
4277 OPTIONAL(line, LineField, ); \
4278 OPTIONAL(name, MDStringField, );
4280 #undef VISIT_MD_FIELDS
4282 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4283 entity.Val, line.Val, name.Val));
4287 #undef PARSE_MD_FIELD
4289 #undef REQUIRE_FIELD
4290 #undef DECLARE_FIELD
4292 /// ParseMetadataAsValue
4293 /// ::= metadata i32 %local
4294 /// ::= metadata i32 @global
4295 /// ::= metadata i32 7
4297 /// ::= metadata !{...}
4298 /// ::= metadata !"string"
4299 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4300 // Note: the type 'metadata' has already been parsed.
4302 if (ParseMetadata(MD, &PFS))
4305 V = MetadataAsValue::get(Context, MD);
4309 /// ParseValueAsMetadata
4313 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4314 PerFunctionState *PFS) {
4317 if (ParseType(Ty, TypeMsg, Loc))
4319 if (Ty->isMetadataTy())
4320 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4323 if (ParseValue(Ty, V, PFS))
4326 MD = ValueAsMetadata::get(V);
4337 /// ::= !DILocation(...)
4338 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4339 if (Lex.getKind() == lltok::MetadataVar) {
4341 if (ParseSpecializedMDNode(N))
4349 if (Lex.getKind() != lltok::exclaim)
4350 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4353 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4357 // ::= '!' STRINGCONSTANT
4358 if (Lex.getKind() == lltok::StringConstant) {
4360 if (ParseMDString(S))
4370 if (ParseMDNodeTail(N))
4377 //===----------------------------------------------------------------------===//
4378 // Function Parsing.
4379 //===----------------------------------------------------------------------===//
4381 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4382 PerFunctionState *PFS) {
4383 if (Ty->isFunctionTy())
4384 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4387 case ValID::t_LocalID:
4388 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4389 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4390 return V == nullptr;
4391 case ValID::t_LocalName:
4392 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4393 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4394 return V == nullptr;
4395 case ValID::t_InlineAsm: {
4396 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4397 return Error(ID.Loc, "invalid type for inline asm constraint string");
4398 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4399 (ID.UIntVal >> 1) & 1,
4400 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4403 case ValID::t_GlobalName:
4404 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4405 return V == nullptr;
4406 case ValID::t_GlobalID:
4407 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4408 return V == nullptr;
4409 case ValID::t_APSInt:
4410 if (!Ty->isIntegerTy())
4411 return Error(ID.Loc, "integer constant must have integer type");
4412 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4413 V = ConstantInt::get(Context, ID.APSIntVal);
4415 case ValID::t_APFloat:
4416 if (!Ty->isFloatingPointTy() ||
4417 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4418 return Error(ID.Loc, "floating point constant invalid for type");
4420 // The lexer has no type info, so builds all half, float, and double FP
4421 // constants as double. Fix this here. Long double does not need this.
4422 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4425 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4427 else if (Ty->isFloatTy())
4428 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4431 V = ConstantFP::get(Context, ID.APFloatVal);
4433 if (V->getType() != Ty)
4434 return Error(ID.Loc, "floating point constant does not have type '" +
4435 getTypeString(Ty) + "'");
4439 if (!Ty->isPointerTy())
4440 return Error(ID.Loc, "null must be a pointer type");
4441 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4443 case ValID::t_Undef:
4444 // FIXME: LabelTy should not be a first-class type.
4445 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4446 return Error(ID.Loc, "invalid type for undef constant");
4447 V = UndefValue::get(Ty);
4449 case ValID::t_EmptyArray:
4450 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4451 return Error(ID.Loc, "invalid empty array initializer");
4452 V = UndefValue::get(Ty);
4455 // FIXME: LabelTy should not be a first-class type.
4456 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4457 return Error(ID.Loc, "invalid type for null constant");
4458 V = Constant::getNullValue(Ty);
4461 if (!Ty->isTokenTy())
4462 return Error(ID.Loc, "invalid type for none constant");
4463 V = Constant::getNullValue(Ty);
4465 case ValID::t_Constant:
4466 if (ID.ConstantVal->getType() != Ty)
4467 return Error(ID.Loc, "constant expression type mismatch");
4471 case ValID::t_ConstantStruct:
4472 case ValID::t_PackedConstantStruct:
4473 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4474 if (ST->getNumElements() != ID.UIntVal)
4475 return Error(ID.Loc,
4476 "initializer with struct type has wrong # elements");
4477 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4478 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4480 // Verify that the elements are compatible with the structtype.
4481 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4482 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4483 return Error(ID.Loc, "element " + Twine(i) +
4484 " of struct initializer doesn't match struct element type");
4486 V = ConstantStruct::get(
4487 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4489 return Error(ID.Loc, "constant expression type mismatch");
4492 llvm_unreachable("Invalid ValID");
4495 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4498 auto Loc = Lex.getLoc();
4499 if (ParseValID(ID, /*PFS=*/nullptr))
4502 case ValID::t_APSInt:
4503 case ValID::t_APFloat:
4504 case ValID::t_Undef:
4505 case ValID::t_Constant:
4506 case ValID::t_ConstantStruct:
4507 case ValID::t_PackedConstantStruct: {
4509 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4511 assert(isa<Constant>(V) && "Expected a constant value");
4512 C = cast<Constant>(V);
4516 return Error(Loc, "expected a constant value");
4520 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4523 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4526 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4528 return ParseType(Ty) ||
4529 ParseValue(Ty, V, PFS);
4532 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4533 PerFunctionState &PFS) {
4536 if (ParseTypeAndValue(V, PFS)) return true;
4537 if (!isa<BasicBlock>(V))
4538 return Error(Loc, "expected a basic block");
4539 BB = cast<BasicBlock>(V);
4545 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4546 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4547 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4548 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4549 // Parse the linkage.
4550 LocTy LinkageLoc = Lex.getLoc();
4553 unsigned Visibility;
4554 unsigned DLLStorageClass;
4555 AttrBuilder RetAttrs;
4558 Type *RetType = nullptr;
4559 LocTy RetTypeLoc = Lex.getLoc();
4560 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4561 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4562 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4565 // Verify that the linkage is ok.
4566 switch ((GlobalValue::LinkageTypes)Linkage) {
4567 case GlobalValue::ExternalLinkage:
4568 break; // always ok.
4569 case GlobalValue::ExternalWeakLinkage:
4571 return Error(LinkageLoc, "invalid linkage for function definition");
4573 case GlobalValue::PrivateLinkage:
4574 case GlobalValue::InternalLinkage:
4575 case GlobalValue::AvailableExternallyLinkage:
4576 case GlobalValue::LinkOnceAnyLinkage:
4577 case GlobalValue::LinkOnceODRLinkage:
4578 case GlobalValue::WeakAnyLinkage:
4579 case GlobalValue::WeakODRLinkage:
4581 return Error(LinkageLoc, "invalid linkage for function declaration");
4583 case GlobalValue::AppendingLinkage:
4584 case GlobalValue::CommonLinkage:
4585 return Error(LinkageLoc, "invalid function linkage type");
4588 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4589 return Error(LinkageLoc,
4590 "symbol with local linkage must have default visibility");
4592 if (!FunctionType::isValidReturnType(RetType))
4593 return Error(RetTypeLoc, "invalid function return type");
4595 LocTy NameLoc = Lex.getLoc();
4597 std::string FunctionName;
4598 if (Lex.getKind() == lltok::GlobalVar) {
4599 FunctionName = Lex.getStrVal();
4600 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4601 unsigned NameID = Lex.getUIntVal();
4603 if (NameID != NumberedVals.size())
4604 return TokError("function expected to be numbered '%" +
4605 Twine(NumberedVals.size()) + "'");
4607 return TokError("expected function name");
4612 if (Lex.getKind() != lltok::lparen)
4613 return TokError("expected '(' in function argument list");
4615 SmallVector<ArgInfo, 8> ArgList;
4617 AttrBuilder FuncAttrs;
4618 std::vector<unsigned> FwdRefAttrGrps;
4620 std::string Section;
4623 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4624 LocTy UnnamedAddrLoc;
4625 Constant *Prefix = nullptr;
4626 Constant *Prologue = nullptr;
4627 Constant *PersonalityFn = nullptr;
4630 if (ParseArgumentList(ArgList, isVarArg) ||
4631 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4632 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4634 (EatIfPresent(lltok::kw_section) &&
4635 ParseStringConstant(Section)) ||
4636 parseOptionalComdat(FunctionName, C) ||
4637 ParseOptionalAlignment(Alignment) ||
4638 (EatIfPresent(lltok::kw_gc) &&
4639 ParseStringConstant(GC)) ||
4640 (EatIfPresent(lltok::kw_prefix) &&
4641 ParseGlobalTypeAndValue(Prefix)) ||
4642 (EatIfPresent(lltok::kw_prologue) &&
4643 ParseGlobalTypeAndValue(Prologue)) ||
4644 (EatIfPresent(lltok::kw_personality) &&
4645 ParseGlobalTypeAndValue(PersonalityFn)))
4648 if (FuncAttrs.contains(Attribute::Builtin))
4649 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4651 // If the alignment was parsed as an attribute, move to the alignment field.
4652 if (FuncAttrs.hasAlignmentAttr()) {
4653 Alignment = FuncAttrs.getAlignment();
4654 FuncAttrs.removeAttribute(Attribute::Alignment);
4657 // Okay, if we got here, the function is syntactically valid. Convert types
4658 // and do semantic checks.
4659 std::vector<Type*> ParamTypeList;
4660 SmallVector<AttributeSet, 8> Attrs;
4662 if (RetAttrs.hasAttributes())
4663 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4664 AttributeSet::ReturnIndex,
4667 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4668 ParamTypeList.push_back(ArgList[i].Ty);
4669 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4670 AttrBuilder B(ArgList[i].Attrs, i + 1);
4671 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4675 if (FuncAttrs.hasAttributes())
4676 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4677 AttributeSet::FunctionIndex,
4680 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4682 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4683 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4686 FunctionType::get(RetType, ParamTypeList, isVarArg);
4687 PointerType *PFT = PointerType::getUnqual(FT);
4690 if (!FunctionName.empty()) {
4691 // If this was a definition of a forward reference, remove the definition
4692 // from the forward reference table and fill in the forward ref.
4693 auto FRVI = ForwardRefVals.find(FunctionName);
4694 if (FRVI != ForwardRefVals.end()) {
4695 Fn = M->getFunction(FunctionName);
4697 return Error(FRVI->second.second, "invalid forward reference to "
4698 "function as global value!");
4699 if (Fn->getType() != PFT)
4700 return Error(FRVI->second.second, "invalid forward reference to "
4701 "function '" + FunctionName + "' with wrong type!");
4703 ForwardRefVals.erase(FRVI);
4704 } else if ((Fn = M->getFunction(FunctionName))) {
4705 // Reject redefinitions.
4706 return Error(NameLoc, "invalid redefinition of function '" +
4707 FunctionName + "'");
4708 } else if (M->getNamedValue(FunctionName)) {
4709 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4713 // If this is a definition of a forward referenced function, make sure the
4715 auto I = ForwardRefValIDs.find(NumberedVals.size());
4716 if (I != ForwardRefValIDs.end()) {
4717 Fn = cast<Function>(I->second.first);
4718 if (Fn->getType() != PFT)
4719 return Error(NameLoc, "type of definition and forward reference of '@" +
4720 Twine(NumberedVals.size()) + "' disagree");
4721 ForwardRefValIDs.erase(I);
4726 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4727 else // Move the forward-reference to the correct spot in the module.
4728 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4730 if (FunctionName.empty())
4731 NumberedVals.push_back(Fn);
4733 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4734 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4735 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4736 Fn->setCallingConv(CC);
4737 Fn->setAttributes(PAL);
4738 Fn->setUnnamedAddr(UnnamedAddr);
4739 Fn->setAlignment(Alignment);
4740 Fn->setSection(Section);
4742 Fn->setPersonalityFn(PersonalityFn);
4743 if (!GC.empty()) Fn->setGC(GC);
4744 Fn->setPrefixData(Prefix);
4745 Fn->setPrologueData(Prologue);
4746 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4748 // Add all of the arguments we parsed to the function.
4749 Function::arg_iterator ArgIt = Fn->arg_begin();
4750 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4751 // If the argument has a name, insert it into the argument symbol table.
4752 if (ArgList[i].Name.empty()) continue;
4754 // Set the name, if it conflicted, it will be auto-renamed.
4755 ArgIt->setName(ArgList[i].Name);
4757 if (ArgIt->getName() != ArgList[i].Name)
4758 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4759 ArgList[i].Name + "'");
4765 // Check the declaration has no block address forward references.
4767 if (FunctionName.empty()) {
4768 ID.Kind = ValID::t_GlobalID;
4769 ID.UIntVal = NumberedVals.size() - 1;
4771 ID.Kind = ValID::t_GlobalName;
4772 ID.StrVal = FunctionName;
4774 auto Blocks = ForwardRefBlockAddresses.find(ID);
4775 if (Blocks != ForwardRefBlockAddresses.end())
4776 return Error(Blocks->first.Loc,
4777 "cannot take blockaddress inside a declaration");
4781 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4783 if (FunctionNumber == -1) {
4784 ID.Kind = ValID::t_GlobalName;
4785 ID.StrVal = F.getName();
4787 ID.Kind = ValID::t_GlobalID;
4788 ID.UIntVal = FunctionNumber;
4791 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4792 if (Blocks == P.ForwardRefBlockAddresses.end())
4795 for (const auto &I : Blocks->second) {
4796 const ValID &BBID = I.first;
4797 GlobalValue *GV = I.second;
4799 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4800 "Expected local id or name");
4802 if (BBID.Kind == ValID::t_LocalName)
4803 BB = GetBB(BBID.StrVal, BBID.Loc);
4805 BB = GetBB(BBID.UIntVal, BBID.Loc);
4807 return P.Error(BBID.Loc, "referenced value is not a basic block");
4809 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4810 GV->eraseFromParent();
4813 P.ForwardRefBlockAddresses.erase(Blocks);
4817 /// ParseFunctionBody
4818 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4819 bool LLParser::ParseFunctionBody(Function &Fn) {
4820 if (Lex.getKind() != lltok::lbrace)
4821 return TokError("expected '{' in function body");
4822 Lex.Lex(); // eat the {.
4824 int FunctionNumber = -1;
4825 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4827 PerFunctionState PFS(*this, Fn, FunctionNumber);
4829 // Resolve block addresses and allow basic blocks to be forward-declared
4830 // within this function.
4831 if (PFS.resolveForwardRefBlockAddresses())
4833 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4835 // We need at least one basic block.
4836 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4837 return TokError("function body requires at least one basic block");
4839 while (Lex.getKind() != lltok::rbrace &&
4840 Lex.getKind() != lltok::kw_uselistorder)
4841 if (ParseBasicBlock(PFS)) return true;
4843 while (Lex.getKind() != lltok::rbrace)
4844 if (ParseUseListOrder(&PFS))
4850 // Verify function is ok.
4851 return PFS.FinishFunction();
4855 /// ::= LabelStr? Instruction*
4856 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4857 // If this basic block starts out with a name, remember it.
4859 LocTy NameLoc = Lex.getLoc();
4860 if (Lex.getKind() == lltok::LabelStr) {
4861 Name = Lex.getStrVal();
4865 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4867 return Error(NameLoc,
4868 "unable to create block named '" + Name + "'");
4870 std::string NameStr;
4872 // Parse the instructions in this block until we get a terminator.
4875 // This instruction may have three possibilities for a name: a) none
4876 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4877 LocTy NameLoc = Lex.getLoc();
4881 if (Lex.getKind() == lltok::LocalVarID) {
4882 NameID = Lex.getUIntVal();
4884 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4886 } else if (Lex.getKind() == lltok::LocalVar) {
4887 NameStr = Lex.getStrVal();
4889 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4893 switch (ParseInstruction(Inst, BB, PFS)) {
4894 default: llvm_unreachable("Unknown ParseInstruction result!");
4895 case InstError: return true;
4897 BB->getInstList().push_back(Inst);
4899 // With a normal result, we check to see if the instruction is followed by
4900 // a comma and metadata.
4901 if (EatIfPresent(lltok::comma))
4902 if (ParseInstructionMetadata(*Inst))
4905 case InstExtraComma:
4906 BB->getInstList().push_back(Inst);
4908 // If the instruction parser ate an extra comma at the end of it, it
4909 // *must* be followed by metadata.
4910 if (ParseInstructionMetadata(*Inst))
4915 // Set the name on the instruction.
4916 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4917 } while (!isa<TerminatorInst>(Inst));
4922 //===----------------------------------------------------------------------===//
4923 // Instruction Parsing.
4924 //===----------------------------------------------------------------------===//
4926 /// ParseInstruction - Parse one of the many different instructions.
4928 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4929 PerFunctionState &PFS) {
4930 lltok::Kind Token = Lex.getKind();
4931 if (Token == lltok::Eof)
4932 return TokError("found end of file when expecting more instructions");
4933 LocTy Loc = Lex.getLoc();
4934 unsigned KeywordVal = Lex.getUIntVal();
4935 Lex.Lex(); // Eat the keyword.
4938 default: return Error(Loc, "expected instruction opcode");
4939 // Terminator Instructions.
4940 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4941 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4942 case lltok::kw_br: return ParseBr(Inst, PFS);
4943 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4944 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4945 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4946 case lltok::kw_resume: return ParseResume(Inst, PFS);
4947 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4948 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4949 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4950 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4951 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4952 // Binary Operators.
4956 case lltok::kw_shl: {
4957 bool NUW = EatIfPresent(lltok::kw_nuw);
4958 bool NSW = EatIfPresent(lltok::kw_nsw);
4959 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4961 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4963 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4964 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4967 case lltok::kw_fadd:
4968 case lltok::kw_fsub:
4969 case lltok::kw_fmul:
4970 case lltok::kw_fdiv:
4971 case lltok::kw_frem: {
4972 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4973 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4977 Inst->setFastMathFlags(FMF);
4981 case lltok::kw_sdiv:
4982 case lltok::kw_udiv:
4983 case lltok::kw_lshr:
4984 case lltok::kw_ashr: {
4985 bool Exact = EatIfPresent(lltok::kw_exact);
4987 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4988 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4992 case lltok::kw_urem:
4993 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4996 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4997 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
4998 case lltok::kw_fcmp: {
4999 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5000 int Res = ParseCompare(Inst, PFS, KeywordVal);
5004 Inst->setFastMathFlags(FMF);
5009 case lltok::kw_trunc:
5010 case lltok::kw_zext:
5011 case lltok::kw_sext:
5012 case lltok::kw_fptrunc:
5013 case lltok::kw_fpext:
5014 case lltok::kw_bitcast:
5015 case lltok::kw_addrspacecast:
5016 case lltok::kw_uitofp:
5017 case lltok::kw_sitofp:
5018 case lltok::kw_fptoui:
5019 case lltok::kw_fptosi:
5020 case lltok::kw_inttoptr:
5021 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5023 case lltok::kw_select: return ParseSelect(Inst, PFS);
5024 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5025 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5026 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5027 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5028 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5029 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5031 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5032 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5033 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5034 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5036 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5037 case lltok::kw_load: return ParseLoad(Inst, PFS);
5038 case lltok::kw_store: return ParseStore(Inst, PFS);
5039 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5040 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5041 case lltok::kw_fence: return ParseFence(Inst, PFS);
5042 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5043 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5044 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5048 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5049 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5050 if (Opc == Instruction::FCmp) {
5051 switch (Lex.getKind()) {
5052 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5053 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5054 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5055 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5056 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5057 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5058 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5059 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5060 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5061 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5062 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5063 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5064 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5065 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5066 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5067 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5068 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5071 switch (Lex.getKind()) {
5072 default: return TokError("expected icmp predicate (e.g. 'eq')");
5073 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5074 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5075 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5076 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5077 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5078 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5079 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5080 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5081 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5082 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5089 //===----------------------------------------------------------------------===//
5090 // Terminator Instructions.
5091 //===----------------------------------------------------------------------===//
5093 /// ParseRet - Parse a return instruction.
5094 /// ::= 'ret' void (',' !dbg, !1)*
5095 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5096 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5097 PerFunctionState &PFS) {
5098 SMLoc TypeLoc = Lex.getLoc();
5100 if (ParseType(Ty, true /*void allowed*/)) return true;
5102 Type *ResType = PFS.getFunction().getReturnType();
5104 if (Ty->isVoidTy()) {
5105 if (!ResType->isVoidTy())
5106 return Error(TypeLoc, "value doesn't match function result type '" +
5107 getTypeString(ResType) + "'");
5109 Inst = ReturnInst::Create(Context);
5114 if (ParseValue(Ty, RV, PFS)) return true;
5116 if (ResType != RV->getType())
5117 return Error(TypeLoc, "value doesn't match function result type '" +
5118 getTypeString(ResType) + "'");
5120 Inst = ReturnInst::Create(Context, RV);
5126 /// ::= 'br' TypeAndValue
5127 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5128 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5131 BasicBlock *Op1, *Op2;
5132 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5134 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5135 Inst = BranchInst::Create(BB);
5139 if (Op0->getType() != Type::getInt1Ty(Context))
5140 return Error(Loc, "branch condition must have 'i1' type");
5142 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5143 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5144 ParseToken(lltok::comma, "expected ',' after true destination") ||
5145 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5148 Inst = BranchInst::Create(Op1, Op2, Op0);
5154 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5156 /// ::= (TypeAndValue ',' TypeAndValue)*
5157 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5158 LocTy CondLoc, BBLoc;
5160 BasicBlock *DefaultBB;
5161 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5162 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5163 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5164 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5167 if (!Cond->getType()->isIntegerTy())
5168 return Error(CondLoc, "switch condition must have integer type");
5170 // Parse the jump table pairs.
5171 SmallPtrSet<Value*, 32> SeenCases;
5172 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5173 while (Lex.getKind() != lltok::rsquare) {
5177 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5178 ParseToken(lltok::comma, "expected ',' after case value") ||
5179 ParseTypeAndBasicBlock(DestBB, PFS))
5182 if (!SeenCases.insert(Constant).second)
5183 return Error(CondLoc, "duplicate case value in switch");
5184 if (!isa<ConstantInt>(Constant))
5185 return Error(CondLoc, "case value is not a constant integer");
5187 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5190 Lex.Lex(); // Eat the ']'.
5192 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5193 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5194 SI->addCase(Table[i].first, Table[i].second);
5201 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5202 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5205 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5206 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5207 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5210 if (!Address->getType()->isPointerTy())
5211 return Error(AddrLoc, "indirectbr address must have pointer type");
5213 // Parse the destination list.
5214 SmallVector<BasicBlock*, 16> DestList;
5216 if (Lex.getKind() != lltok::rsquare) {
5218 if (ParseTypeAndBasicBlock(DestBB, PFS))
5220 DestList.push_back(DestBB);
5222 while (EatIfPresent(lltok::comma)) {
5223 if (ParseTypeAndBasicBlock(DestBB, PFS))
5225 DestList.push_back(DestBB);
5229 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5232 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5233 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5234 IBI->addDestination(DestList[i]);
5241 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5242 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5243 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5244 LocTy CallLoc = Lex.getLoc();
5245 AttrBuilder RetAttrs, FnAttrs;
5246 std::vector<unsigned> FwdRefAttrGrps;
5249 Type *RetType = nullptr;
5252 SmallVector<ParamInfo, 16> ArgList;
5253 SmallVector<OperandBundleDef, 2> BundleList;
5255 BasicBlock *NormalBB, *UnwindBB;
5256 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5257 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5258 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5259 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5261 ParseOptionalOperandBundles(BundleList, PFS) ||
5262 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5263 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5264 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5265 ParseTypeAndBasicBlock(UnwindBB, PFS))
5268 // If RetType is a non-function pointer type, then this is the short syntax
5269 // for the call, which means that RetType is just the return type. Infer the
5270 // rest of the function argument types from the arguments that are present.
5271 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5273 // Pull out the types of all of the arguments...
5274 std::vector<Type*> ParamTypes;
5275 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5276 ParamTypes.push_back(ArgList[i].V->getType());
5278 if (!FunctionType::isValidReturnType(RetType))
5279 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5281 Ty = FunctionType::get(RetType, ParamTypes, false);
5286 // Look up the callee.
5288 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5291 // Set up the Attribute for the function.
5292 SmallVector<AttributeSet, 8> Attrs;
5293 if (RetAttrs.hasAttributes())
5294 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5295 AttributeSet::ReturnIndex,
5298 SmallVector<Value*, 8> Args;
5300 // Loop through FunctionType's arguments and ensure they are specified
5301 // correctly. Also, gather any parameter attributes.
5302 FunctionType::param_iterator I = Ty->param_begin();
5303 FunctionType::param_iterator E = Ty->param_end();
5304 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5305 Type *ExpectedTy = nullptr;
5308 } else if (!Ty->isVarArg()) {
5309 return Error(ArgList[i].Loc, "too many arguments specified");
5312 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5313 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5314 getTypeString(ExpectedTy) + "'");
5315 Args.push_back(ArgList[i].V);
5316 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5317 AttrBuilder B(ArgList[i].Attrs, i + 1);
5318 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5323 return Error(CallLoc, "not enough parameters specified for call");
5325 if (FnAttrs.hasAttributes()) {
5326 if (FnAttrs.hasAlignmentAttr())
5327 return Error(CallLoc, "invoke instructions may not have an alignment");
5329 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5330 AttributeSet::FunctionIndex,
5334 // Finish off the Attribute and check them
5335 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5338 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5339 II->setCallingConv(CC);
5340 II->setAttributes(PAL);
5341 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5347 /// ::= 'resume' TypeAndValue
5348 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5349 Value *Exn; LocTy ExnLoc;
5350 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5353 ResumeInst *RI = ResumeInst::Create(Exn);
5358 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5359 PerFunctionState &PFS) {
5360 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5363 while (Lex.getKind() != lltok::rsquare) {
5364 // If this isn't the first argument, we need a comma.
5365 if (!Args.empty() &&
5366 ParseToken(lltok::comma, "expected ',' in argument list"))
5369 // Parse the argument.
5371 Type *ArgTy = nullptr;
5372 if (ParseType(ArgTy, ArgLoc))
5376 if (ArgTy->isMetadataTy()) {
5377 if (ParseMetadataAsValue(V, PFS))
5380 if (ParseValue(ArgTy, V, PFS))
5386 Lex.Lex(); // Lex the ']'.
5391 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5392 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5393 Value *CleanupPad = nullptr;
5395 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5398 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5401 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5404 BasicBlock *UnwindBB = nullptr;
5405 if (Lex.getKind() == lltok::kw_to) {
5407 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5410 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5415 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5420 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
5421 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5422 Value *CatchPad = nullptr;
5424 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5427 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5431 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5432 ParseTypeAndBasicBlock(BB, PFS))
5435 Inst = CatchReturnInst::Create(CatchPad, BB);
5439 /// ParseCatchSwitch
5440 /// ::= 'catchswitch' within Parent
5441 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5445 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5448 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5449 Lex.getKind() != lltok::LocalVarID)
5450 return TokError("expected scope value for catchswitch");
5452 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5455 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5458 SmallVector<BasicBlock *, 32> Table;
5461 if (ParseTypeAndBasicBlock(DestBB, PFS))
5463 Table.push_back(DestBB);
5464 } while (EatIfPresent(lltok::comma));
5466 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5469 if (ParseToken(lltok::kw_unwind,
5470 "expected 'unwind' after catchswitch scope"))
5473 BasicBlock *UnwindBB = nullptr;
5474 if (EatIfPresent(lltok::kw_to)) {
5475 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5478 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5483 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5484 for (BasicBlock *DestBB : Table)
5485 CatchSwitch->addHandler(DestBB);
5491 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5492 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5493 Value *CatchSwitch = nullptr;
5495 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5498 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5499 return TokError("expected scope value for catchpad");
5501 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5504 SmallVector<Value *, 8> Args;
5505 if (ParseExceptionArgs(Args, PFS))
5508 Inst = CatchPadInst::Create(CatchSwitch, Args);
5513 /// ::= 'cleanuppad' within Parent ParamList
5514 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5515 Value *ParentPad = nullptr;
5517 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5520 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5521 Lex.getKind() != lltok::LocalVarID)
5522 return TokError("expected scope value for cleanuppad");
5524 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5527 SmallVector<Value *, 8> Args;
5528 if (ParseExceptionArgs(Args, PFS))
5531 Inst = CleanupPadInst::Create(ParentPad, Args);
5535 //===----------------------------------------------------------------------===//
5536 // Binary Operators.
5537 //===----------------------------------------------------------------------===//
5540 /// ::= ArithmeticOps TypeAndValue ',' Value
5542 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5543 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5544 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5545 unsigned Opc, unsigned OperandType) {
5546 LocTy Loc; Value *LHS, *RHS;
5547 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5548 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5549 ParseValue(LHS->getType(), RHS, PFS))
5553 switch (OperandType) {
5554 default: llvm_unreachable("Unknown operand type!");
5555 case 0: // int or FP.
5556 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5557 LHS->getType()->isFPOrFPVectorTy();
5559 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5560 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5564 return Error(Loc, "invalid operand type for instruction");
5566 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5571 /// ::= ArithmeticOps TypeAndValue ',' Value {
5572 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5574 LocTy Loc; Value *LHS, *RHS;
5575 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5576 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5577 ParseValue(LHS->getType(), RHS, PFS))
5580 if (!LHS->getType()->isIntOrIntVectorTy())
5581 return Error(Loc,"instruction requires integer or integer vector operands");
5583 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5589 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5590 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5591 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5593 // Parse the integer/fp comparison predicate.
5597 if (ParseCmpPredicate(Pred, Opc) ||
5598 ParseTypeAndValue(LHS, Loc, PFS) ||
5599 ParseToken(lltok::comma, "expected ',' after compare value") ||
5600 ParseValue(LHS->getType(), RHS, PFS))
5603 if (Opc == Instruction::FCmp) {
5604 if (!LHS->getType()->isFPOrFPVectorTy())
5605 return Error(Loc, "fcmp requires floating point operands");
5606 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5608 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5609 if (!LHS->getType()->isIntOrIntVectorTy() &&
5610 !LHS->getType()->getScalarType()->isPointerTy())
5611 return Error(Loc, "icmp requires integer operands");
5612 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5617 //===----------------------------------------------------------------------===//
5618 // Other Instructions.
5619 //===----------------------------------------------------------------------===//
5623 /// ::= CastOpc TypeAndValue 'to' Type
5624 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5628 Type *DestTy = nullptr;
5629 if (ParseTypeAndValue(Op, Loc, PFS) ||
5630 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5634 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5635 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5636 return Error(Loc, "invalid cast opcode for cast from '" +
5637 getTypeString(Op->getType()) + "' to '" +
5638 getTypeString(DestTy) + "'");
5640 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5645 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5646 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5648 Value *Op0, *Op1, *Op2;
5649 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5650 ParseToken(lltok::comma, "expected ',' after select condition") ||
5651 ParseTypeAndValue(Op1, PFS) ||
5652 ParseToken(lltok::comma, "expected ',' after select value") ||
5653 ParseTypeAndValue(Op2, PFS))
5656 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5657 return Error(Loc, Reason);
5659 Inst = SelectInst::Create(Op0, Op1, Op2);
5664 /// ::= 'va_arg' TypeAndValue ',' Type
5665 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5667 Type *EltTy = nullptr;
5669 if (ParseTypeAndValue(Op, PFS) ||
5670 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5671 ParseType(EltTy, TypeLoc))
5674 if (!EltTy->isFirstClassType())
5675 return Error(TypeLoc, "va_arg requires operand with first class type");
5677 Inst = new VAArgInst(Op, EltTy);
5681 /// ParseExtractElement
5682 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5683 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5686 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5687 ParseToken(lltok::comma, "expected ',' after extract value") ||
5688 ParseTypeAndValue(Op1, PFS))
5691 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5692 return Error(Loc, "invalid extractelement operands");
5694 Inst = ExtractElementInst::Create(Op0, Op1);
5698 /// ParseInsertElement
5699 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5700 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5702 Value *Op0, *Op1, *Op2;
5703 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5704 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5705 ParseTypeAndValue(Op1, PFS) ||
5706 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5707 ParseTypeAndValue(Op2, PFS))
5710 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5711 return Error(Loc, "invalid insertelement operands");
5713 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5717 /// ParseShuffleVector
5718 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5719 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5721 Value *Op0, *Op1, *Op2;
5722 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5723 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5724 ParseTypeAndValue(Op1, PFS) ||
5725 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5726 ParseTypeAndValue(Op2, PFS))
5729 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5730 return Error(Loc, "invalid shufflevector operands");
5732 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5737 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5738 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5739 Type *Ty = nullptr; LocTy TypeLoc;
5742 if (ParseType(Ty, TypeLoc) ||
5743 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5744 ParseValue(Ty, Op0, PFS) ||
5745 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5746 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5747 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5750 bool AteExtraComma = false;
5751 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5753 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5755 if (!EatIfPresent(lltok::comma))
5758 if (Lex.getKind() == lltok::MetadataVar) {
5759 AteExtraComma = true;
5763 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5764 ParseValue(Ty, Op0, PFS) ||
5765 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5766 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5767 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5771 if (!Ty->isFirstClassType())
5772 return Error(TypeLoc, "phi node must have first class type");
5774 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5775 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5776 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5778 return AteExtraComma ? InstExtraComma : InstNormal;
5782 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5784 /// ::= 'catch' TypeAndValue
5786 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5787 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5788 Type *Ty = nullptr; LocTy TyLoc;
5790 if (ParseType(Ty, TyLoc))
5793 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5794 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5796 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5797 LandingPadInst::ClauseType CT;
5798 if (EatIfPresent(lltok::kw_catch))
5799 CT = LandingPadInst::Catch;
5800 else if (EatIfPresent(lltok::kw_filter))
5801 CT = LandingPadInst::Filter;
5803 return TokError("expected 'catch' or 'filter' clause type");
5807 if (ParseTypeAndValue(V, VLoc, PFS))
5810 // A 'catch' type expects a non-array constant. A filter clause expects an
5812 if (CT == LandingPadInst::Catch) {
5813 if (isa<ArrayType>(V->getType()))
5814 Error(VLoc, "'catch' clause has an invalid type");
5816 if (!isa<ArrayType>(V->getType()))
5817 Error(VLoc, "'filter' clause has an invalid type");
5820 Constant *CV = dyn_cast<Constant>(V);
5822 return Error(VLoc, "clause argument must be a constant");
5826 Inst = LP.release();
5831 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5832 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5833 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5834 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5835 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5836 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5837 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5838 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5839 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5840 CallInst::TailCallKind TCK) {
5841 AttrBuilder RetAttrs, FnAttrs;
5842 std::vector<unsigned> FwdRefAttrGrps;
5845 Type *RetType = nullptr;
5848 SmallVector<ParamInfo, 16> ArgList;
5849 SmallVector<OperandBundleDef, 2> BundleList;
5850 LocTy CallLoc = Lex.getLoc();
5852 if (TCK != CallInst::TCK_None &&
5853 ParseToken(lltok::kw_call,
5854 "expected 'tail call', 'musttail call', or 'notail call'"))
5857 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5859 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5860 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5861 ParseValID(CalleeID) ||
5862 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5863 PFS.getFunction().isVarArg()) ||
5864 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5865 ParseOptionalOperandBundles(BundleList, PFS))
5868 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5869 return Error(CallLoc, "fast-math-flags specified for call without "
5870 "floating-point scalar or vector return type");
5872 // If RetType is a non-function pointer type, then this is the short syntax
5873 // for the call, which means that RetType is just the return type. Infer the
5874 // rest of the function argument types from the arguments that are present.
5875 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5877 // Pull out the types of all of the arguments...
5878 std::vector<Type*> ParamTypes;
5879 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5880 ParamTypes.push_back(ArgList[i].V->getType());
5882 if (!FunctionType::isValidReturnType(RetType))
5883 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5885 Ty = FunctionType::get(RetType, ParamTypes, false);
5890 // Look up the callee.
5892 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5895 // Set up the Attribute for the function.
5896 SmallVector<AttributeSet, 8> Attrs;
5897 if (RetAttrs.hasAttributes())
5898 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5899 AttributeSet::ReturnIndex,
5902 SmallVector<Value*, 8> Args;
5904 // Loop through FunctionType's arguments and ensure they are specified
5905 // correctly. Also, gather any parameter attributes.
5906 FunctionType::param_iterator I = Ty->param_begin();
5907 FunctionType::param_iterator E = Ty->param_end();
5908 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5909 Type *ExpectedTy = nullptr;
5912 } else if (!Ty->isVarArg()) {
5913 return Error(ArgList[i].Loc, "too many arguments specified");
5916 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5917 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5918 getTypeString(ExpectedTy) + "'");
5919 Args.push_back(ArgList[i].V);
5920 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5921 AttrBuilder B(ArgList[i].Attrs, i + 1);
5922 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5927 return Error(CallLoc, "not enough parameters specified for call");
5929 if (FnAttrs.hasAttributes()) {
5930 if (FnAttrs.hasAlignmentAttr())
5931 return Error(CallLoc, "call instructions may not have an alignment");
5933 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5934 AttributeSet::FunctionIndex,
5938 // Finish off the Attribute and check them
5939 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5941 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
5942 CI->setTailCallKind(TCK);
5943 CI->setCallingConv(CC);
5945 CI->setFastMathFlags(FMF);
5946 CI->setAttributes(PAL);
5947 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5952 //===----------------------------------------------------------------------===//
5953 // Memory Instructions.
5954 //===----------------------------------------------------------------------===//
5957 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5958 /// (',' 'align' i32)?
5959 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5960 Value *Size = nullptr;
5961 LocTy SizeLoc, TyLoc;
5962 unsigned Alignment = 0;
5965 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5966 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
5968 if (ParseType(Ty, TyLoc)) return true;
5970 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5971 return Error(TyLoc, "invalid type for alloca");
5973 bool AteExtraComma = false;
5974 if (EatIfPresent(lltok::comma)) {
5975 if (Lex.getKind() == lltok::kw_align) {
5976 if (ParseOptionalAlignment(Alignment)) return true;
5977 } else if (Lex.getKind() == lltok::MetadataVar) {
5978 AteExtraComma = true;
5980 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5981 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5986 if (Size && !Size->getType()->isIntegerTy())
5987 return Error(SizeLoc, "element count must have integer type");
5989 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5990 AI->setUsedWithInAlloca(IsInAlloca);
5991 AI->setSwiftError(IsSwiftError);
5993 return AteExtraComma ? InstExtraComma : InstNormal;
5997 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5998 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5999 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6000 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6001 Value *Val; LocTy Loc;
6002 unsigned Alignment = 0;
6003 bool AteExtraComma = false;
6004 bool isAtomic = false;
6005 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6006 SynchronizationScope Scope = CrossThread;
6008 if (Lex.getKind() == lltok::kw_atomic) {
6013 bool isVolatile = false;
6014 if (Lex.getKind() == lltok::kw_volatile) {
6020 LocTy ExplicitTypeLoc = Lex.getLoc();
6021 if (ParseType(Ty) ||
6022 ParseToken(lltok::comma, "expected comma after load's type") ||
6023 ParseTypeAndValue(Val, Loc, PFS) ||
6024 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6025 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6028 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6029 return Error(Loc, "load operand must be a pointer to a first class type");
6030 if (isAtomic && !Alignment)
6031 return Error(Loc, "atomic load must have explicit non-zero alignment");
6032 if (Ordering == AtomicOrdering::Release ||
6033 Ordering == AtomicOrdering::AcquireRelease)
6034 return Error(Loc, "atomic load cannot use Release ordering");
6036 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6037 return Error(ExplicitTypeLoc,
6038 "explicit pointee type doesn't match operand's pointee type");
6040 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
6041 return AteExtraComma ? InstExtraComma : InstNormal;
6046 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6047 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6048 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6049 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6050 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6051 unsigned Alignment = 0;
6052 bool AteExtraComma = false;
6053 bool isAtomic = false;
6054 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6055 SynchronizationScope Scope = CrossThread;
6057 if (Lex.getKind() == lltok::kw_atomic) {
6062 bool isVolatile = false;
6063 if (Lex.getKind() == lltok::kw_volatile) {
6068 if (ParseTypeAndValue(Val, Loc, PFS) ||
6069 ParseToken(lltok::comma, "expected ',' after store operand") ||
6070 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6071 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6072 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6075 if (!Ptr->getType()->isPointerTy())
6076 return Error(PtrLoc, "store operand must be a pointer");
6077 if (!Val->getType()->isFirstClassType())
6078 return Error(Loc, "store operand must be a first class value");
6079 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6080 return Error(Loc, "stored value and pointer type do not match");
6081 if (isAtomic && !Alignment)
6082 return Error(Loc, "atomic store must have explicit non-zero alignment");
6083 if (Ordering == AtomicOrdering::Acquire ||
6084 Ordering == AtomicOrdering::AcquireRelease)
6085 return Error(Loc, "atomic store cannot use Acquire ordering");
6087 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6088 return AteExtraComma ? InstExtraComma : InstNormal;
6092 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6093 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6094 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6095 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6096 bool AteExtraComma = false;
6097 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6098 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6099 SynchronizationScope Scope = CrossThread;
6100 bool isVolatile = false;
6101 bool isWeak = false;
6103 if (EatIfPresent(lltok::kw_weak))
6106 if (EatIfPresent(lltok::kw_volatile))
6109 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6110 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6111 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6112 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6113 ParseTypeAndValue(New, NewLoc, PFS) ||
6114 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6115 ParseOrdering(FailureOrdering))
6118 if (SuccessOrdering == AtomicOrdering::Unordered ||
6119 FailureOrdering == AtomicOrdering::Unordered)
6120 return TokError("cmpxchg cannot be unordered");
6121 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6122 return TokError("cmpxchg failure argument shall be no stronger than the "
6123 "success argument");
6124 if (FailureOrdering == AtomicOrdering::Release ||
6125 FailureOrdering == AtomicOrdering::AcquireRelease)
6127 "cmpxchg failure ordering cannot include release semantics");
6128 if (!Ptr->getType()->isPointerTy())
6129 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6130 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6131 return Error(CmpLoc, "compare value and pointer type do not match");
6132 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6133 return Error(NewLoc, "new value and pointer type do not match");
6134 if (!New->getType()->isFirstClassType())
6135 return Error(NewLoc, "cmpxchg operand must be a first class value");
6136 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6137 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6138 CXI->setVolatile(isVolatile);
6139 CXI->setWeak(isWeak);
6141 return AteExtraComma ? InstExtraComma : InstNormal;
6145 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6146 /// 'singlethread'? AtomicOrdering
6147 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6148 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6149 bool AteExtraComma = false;
6150 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6151 SynchronizationScope Scope = CrossThread;
6152 bool isVolatile = false;
6153 AtomicRMWInst::BinOp Operation;
6155 if (EatIfPresent(lltok::kw_volatile))
6158 switch (Lex.getKind()) {
6159 default: return TokError("expected binary operation in atomicrmw");
6160 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6161 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6162 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6163 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6164 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6165 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6166 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6167 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6168 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6169 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6170 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6172 Lex.Lex(); // Eat the operation.
6174 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6175 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6176 ParseTypeAndValue(Val, ValLoc, PFS) ||
6177 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6180 if (Ordering == AtomicOrdering::Unordered)
6181 return TokError("atomicrmw cannot be unordered");
6182 if (!Ptr->getType()->isPointerTy())
6183 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6184 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6185 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6186 if (!Val->getType()->isIntegerTy())
6187 return Error(ValLoc, "atomicrmw operand must be an integer");
6188 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6189 if (Size < 8 || (Size & (Size - 1)))
6190 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6193 AtomicRMWInst *RMWI =
6194 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6195 RMWI->setVolatile(isVolatile);
6197 return AteExtraComma ? InstExtraComma : InstNormal;
6201 /// ::= 'fence' 'singlethread'? AtomicOrdering
6202 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6203 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6204 SynchronizationScope Scope = CrossThread;
6205 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6208 if (Ordering == AtomicOrdering::Unordered)
6209 return TokError("fence cannot be unordered");
6210 if (Ordering == AtomicOrdering::Monotonic)
6211 return TokError("fence cannot be monotonic");
6213 Inst = new FenceInst(Context, Ordering, Scope);
6217 /// ParseGetElementPtr
6218 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6219 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6220 Value *Ptr = nullptr;
6221 Value *Val = nullptr;
6224 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6227 LocTy ExplicitTypeLoc = Lex.getLoc();
6228 if (ParseType(Ty) ||
6229 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6230 ParseTypeAndValue(Ptr, Loc, PFS))
6233 Type *BaseType = Ptr->getType();
6234 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6235 if (!BasePointerType)
6236 return Error(Loc, "base of getelementptr must be a pointer");
6238 if (Ty != BasePointerType->getElementType())
6239 return Error(ExplicitTypeLoc,
6240 "explicit pointee type doesn't match operand's pointee type");
6242 SmallVector<Value*, 16> Indices;
6243 bool AteExtraComma = false;
6244 // GEP returns a vector of pointers if at least one of parameters is a vector.
6245 // All vector parameters should have the same vector width.
6246 unsigned GEPWidth = BaseType->isVectorTy() ?
6247 BaseType->getVectorNumElements() : 0;
6249 while (EatIfPresent(lltok::comma)) {
6250 if (Lex.getKind() == lltok::MetadataVar) {
6251 AteExtraComma = true;
6254 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6255 if (!Val->getType()->getScalarType()->isIntegerTy())
6256 return Error(EltLoc, "getelementptr index must be an integer");
6258 if (Val->getType()->isVectorTy()) {
6259 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6260 if (GEPWidth && GEPWidth != ValNumEl)
6261 return Error(EltLoc,
6262 "getelementptr vector index has a wrong number of elements");
6263 GEPWidth = ValNumEl;
6265 Indices.push_back(Val);
6268 SmallPtrSet<Type*, 4> Visited;
6269 if (!Indices.empty() && !Ty->isSized(&Visited))
6270 return Error(Loc, "base element of getelementptr must be sized");
6272 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6273 return Error(Loc, "invalid getelementptr indices");
6274 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6276 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6277 return AteExtraComma ? InstExtraComma : InstNormal;
6280 /// ParseExtractValue
6281 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6282 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6283 Value *Val; LocTy Loc;
6284 SmallVector<unsigned, 4> Indices;
6286 if (ParseTypeAndValue(Val, Loc, PFS) ||
6287 ParseIndexList(Indices, AteExtraComma))
6290 if (!Val->getType()->isAggregateType())
6291 return Error(Loc, "extractvalue operand must be aggregate type");
6293 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6294 return Error(Loc, "invalid indices for extractvalue");
6295 Inst = ExtractValueInst::Create(Val, Indices);
6296 return AteExtraComma ? InstExtraComma : InstNormal;
6299 /// ParseInsertValue
6300 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6301 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6302 Value *Val0, *Val1; LocTy Loc0, Loc1;
6303 SmallVector<unsigned, 4> Indices;
6305 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6306 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6307 ParseTypeAndValue(Val1, Loc1, PFS) ||
6308 ParseIndexList(Indices, AteExtraComma))
6311 if (!Val0->getType()->isAggregateType())
6312 return Error(Loc0, "insertvalue operand must be aggregate type");
6314 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6316 return Error(Loc0, "invalid indices for insertvalue");
6317 if (IndexedType != Val1->getType())
6318 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6319 getTypeString(Val1->getType()) + "' instead of '" +
6320 getTypeString(IndexedType) + "'");
6321 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6322 return AteExtraComma ? InstExtraComma : InstNormal;
6325 //===----------------------------------------------------------------------===//
6326 // Embedded metadata.
6327 //===----------------------------------------------------------------------===//
6329 /// ParseMDNodeVector
6330 /// ::= { Element (',' Element)* }
6332 /// ::= 'null' | TypeAndValue
6333 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6334 if (ParseToken(lltok::lbrace, "expected '{' here"))
6337 // Check for an empty list.
6338 if (EatIfPresent(lltok::rbrace))
6342 // Null is a special case since it is typeless.
6343 if (EatIfPresent(lltok::kw_null)) {
6344 Elts.push_back(nullptr);
6349 if (ParseMetadata(MD, nullptr))
6352 } while (EatIfPresent(lltok::comma));
6354 return ParseToken(lltok::rbrace, "expected end of metadata node");
6357 //===----------------------------------------------------------------------===//
6358 // Use-list order directives.
6359 //===----------------------------------------------------------------------===//
6360 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6363 return Error(Loc, "value has no uses");
6365 unsigned NumUses = 0;
6366 SmallDenseMap<const Use *, unsigned, 16> Order;
6367 for (const Use &U : V->uses()) {
6368 if (++NumUses > Indexes.size())
6370 Order[&U] = Indexes[NumUses - 1];
6373 return Error(Loc, "value only has one use");
6374 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6375 return Error(Loc, "wrong number of indexes, expected " +
6376 Twine(std::distance(V->use_begin(), V->use_end())));
6378 V->sortUseList([&](const Use &L, const Use &R) {
6379 return Order.lookup(&L) < Order.lookup(&R);
6384 /// ParseUseListOrderIndexes
6385 /// ::= '{' uint32 (',' uint32)+ '}'
6386 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6387 SMLoc Loc = Lex.getLoc();
6388 if (ParseToken(lltok::lbrace, "expected '{' here"))
6390 if (Lex.getKind() == lltok::rbrace)
6391 return Lex.Error("expected non-empty list of uselistorder indexes");
6393 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6394 // indexes should be distinct numbers in the range [0, size-1], and should
6396 unsigned Offset = 0;
6398 bool IsOrdered = true;
6399 assert(Indexes.empty() && "Expected empty order vector");
6402 if (ParseUInt32(Index))
6405 // Update consistency checks.
6406 Offset += Index - Indexes.size();
6407 Max = std::max(Max, Index);
6408 IsOrdered &= Index == Indexes.size();
6410 Indexes.push_back(Index);
6411 } while (EatIfPresent(lltok::comma));
6413 if (ParseToken(lltok::rbrace, "expected '}' here"))
6416 if (Indexes.size() < 2)
6417 return Error(Loc, "expected >= 2 uselistorder indexes");
6418 if (Offset != 0 || Max >= Indexes.size())
6419 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6421 return Error(Loc, "expected uselistorder indexes to change the order");
6426 /// ParseUseListOrder
6427 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6428 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6429 SMLoc Loc = Lex.getLoc();
6430 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6434 SmallVector<unsigned, 16> Indexes;
6435 if (ParseTypeAndValue(V, PFS) ||
6436 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6437 ParseUseListOrderIndexes(Indexes))
6440 return sortUseListOrder(V, Indexes, Loc);
6443 /// ParseUseListOrderBB
6444 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6445 bool LLParser::ParseUseListOrderBB() {
6446 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6447 SMLoc Loc = Lex.getLoc();
6451 SmallVector<unsigned, 16> Indexes;
6452 if (ParseValID(Fn) ||
6453 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6454 ParseValID(Label) ||
6455 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6456 ParseUseListOrderIndexes(Indexes))
6459 // Check the function.
6461 if (Fn.Kind == ValID::t_GlobalName)
6462 GV = M->getNamedValue(Fn.StrVal);
6463 else if (Fn.Kind == ValID::t_GlobalID)
6464 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6466 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6468 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6469 auto *F = dyn_cast<Function>(GV);
6471 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6472 if (F->isDeclaration())
6473 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6475 // Check the basic block.
6476 if (Label.Kind == ValID::t_LocalID)
6477 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6478 if (Label.Kind != ValID::t_LocalName)
6479 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6480 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6482 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6483 if (!isa<BasicBlock>(V))
6484 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6486 return sortUseListOrder(V, Indexes, Loc);