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/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/Dwarf.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
57 static std::string getTypeString(Type *T) {
59 raw_string_ostream Tmp(Result);
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run() {
69 if (Context.shouldDiscardValueNames())
72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
78 bool LLParser::parseStandaloneConstantValue(Constant *&C,
79 const SlotMapping *Slots) {
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
86 if (Lex.getKind() != lltok::Eof)
87 return Error(Lex.getLoc(), "expected end of string");
91 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
92 const SlotMapping *Slots) {
93 restoreParsingState(Slots);
97 SMLoc Start = Lex.getLoc();
101 SMLoc End = Lex.getLoc();
102 Read = End.getPointer() - Start.getPointer();
107 void LLParser::restoreParsingState(const SlotMapping *Slots) {
110 NumberedVals = Slots->GlobalValues;
111 NumberedMetadata = Slots->MetadataNodes;
112 for (const auto &I : Slots->NamedTypes)
114 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
115 for (const auto &I : Slots->Types)
116 NumberedTypes.insert(
117 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
120 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
122 bool LLParser::ValidateEndOfModule() {
123 // Handle any function attribute group forward references.
124 for (std::map<Value*, std::vector<unsigned> >::iterator
125 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
128 std::vector<unsigned> &Vec = I->second;
131 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
133 B.merge(NumberedAttrBuilders[*VI]);
135 if (Function *Fn = dyn_cast<Function>(V)) {
136 AttributeSet AS = Fn->getAttributes();
137 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
138 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
139 AS.getFnAttributes());
143 // If the alignment was parsed as an attribute, move to the alignment
145 if (FnAttrs.hasAlignmentAttr()) {
146 Fn->setAlignment(FnAttrs.getAlignment());
147 FnAttrs.removeAttribute(Attribute::Alignment);
150 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
151 AttributeSet::get(Context,
152 AttributeSet::FunctionIndex,
154 Fn->setAttributes(AS);
155 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
156 AttributeSet AS = CI->getAttributes();
157 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
158 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
159 AS.getFnAttributes());
161 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
162 AttributeSet::get(Context,
163 AttributeSet::FunctionIndex,
165 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeSet AS = II->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
169 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
170 AS.getFnAttributes());
172 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
173 AttributeSet::get(Context,
174 AttributeSet::FunctionIndex,
176 II->setAttributes(AS);
178 llvm_unreachable("invalid object with forward attribute group reference");
182 // If there are entries in ForwardRefBlockAddresses at this point, the
183 // function was never defined.
184 if (!ForwardRefBlockAddresses.empty())
185 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
186 "expected function name in blockaddress");
188 for (const auto &NT : NumberedTypes)
189 if (NT.second.second.isValid())
190 return Error(NT.second.second,
191 "use of undefined type '%" + Twine(NT.first) + "'");
193 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
194 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
195 if (I->second.second.isValid())
196 return Error(I->second.second,
197 "use of undefined type named '" + I->getKey() + "'");
199 if (!ForwardRefComdats.empty())
200 return Error(ForwardRefComdats.begin()->second,
201 "use of undefined comdat '$" +
202 ForwardRefComdats.begin()->first + "'");
204 if (!ForwardRefVals.empty())
205 return Error(ForwardRefVals.begin()->second.second,
206 "use of undefined value '@" + ForwardRefVals.begin()->first +
209 if (!ForwardRefValIDs.empty())
210 return Error(ForwardRefValIDs.begin()->second.second,
211 "use of undefined value '@" +
212 Twine(ForwardRefValIDs.begin()->first) + "'");
214 if (!ForwardRefMDNodes.empty())
215 return Error(ForwardRefMDNodes.begin()->second.second,
216 "use of undefined metadata '!" +
217 Twine(ForwardRefMDNodes.begin()->first) + "'");
219 // Resolve metadata cycles.
220 for (auto &N : NumberedMetadata) {
221 if (N.second && !N.second->isResolved())
222 N.second->resolveCycles();
225 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
226 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
228 // Look for intrinsic functions and CallInst that need to be upgraded
229 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
230 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
232 // Some types could be renamed during loading if several modules are
233 // loaded in the same LLVMContext (LTO scenario). In this case we should
234 // remangle intrinsics names as well.
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
236 Function *F = &*FI++;
237 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
238 F->replaceAllUsesWith(Remangled.getValue());
239 F->eraseFromParent();
243 UpgradeDebugInfo(*M);
245 UpgradeModuleFlags(*M);
249 // Initialize the slot mapping.
250 // Because by this point we've parsed and validated everything, we can "steal"
251 // the mapping from LLParser as it doesn't need it anymore.
252 Slots->GlobalValues = std::move(NumberedVals);
253 Slots->MetadataNodes = std::move(NumberedMetadata);
254 for (const auto &I : NamedTypes)
255 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
256 for (const auto &I : NumberedTypes)
257 Slots->Types.insert(std::make_pair(I.first, I.second.first));
262 //===----------------------------------------------------------------------===//
263 // Top-Level Entities
264 //===----------------------------------------------------------------------===//
266 bool LLParser::ParseTopLevelEntities() {
268 switch (Lex.getKind()) {
269 default: return TokError("expected top-level entity");
270 case lltok::Eof: return false;
271 case lltok::kw_declare: if (ParseDeclare()) return true; break;
272 case lltok::kw_define: if (ParseDefine()) return true; break;
273 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
274 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
275 case lltok::kw_source_filename:
276 if (ParseSourceFileName())
279 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
280 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
281 case lltok::LocalVar: if (ParseNamedType()) return true; break;
282 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
283 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
284 case lltok::ComdatVar: if (parseComdat()) return true; break;
285 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
286 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
287 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
288 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
289 case lltok::kw_uselistorder_bb:
290 if (ParseUseListOrderBB())
298 /// ::= 'module' 'asm' STRINGCONSTANT
299 bool LLParser::ParseModuleAsm() {
300 assert(Lex.getKind() == lltok::kw_module);
304 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
305 ParseStringConstant(AsmStr)) return true;
307 M->appendModuleInlineAsm(AsmStr);
312 /// ::= 'target' 'triple' '=' STRINGCONSTANT
313 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
314 bool LLParser::ParseTargetDefinition() {
315 assert(Lex.getKind() == lltok::kw_target);
318 default: return TokError("unknown target property");
319 case lltok::kw_triple:
321 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
322 ParseStringConstant(Str))
324 M->setTargetTriple(Str);
326 case lltok::kw_datalayout:
328 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
329 ParseStringConstant(Str))
331 M->setDataLayout(Str);
337 /// ::= 'source_filename' '=' STRINGCONSTANT
338 bool LLParser::ParseSourceFileName() {
339 assert(Lex.getKind() == lltok::kw_source_filename);
342 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
343 ParseStringConstant(Str))
345 M->setSourceFileName(Str);
350 /// ::= 'deplibs' '=' '[' ']'
351 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
352 /// FIXME: Remove in 4.0. Currently parse, but ignore.
353 bool LLParser::ParseDepLibs() {
354 assert(Lex.getKind() == lltok::kw_deplibs);
356 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
357 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
360 if (EatIfPresent(lltok::rsquare))
365 if (ParseStringConstant(Str)) return true;
366 } while (EatIfPresent(lltok::comma));
368 return ParseToken(lltok::rsquare, "expected ']' at end of list");
371 /// ParseUnnamedType:
372 /// ::= LocalVarID '=' 'type' type
373 bool LLParser::ParseUnnamedType() {
374 LocTy TypeLoc = Lex.getLoc();
375 unsigned TypeID = Lex.getUIntVal();
376 Lex.Lex(); // eat LocalVarID;
378 if (ParseToken(lltok::equal, "expected '=' after name") ||
379 ParseToken(lltok::kw_type, "expected 'type' after '='"))
382 Type *Result = nullptr;
383 if (ParseStructDefinition(TypeLoc, "",
384 NumberedTypes[TypeID], Result)) return true;
386 if (!isa<StructType>(Result)) {
387 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
389 return Error(TypeLoc, "non-struct types may not be recursive");
390 Entry.first = Result;
391 Entry.second = SMLoc();
398 /// ::= LocalVar '=' 'type' type
399 bool LLParser::ParseNamedType() {
400 std::string Name = Lex.getStrVal();
401 LocTy NameLoc = Lex.getLoc();
402 Lex.Lex(); // eat LocalVar.
404 if (ParseToken(lltok::equal, "expected '=' after name") ||
405 ParseToken(lltok::kw_type, "expected 'type' after name"))
408 Type *Result = nullptr;
409 if (ParseStructDefinition(NameLoc, Name,
410 NamedTypes[Name], Result)) return true;
412 if (!isa<StructType>(Result)) {
413 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
415 return Error(NameLoc, "non-struct types may not be recursive");
416 Entry.first = Result;
417 Entry.second = SMLoc();
424 /// ::= 'declare' FunctionHeader
425 bool LLParser::ParseDeclare() {
426 assert(Lex.getKind() == lltok::kw_declare);
429 std::vector<std::pair<unsigned, MDNode *>> MDs;
430 while (Lex.getKind() == lltok::MetadataVar) {
433 if (ParseMetadataAttachment(MDK, N))
435 MDs.push_back({MDK, N});
439 if (ParseFunctionHeader(F, false))
442 F->addMetadata(MD.first, *MD.second);
447 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
448 bool LLParser::ParseDefine() {
449 assert(Lex.getKind() == lltok::kw_define);
453 return ParseFunctionHeader(F, true) ||
454 ParseOptionalFunctionMetadata(*F) ||
455 ParseFunctionBody(*F);
461 bool LLParser::ParseGlobalType(bool &IsConstant) {
462 if (Lex.getKind() == lltok::kw_constant)
464 else if (Lex.getKind() == lltok::kw_global)
468 return TokError("expected 'global' or 'constant'");
474 bool LLParser::ParseOptionalUnnamedAddr(
475 GlobalVariable::UnnamedAddr &UnnamedAddr) {
476 if (EatIfPresent(lltok::kw_unnamed_addr))
477 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
478 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
479 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
481 UnnamedAddr = GlobalValue::UnnamedAddr::None;
485 /// ParseUnnamedGlobal:
486 /// OptionalVisibility (ALIAS | IFUNC) ...
487 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
488 /// ... -> global variable
489 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
490 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
491 /// ... -> global variable
492 bool LLParser::ParseUnnamedGlobal() {
493 unsigned VarID = NumberedVals.size();
495 LocTy NameLoc = Lex.getLoc();
497 // Handle the GlobalID form.
498 if (Lex.getKind() == lltok::GlobalID) {
499 if (Lex.getUIntVal() != VarID)
500 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
502 Lex.Lex(); // eat GlobalID;
504 if (ParseToken(lltok::equal, "expected '=' after name"))
509 unsigned Linkage, Visibility, DLLStorageClass;
510 GlobalVariable::ThreadLocalMode TLM;
511 GlobalVariable::UnnamedAddr UnnamedAddr;
512 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
513 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
516 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
517 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
518 DLLStorageClass, TLM, UnnamedAddr);
520 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
521 DLLStorageClass, TLM, UnnamedAddr);
524 /// ParseNamedGlobal:
525 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
526 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
527 /// ... -> global variable
528 bool LLParser::ParseNamedGlobal() {
529 assert(Lex.getKind() == lltok::GlobalVar);
530 LocTy NameLoc = Lex.getLoc();
531 std::string Name = Lex.getStrVal();
535 unsigned Linkage, Visibility, DLLStorageClass;
536 GlobalVariable::ThreadLocalMode TLM;
537 GlobalVariable::UnnamedAddr UnnamedAddr;
538 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
539 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
540 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
543 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
544 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
545 DLLStorageClass, TLM, UnnamedAddr);
547 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
548 DLLStorageClass, TLM, UnnamedAddr);
551 bool LLParser::parseComdat() {
552 assert(Lex.getKind() == lltok::ComdatVar);
553 std::string Name = Lex.getStrVal();
554 LocTy NameLoc = Lex.getLoc();
557 if (ParseToken(lltok::equal, "expected '=' here"))
560 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
561 return TokError("expected comdat type");
563 Comdat::SelectionKind SK;
564 switch (Lex.getKind()) {
566 return TokError("unknown selection kind");
570 case lltok::kw_exactmatch:
571 SK = Comdat::ExactMatch;
573 case lltok::kw_largest:
574 SK = Comdat::Largest;
576 case lltok::kw_noduplicates:
577 SK = Comdat::NoDuplicates;
579 case lltok::kw_samesize:
580 SK = Comdat::SameSize;
585 // See if the comdat was forward referenced, if so, use the comdat.
586 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
587 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
588 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
589 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
592 if (I != ComdatSymTab.end())
595 C = M->getOrInsertComdat(Name);
596 C->setSelectionKind(SK);
602 // ::= '!' STRINGCONSTANT
603 bool LLParser::ParseMDString(MDString *&Result) {
605 if (ParseStringConstant(Str)) return true;
606 Result = MDString::get(Context, Str);
611 // ::= '!' MDNodeNumber
612 bool LLParser::ParseMDNodeID(MDNode *&Result) {
613 // !{ ..., !42, ... }
614 LocTy IDLoc = Lex.getLoc();
616 if (ParseUInt32(MID))
619 // If not a forward reference, just return it now.
620 if (NumberedMetadata.count(MID)) {
621 Result = NumberedMetadata[MID];
625 // Otherwise, create MDNode forward reference.
626 auto &FwdRef = ForwardRefMDNodes[MID];
627 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
629 Result = FwdRef.first.get();
630 NumberedMetadata[MID].reset(Result);
634 /// ParseNamedMetadata:
635 /// !foo = !{ !1, !2 }
636 bool LLParser::ParseNamedMetadata() {
637 assert(Lex.getKind() == lltok::MetadataVar);
638 std::string Name = Lex.getStrVal();
641 if (ParseToken(lltok::equal, "expected '=' here") ||
642 ParseToken(lltok::exclaim, "Expected '!' here") ||
643 ParseToken(lltok::lbrace, "Expected '{' here"))
646 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
647 if (Lex.getKind() != lltok::rbrace)
649 if (ParseToken(lltok::exclaim, "Expected '!' here"))
653 if (ParseMDNodeID(N)) return true;
655 } while (EatIfPresent(lltok::comma));
657 return ParseToken(lltok::rbrace, "expected end of metadata node");
660 /// ParseStandaloneMetadata:
662 bool LLParser::ParseStandaloneMetadata() {
663 assert(Lex.getKind() == lltok::exclaim);
665 unsigned MetadataID = 0;
668 if (ParseUInt32(MetadataID) ||
669 ParseToken(lltok::equal, "expected '=' here"))
672 // Detect common error, from old metadata syntax.
673 if (Lex.getKind() == lltok::Type)
674 return TokError("unexpected type in metadata definition");
676 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
677 if (Lex.getKind() == lltok::MetadataVar) {
678 if (ParseSpecializedMDNode(Init, IsDistinct))
680 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
681 ParseMDTuple(Init, IsDistinct))
684 // See if this was forward referenced, if so, handle it.
685 auto FI = ForwardRefMDNodes.find(MetadataID);
686 if (FI != ForwardRefMDNodes.end()) {
687 FI->second.first->replaceAllUsesWith(Init);
688 ForwardRefMDNodes.erase(FI);
690 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
692 if (NumberedMetadata.count(MetadataID))
693 return TokError("Metadata id is already used");
694 NumberedMetadata[MetadataID].reset(Init);
700 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
701 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
702 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
705 /// parseIndirectSymbol:
706 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
707 /// OptionalDLLStorageClass OptionalThreadLocal
708 /// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
713 /// Everything through OptionalUnnamedAddr has already been parsed.
715 bool LLParser::parseIndirectSymbol(
716 const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
717 unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
718 GlobalVariable::UnnamedAddr UnnamedAddr) {
720 if (Lex.getKind() == lltok::kw_alias)
722 else if (Lex.getKind() == lltok::kw_ifunc)
725 llvm_unreachable("Not an alias or ifunc!");
728 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
730 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
731 return Error(NameLoc, "invalid linkage type for alias");
733 if (!isValidVisibilityForLinkage(Visibility, L))
734 return Error(NameLoc,
735 "symbol with local linkage must have default visibility");
738 LocTy ExplicitTypeLoc = Lex.getLoc();
740 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
744 LocTy AliaseeLoc = Lex.getLoc();
745 if (Lex.getKind() != lltok::kw_bitcast &&
746 Lex.getKind() != lltok::kw_getelementptr &&
747 Lex.getKind() != lltok::kw_addrspacecast &&
748 Lex.getKind() != lltok::kw_inttoptr) {
749 if (ParseGlobalTypeAndValue(Aliasee))
752 // The bitcast dest type is not present, it is implied by the dest type.
756 if (ID.Kind != ValID::t_Constant)
757 return Error(AliaseeLoc, "invalid aliasee");
758 Aliasee = ID.ConstantVal;
761 Type *AliaseeType = Aliasee->getType();
762 auto *PTy = dyn_cast<PointerType>(AliaseeType);
764 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
765 unsigned AddrSpace = PTy->getAddressSpace();
767 if (IsAlias && Ty != PTy->getElementType())
770 "explicit pointee type doesn't match operand's pointee type");
772 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
775 "explicit pointee type should be a function type");
777 GlobalValue *GVal = nullptr;
779 // See if the alias was forward referenced, if so, prepare to replace the
780 // forward reference.
782 GVal = M->getNamedValue(Name);
784 if (!ForwardRefVals.erase(Name))
785 return Error(NameLoc, "redefinition of global '@" + Name + "'");
788 auto I = ForwardRefValIDs.find(NumberedVals.size());
789 if (I != ForwardRefValIDs.end()) {
790 GVal = I->second.first;
791 ForwardRefValIDs.erase(I);
795 // Okay, create the alias but do not insert it into the module yet.
796 std::unique_ptr<GlobalIndirectSymbol> GA;
798 GA.reset(GlobalAlias::create(Ty, AddrSpace,
799 (GlobalValue::LinkageTypes)Linkage, Name,
800 Aliasee, /*Parent*/ nullptr));
802 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
803 (GlobalValue::LinkageTypes)Linkage, Name,
804 Aliasee, /*Parent*/ nullptr));
805 GA->setThreadLocalMode(TLM);
806 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
807 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
808 GA->setUnnamedAddr(UnnamedAddr);
811 NumberedVals.push_back(GA.get());
814 // Verify that types agree.
815 if (GVal->getType() != GA->getType())
818 "forward reference and definition of alias have different types");
820 // If they agree, just RAUW the old value with the alias and remove the
822 GVal->replaceAllUsesWith(GA.get());
823 GVal->eraseFromParent();
826 // Insert into the module, we know its name won't collide now.
828 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
830 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
831 assert(GA->getName() == Name && "Should not be a name conflict!");
833 // The module owns this now
840 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
841 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
842 /// OptionalExternallyInitialized GlobalType Type Const
843 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
844 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
845 /// OptionalExternallyInitialized GlobalType Type Const
847 /// Everything up to and including OptionalUnnamedAddr has been parsed
850 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
851 unsigned Linkage, bool HasLinkage,
852 unsigned Visibility, unsigned DLLStorageClass,
853 GlobalVariable::ThreadLocalMode TLM,
854 GlobalVariable::UnnamedAddr UnnamedAddr) {
855 if (!isValidVisibilityForLinkage(Visibility, Linkage))
856 return Error(NameLoc,
857 "symbol with local linkage must have default visibility");
860 bool IsConstant, IsExternallyInitialized;
861 LocTy IsExternallyInitializedLoc;
865 if (ParseOptionalAddrSpace(AddrSpace) ||
866 ParseOptionalToken(lltok::kw_externally_initialized,
867 IsExternallyInitialized,
868 &IsExternallyInitializedLoc) ||
869 ParseGlobalType(IsConstant) ||
870 ParseType(Ty, TyLoc))
873 // If the linkage is specified and is external, then no initializer is
875 Constant *Init = nullptr;
877 !GlobalValue::isValidDeclarationLinkage(
878 (GlobalValue::LinkageTypes)Linkage)) {
879 if (ParseGlobalValue(Ty, Init))
883 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
884 return Error(TyLoc, "invalid type for global variable");
886 GlobalValue *GVal = nullptr;
888 // See if the global was forward referenced, if so, use the global.
890 GVal = M->getNamedValue(Name);
892 if (!ForwardRefVals.erase(Name))
893 return Error(NameLoc, "redefinition of global '@" + Name + "'");
896 auto I = ForwardRefValIDs.find(NumberedVals.size());
897 if (I != ForwardRefValIDs.end()) {
898 GVal = I->second.first;
899 ForwardRefValIDs.erase(I);
905 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
906 Name, nullptr, GlobalVariable::NotThreadLocal,
909 if (GVal->getValueType() != Ty)
911 "forward reference and definition of global have different types");
913 GV = cast<GlobalVariable>(GVal);
915 // Move the forward-reference to the correct spot in the module.
916 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
920 NumberedVals.push_back(GV);
922 // Set the parsed properties on the global.
924 GV->setInitializer(Init);
925 GV->setConstant(IsConstant);
926 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
927 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
928 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
929 GV->setExternallyInitialized(IsExternallyInitialized);
930 GV->setThreadLocalMode(TLM);
931 GV->setUnnamedAddr(UnnamedAddr);
933 // Parse attributes on the global.
934 while (Lex.getKind() == lltok::comma) {
937 if (Lex.getKind() == lltok::kw_section) {
939 GV->setSection(Lex.getStrVal());
940 if (ParseToken(lltok::StringConstant, "expected global section string"))
942 } else if (Lex.getKind() == lltok::kw_align) {
944 if (ParseOptionalAlignment(Alignment)) return true;
945 GV->setAlignment(Alignment);
946 } else if (Lex.getKind() == lltok::MetadataVar) {
947 if (ParseGlobalObjectMetadataAttachment(*GV))
951 if (parseOptionalComdat(Name, C))
956 return TokError("unknown global variable property!");
963 /// ParseUnnamedAttrGrp
964 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
965 bool LLParser::ParseUnnamedAttrGrp() {
966 assert(Lex.getKind() == lltok::kw_attributes);
967 LocTy AttrGrpLoc = Lex.getLoc();
970 if (Lex.getKind() != lltok::AttrGrpID)
971 return TokError("expected attribute group id");
973 unsigned VarID = Lex.getUIntVal();
974 std::vector<unsigned> unused;
978 if (ParseToken(lltok::equal, "expected '=' here") ||
979 ParseToken(lltok::lbrace, "expected '{' here") ||
980 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
982 ParseToken(lltok::rbrace, "expected end of attribute group"))
985 if (!NumberedAttrBuilders[VarID].hasAttributes())
986 return Error(AttrGrpLoc, "attribute group has no attributes");
991 /// ParseFnAttributeValuePairs
992 /// ::= <attr> | <attr> '=' <value>
993 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
994 std::vector<unsigned> &FwdRefAttrGrps,
995 bool inAttrGrp, LocTy &BuiltinLoc) {
996 bool HaveError = false;
1001 lltok::Kind Token = Lex.getKind();
1002 if (Token == lltok::kw_builtin)
1003 BuiltinLoc = Lex.getLoc();
1006 if (!inAttrGrp) return HaveError;
1007 return Error(Lex.getLoc(), "unterminated attribute group");
1012 case lltok::AttrGrpID: {
1013 // Allow a function to reference an attribute group:
1015 // define void @foo() #1 { ... }
1019 "cannot have an attribute group reference in an attribute group");
1021 unsigned AttrGrpNum = Lex.getUIntVal();
1022 if (inAttrGrp) break;
1024 // Save the reference to the attribute group. We'll fill it in later.
1025 FwdRefAttrGrps.push_back(AttrGrpNum);
1028 // Target-dependent attributes:
1029 case lltok::StringConstant: {
1030 if (ParseStringAttribute(B))
1035 // Target-independent attributes:
1036 case lltok::kw_align: {
1037 // As a hack, we allow function alignment to be initially parsed as an
1038 // attribute on a function declaration/definition or added to an attribute
1039 // group and later moved to the alignment field.
1043 if (ParseToken(lltok::equal, "expected '=' here") ||
1044 ParseUInt32(Alignment))
1047 if (ParseOptionalAlignment(Alignment))
1050 B.addAlignmentAttr(Alignment);
1053 case lltok::kw_alignstack: {
1057 if (ParseToken(lltok::equal, "expected '=' here") ||
1058 ParseUInt32(Alignment))
1061 if (ParseOptionalStackAlignment(Alignment))
1064 B.addStackAlignmentAttr(Alignment);
1067 case lltok::kw_allocsize: {
1068 unsigned ElemSizeArg;
1069 Optional<unsigned> NumElemsArg;
1070 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1071 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1073 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1076 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1077 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1078 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1079 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1080 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1081 case lltok::kw_inaccessiblememonly:
1082 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1083 case lltok::kw_inaccessiblemem_or_argmemonly:
1084 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1085 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1086 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1087 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1088 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1089 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1090 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1091 case lltok::kw_noimplicitfloat:
1092 B.addAttribute(Attribute::NoImplicitFloat); break;
1093 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1094 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1095 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1096 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1097 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1098 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1099 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1100 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1101 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1102 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1103 case lltok::kw_returns_twice:
1104 B.addAttribute(Attribute::ReturnsTwice); break;
1105 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1106 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1107 case lltok::kw_sspstrong:
1108 B.addAttribute(Attribute::StackProtectStrong); break;
1109 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1110 case lltok::kw_sanitize_address:
1111 B.addAttribute(Attribute::SanitizeAddress); break;
1112 case lltok::kw_sanitize_thread:
1113 B.addAttribute(Attribute::SanitizeThread); break;
1114 case lltok::kw_sanitize_memory:
1115 B.addAttribute(Attribute::SanitizeMemory); break;
1116 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1117 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1120 case lltok::kw_inreg:
1121 case lltok::kw_signext:
1122 case lltok::kw_zeroext:
1125 "invalid use of attribute on a function");
1127 case lltok::kw_byval:
1128 case lltok::kw_dereferenceable:
1129 case lltok::kw_dereferenceable_or_null:
1130 case lltok::kw_inalloca:
1131 case lltok::kw_nest:
1132 case lltok::kw_noalias:
1133 case lltok::kw_nocapture:
1134 case lltok::kw_nonnull:
1135 case lltok::kw_returned:
1136 case lltok::kw_sret:
1137 case lltok::kw_swifterror:
1138 case lltok::kw_swiftself:
1141 "invalid use of parameter-only attribute on a function");
1149 //===----------------------------------------------------------------------===//
1150 // GlobalValue Reference/Resolution Routines.
1151 //===----------------------------------------------------------------------===//
1153 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1154 const std::string &Name) {
1155 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1156 return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1158 return new GlobalVariable(*M, PTy->getElementType(), false,
1159 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1160 nullptr, GlobalVariable::NotThreadLocal,
1161 PTy->getAddressSpace());
1164 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1165 /// forward reference record if needed. This can return null if the value
1166 /// exists but does not have the right type.
1167 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1169 PointerType *PTy = dyn_cast<PointerType>(Ty);
1171 Error(Loc, "global variable reference must have pointer type");
1175 // Look this name up in the normal function symbol table.
1177 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1179 // If this is a forward reference for the value, see if we already created a
1180 // forward ref record.
1182 auto I = ForwardRefVals.find(Name);
1183 if (I != ForwardRefVals.end())
1184 Val = I->second.first;
1187 // If we have the value in the symbol table or fwd-ref table, return it.
1189 if (Val->getType() == Ty) return Val;
1190 Error(Loc, "'@" + Name + "' defined with type '" +
1191 getTypeString(Val->getType()) + "'");
1195 // Otherwise, create a new forward reference for this value and remember it.
1196 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1197 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1201 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1202 PointerType *PTy = dyn_cast<PointerType>(Ty);
1204 Error(Loc, "global variable reference must have pointer type");
1208 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1210 // If this is a forward reference for the value, see if we already created a
1211 // forward ref record.
1213 auto I = ForwardRefValIDs.find(ID);
1214 if (I != ForwardRefValIDs.end())
1215 Val = I->second.first;
1218 // If we have the value in the symbol table or fwd-ref table, return it.
1220 if (Val->getType() == Ty) return Val;
1221 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1222 getTypeString(Val->getType()) + "'");
1226 // Otherwise, create a new forward reference for this value and remember it.
1227 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1228 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1232 //===----------------------------------------------------------------------===//
1233 // Comdat Reference/Resolution Routines.
1234 //===----------------------------------------------------------------------===//
1236 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1237 // Look this name up in the comdat symbol table.
1238 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1239 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1240 if (I != ComdatSymTab.end())
1243 // Otherwise, create a new forward reference for this value and remember it.
1244 Comdat *C = M->getOrInsertComdat(Name);
1245 ForwardRefComdats[Name] = Loc;
1249 //===----------------------------------------------------------------------===//
1251 //===----------------------------------------------------------------------===//
1253 /// ParseToken - If the current token has the specified kind, eat it and return
1254 /// success. Otherwise, emit the specified error and return failure.
1255 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1256 if (Lex.getKind() != T)
1257 return TokError(ErrMsg);
1262 /// ParseStringConstant
1263 /// ::= StringConstant
1264 bool LLParser::ParseStringConstant(std::string &Result) {
1265 if (Lex.getKind() != lltok::StringConstant)
1266 return TokError("expected string constant");
1267 Result = Lex.getStrVal();
1274 bool LLParser::ParseUInt32(unsigned &Val) {
1275 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1276 return TokError("expected integer");
1277 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1278 if (Val64 != unsigned(Val64))
1279 return TokError("expected 32-bit integer (too large)");
1287 bool LLParser::ParseUInt64(uint64_t &Val) {
1288 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1289 return TokError("expected integer");
1290 Val = Lex.getAPSIntVal().getLimitedValue();
1296 /// := 'localdynamic'
1297 /// := 'initialexec'
1299 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1300 switch (Lex.getKind()) {
1302 return TokError("expected localdynamic, initialexec or localexec");
1303 case lltok::kw_localdynamic:
1304 TLM = GlobalVariable::LocalDynamicTLSModel;
1306 case lltok::kw_initialexec:
1307 TLM = GlobalVariable::InitialExecTLSModel;
1309 case lltok::kw_localexec:
1310 TLM = GlobalVariable::LocalExecTLSModel;
1318 /// ParseOptionalThreadLocal
1320 /// := 'thread_local'
1321 /// := 'thread_local' '(' tlsmodel ')'
1322 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1323 TLM = GlobalVariable::NotThreadLocal;
1324 if (!EatIfPresent(lltok::kw_thread_local))
1327 TLM = GlobalVariable::GeneralDynamicTLSModel;
1328 if (Lex.getKind() == lltok::lparen) {
1330 return ParseTLSModel(TLM) ||
1331 ParseToken(lltok::rparen, "expected ')' after thread local model");
1336 /// ParseOptionalAddrSpace
1338 /// := 'addrspace' '(' uint32 ')'
1339 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1341 if (!EatIfPresent(lltok::kw_addrspace))
1343 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1344 ParseUInt32(AddrSpace) ||
1345 ParseToken(lltok::rparen, "expected ')' in address space");
1348 /// ParseStringAttribute
1349 /// := StringConstant
1350 /// := StringConstant '=' StringConstant
1351 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1352 std::string Attr = Lex.getStrVal();
1355 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1357 B.addAttribute(Attr, Val);
1361 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1362 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1363 bool HaveError = false;
1368 lltok::Kind Token = Lex.getKind();
1370 default: // End of attributes.
1372 case lltok::StringConstant: {
1373 if (ParseStringAttribute(B))
1377 case lltok::kw_align: {
1379 if (ParseOptionalAlignment(Alignment))
1381 B.addAlignmentAttr(Alignment);
1384 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1385 case lltok::kw_dereferenceable: {
1387 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1389 B.addDereferenceableAttr(Bytes);
1392 case lltok::kw_dereferenceable_or_null: {
1394 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1396 B.addDereferenceableOrNullAttr(Bytes);
1399 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1400 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1401 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1402 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1403 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1404 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1405 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1406 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1407 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1408 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1409 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1410 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1411 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1412 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1413 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1415 case lltok::kw_alignstack:
1416 case lltok::kw_alwaysinline:
1417 case lltok::kw_argmemonly:
1418 case lltok::kw_builtin:
1419 case lltok::kw_inlinehint:
1420 case lltok::kw_jumptable:
1421 case lltok::kw_minsize:
1422 case lltok::kw_naked:
1423 case lltok::kw_nobuiltin:
1424 case lltok::kw_noduplicate:
1425 case lltok::kw_noimplicitfloat:
1426 case lltok::kw_noinline:
1427 case lltok::kw_nonlazybind:
1428 case lltok::kw_noredzone:
1429 case lltok::kw_noreturn:
1430 case lltok::kw_nounwind:
1431 case lltok::kw_optnone:
1432 case lltok::kw_optsize:
1433 case lltok::kw_returns_twice:
1434 case lltok::kw_sanitize_address:
1435 case lltok::kw_sanitize_memory:
1436 case lltok::kw_sanitize_thread:
1438 case lltok::kw_sspreq:
1439 case lltok::kw_sspstrong:
1440 case lltok::kw_safestack:
1441 case lltok::kw_uwtable:
1442 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1450 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1451 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1452 bool HaveError = false;
1457 lltok::Kind Token = Lex.getKind();
1459 default: // End of attributes.
1461 case lltok::StringConstant: {
1462 if (ParseStringAttribute(B))
1466 case lltok::kw_dereferenceable: {
1468 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1470 B.addDereferenceableAttr(Bytes);
1473 case lltok::kw_dereferenceable_or_null: {
1475 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1477 B.addDereferenceableOrNullAttr(Bytes);
1480 case lltok::kw_align: {
1482 if (ParseOptionalAlignment(Alignment))
1484 B.addAlignmentAttr(Alignment);
1487 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1488 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1489 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1490 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1491 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1494 case lltok::kw_byval:
1495 case lltok::kw_inalloca:
1496 case lltok::kw_nest:
1497 case lltok::kw_nocapture:
1498 case lltok::kw_returned:
1499 case lltok::kw_sret:
1500 case lltok::kw_swifterror:
1501 case lltok::kw_swiftself:
1502 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1505 case lltok::kw_alignstack:
1506 case lltok::kw_alwaysinline:
1507 case lltok::kw_argmemonly:
1508 case lltok::kw_builtin:
1509 case lltok::kw_cold:
1510 case lltok::kw_inlinehint:
1511 case lltok::kw_jumptable:
1512 case lltok::kw_minsize:
1513 case lltok::kw_naked:
1514 case lltok::kw_nobuiltin:
1515 case lltok::kw_noduplicate:
1516 case lltok::kw_noimplicitfloat:
1517 case lltok::kw_noinline:
1518 case lltok::kw_nonlazybind:
1519 case lltok::kw_noredzone:
1520 case lltok::kw_noreturn:
1521 case lltok::kw_nounwind:
1522 case lltok::kw_optnone:
1523 case lltok::kw_optsize:
1524 case lltok::kw_returns_twice:
1525 case lltok::kw_sanitize_address:
1526 case lltok::kw_sanitize_memory:
1527 case lltok::kw_sanitize_thread:
1529 case lltok::kw_sspreq:
1530 case lltok::kw_sspstrong:
1531 case lltok::kw_safestack:
1532 case lltok::kw_uwtable:
1533 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1536 case lltok::kw_readnone:
1537 case lltok::kw_readonly:
1538 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1545 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1550 return GlobalValue::ExternalLinkage;
1551 case lltok::kw_private:
1552 return GlobalValue::PrivateLinkage;
1553 case lltok::kw_internal:
1554 return GlobalValue::InternalLinkage;
1555 case lltok::kw_weak:
1556 return GlobalValue::WeakAnyLinkage;
1557 case lltok::kw_weak_odr:
1558 return GlobalValue::WeakODRLinkage;
1559 case lltok::kw_linkonce:
1560 return GlobalValue::LinkOnceAnyLinkage;
1561 case lltok::kw_linkonce_odr:
1562 return GlobalValue::LinkOnceODRLinkage;
1563 case lltok::kw_available_externally:
1564 return GlobalValue::AvailableExternallyLinkage;
1565 case lltok::kw_appending:
1566 return GlobalValue::AppendingLinkage;
1567 case lltok::kw_common:
1568 return GlobalValue::CommonLinkage;
1569 case lltok::kw_extern_weak:
1570 return GlobalValue::ExternalWeakLinkage;
1571 case lltok::kw_external:
1572 return GlobalValue::ExternalLinkage;
1576 /// ParseOptionalLinkage
1583 /// ::= 'linkonce_odr'
1584 /// ::= 'available_externally'
1587 /// ::= 'extern_weak'
1589 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1590 unsigned &Visibility,
1591 unsigned &DLLStorageClass) {
1592 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1595 ParseOptionalVisibility(Visibility);
1596 ParseOptionalDLLStorageClass(DLLStorageClass);
1600 /// ParseOptionalVisibility
1606 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1607 switch (Lex.getKind()) {
1609 Res = GlobalValue::DefaultVisibility;
1611 case lltok::kw_default:
1612 Res = GlobalValue::DefaultVisibility;
1614 case lltok::kw_hidden:
1615 Res = GlobalValue::HiddenVisibility;
1617 case lltok::kw_protected:
1618 Res = GlobalValue::ProtectedVisibility;
1624 /// ParseOptionalDLLStorageClass
1629 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1630 switch (Lex.getKind()) {
1632 Res = GlobalValue::DefaultStorageClass;
1634 case lltok::kw_dllimport:
1635 Res = GlobalValue::DLLImportStorageClass;
1637 case lltok::kw_dllexport:
1638 Res = GlobalValue::DLLExportStorageClass;
1644 /// ParseOptionalCallingConv
1648 /// ::= 'intel_ocl_bicc'
1650 /// ::= 'x86_stdcallcc'
1651 /// ::= 'x86_fastcallcc'
1652 /// ::= 'x86_thiscallcc'
1653 /// ::= 'x86_vectorcallcc'
1654 /// ::= 'arm_apcscc'
1655 /// ::= 'arm_aapcscc'
1656 /// ::= 'arm_aapcs_vfpcc'
1657 /// ::= 'msp430_intrcc'
1658 /// ::= 'avr_intrcc'
1659 /// ::= 'avr_signalcc'
1660 /// ::= 'ptx_kernel'
1661 /// ::= 'ptx_device'
1663 /// ::= 'spir_kernel'
1664 /// ::= 'x86_64_sysvcc'
1665 /// ::= 'x86_64_win64cc'
1666 /// ::= 'webkit_jscc'
1668 /// ::= 'preserve_mostcc'
1669 /// ::= 'preserve_allcc'
1672 /// ::= 'x86_intrcc'
1675 /// ::= 'cxx_fast_tlscc'
1677 /// ::= 'amdgpu_tcs'
1678 /// ::= 'amdgpu_tes'
1682 /// ::= 'amdgpu_kernel'
1685 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1686 switch (Lex.getKind()) {
1687 default: CC = CallingConv::C; return false;
1688 case lltok::kw_ccc: CC = CallingConv::C; break;
1689 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1690 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1691 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1692 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1693 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1694 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1695 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1696 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1697 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1698 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1699 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1700 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1701 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1702 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1703 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1704 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1705 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1706 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1707 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1708 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1709 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1710 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1711 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1712 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1713 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1714 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1715 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1716 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1717 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1718 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1719 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1720 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1721 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1722 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1723 case lltok::kw_cc: {
1725 return ParseUInt32(CC);
1733 /// ParseMetadataAttachment
1735 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1736 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1738 std::string Name = Lex.getStrVal();
1739 Kind = M->getMDKindID(Name);
1742 return ParseMDNode(MD);
1745 /// ParseInstructionMetadata
1746 /// ::= !dbg !42 (',' !dbg !57)*
1747 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1749 if (Lex.getKind() != lltok::MetadataVar)
1750 return TokError("expected metadata after comma");
1754 if (ParseMetadataAttachment(MDK, N))
1757 Inst.setMetadata(MDK, N);
1758 if (MDK == LLVMContext::MD_tbaa)
1759 InstsWithTBAATag.push_back(&Inst);
1761 // If this is the end of the list, we're done.
1762 } while (EatIfPresent(lltok::comma));
1766 /// ParseGlobalObjectMetadataAttachment
1768 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
1771 if (ParseMetadataAttachment(MDK, N))
1774 GO.addMetadata(MDK, *N);
1778 /// ParseOptionalFunctionMetadata
1780 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1781 while (Lex.getKind() == lltok::MetadataVar)
1782 if (ParseGlobalObjectMetadataAttachment(F))
1787 /// ParseOptionalAlignment
1790 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1792 if (!EatIfPresent(lltok::kw_align))
1794 LocTy AlignLoc = Lex.getLoc();
1795 if (ParseUInt32(Alignment)) return true;
1796 if (!isPowerOf2_32(Alignment))
1797 return Error(AlignLoc, "alignment is not a power of two");
1798 if (Alignment > Value::MaximumAlignment)
1799 return Error(AlignLoc, "huge alignments are not supported yet");
1803 /// ParseOptionalDerefAttrBytes
1805 /// ::= AttrKind '(' 4 ')'
1807 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1808 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1810 assert((AttrKind == lltok::kw_dereferenceable ||
1811 AttrKind == lltok::kw_dereferenceable_or_null) &&
1815 if (!EatIfPresent(AttrKind))
1817 LocTy ParenLoc = Lex.getLoc();
1818 if (!EatIfPresent(lltok::lparen))
1819 return Error(ParenLoc, "expected '('");
1820 LocTy DerefLoc = Lex.getLoc();
1821 if (ParseUInt64(Bytes)) return true;
1822 ParenLoc = Lex.getLoc();
1823 if (!EatIfPresent(lltok::rparen))
1824 return Error(ParenLoc, "expected ')'");
1826 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1830 /// ParseOptionalCommaAlign
1834 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1836 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1837 bool &AteExtraComma) {
1838 AteExtraComma = false;
1839 while (EatIfPresent(lltok::comma)) {
1840 // Metadata at the end is an early exit.
1841 if (Lex.getKind() == lltok::MetadataVar) {
1842 AteExtraComma = true;
1846 if (Lex.getKind() != lltok::kw_align)
1847 return Error(Lex.getLoc(), "expected metadata or 'align'");
1849 if (ParseOptionalAlignment(Alignment)) return true;
1855 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
1856 Optional<unsigned> &HowManyArg) {
1859 auto StartParen = Lex.getLoc();
1860 if (!EatIfPresent(lltok::lparen))
1861 return Error(StartParen, "expected '('");
1863 if (ParseUInt32(BaseSizeArg))
1866 if (EatIfPresent(lltok::comma)) {
1867 auto HowManyAt = Lex.getLoc();
1869 if (ParseUInt32(HowMany))
1871 if (HowMany == BaseSizeArg)
1872 return Error(HowManyAt,
1873 "'allocsize' indices can't refer to the same parameter");
1874 HowManyArg = HowMany;
1878 auto EndParen = Lex.getLoc();
1879 if (!EatIfPresent(lltok::rparen))
1880 return Error(EndParen, "expected ')'");
1884 /// ParseScopeAndOrdering
1885 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1888 /// This sets Scope and Ordering to the parsed values.
1889 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1890 AtomicOrdering &Ordering) {
1894 Scope = CrossThread;
1895 if (EatIfPresent(lltok::kw_singlethread))
1896 Scope = SingleThread;
1898 return ParseOrdering(Ordering);
1902 /// ::= AtomicOrdering
1904 /// This sets Ordering to the parsed value.
1905 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1906 switch (Lex.getKind()) {
1907 default: return TokError("Expected ordering on atomic instruction");
1908 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
1909 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
1910 // Not specified yet:
1911 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
1912 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
1913 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
1914 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
1915 case lltok::kw_seq_cst:
1916 Ordering = AtomicOrdering::SequentiallyConsistent;
1923 /// ParseOptionalStackAlignment
1925 /// ::= 'alignstack' '(' 4 ')'
1926 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1928 if (!EatIfPresent(lltok::kw_alignstack))
1930 LocTy ParenLoc = Lex.getLoc();
1931 if (!EatIfPresent(lltok::lparen))
1932 return Error(ParenLoc, "expected '('");
1933 LocTy AlignLoc = Lex.getLoc();
1934 if (ParseUInt32(Alignment)) return true;
1935 ParenLoc = Lex.getLoc();
1936 if (!EatIfPresent(lltok::rparen))
1937 return Error(ParenLoc, "expected ')'");
1938 if (!isPowerOf2_32(Alignment))
1939 return Error(AlignLoc, "stack alignment is not a power of two");
1943 /// ParseIndexList - This parses the index list for an insert/extractvalue
1944 /// instruction. This sets AteExtraComma in the case where we eat an extra
1945 /// comma at the end of the line and find that it is followed by metadata.
1946 /// Clients that don't allow metadata can call the version of this function that
1947 /// only takes one argument.
1950 /// ::= (',' uint32)+
1952 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1953 bool &AteExtraComma) {
1954 AteExtraComma = false;
1956 if (Lex.getKind() != lltok::comma)
1957 return TokError("expected ',' as start of index list");
1959 while (EatIfPresent(lltok::comma)) {
1960 if (Lex.getKind() == lltok::MetadataVar) {
1961 if (Indices.empty()) return TokError("expected index");
1962 AteExtraComma = true;
1966 if (ParseUInt32(Idx)) return true;
1967 Indices.push_back(Idx);
1973 //===----------------------------------------------------------------------===//
1975 //===----------------------------------------------------------------------===//
1977 /// ParseType - Parse a type.
1978 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1979 SMLoc TypeLoc = Lex.getLoc();
1980 switch (Lex.getKind()) {
1982 return TokError(Msg);
1984 // Type ::= 'float' | 'void' (etc)
1985 Result = Lex.getTyVal();
1989 // Type ::= StructType
1990 if (ParseAnonStructType(Result, false))
1993 case lltok::lsquare:
1994 // Type ::= '[' ... ']'
1995 Lex.Lex(); // eat the lsquare.
1996 if (ParseArrayVectorType(Result, false))
1999 case lltok::less: // Either vector or packed struct.
2000 // Type ::= '<' ... '>'
2002 if (Lex.getKind() == lltok::lbrace) {
2003 if (ParseAnonStructType(Result, true) ||
2004 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2006 } else if (ParseArrayVectorType(Result, true))
2009 case lltok::LocalVar: {
2011 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2013 // If the type hasn't been defined yet, create a forward definition and
2014 // remember where that forward def'n was seen (in case it never is defined).
2016 Entry.first = StructType::create(Context, Lex.getStrVal());
2017 Entry.second = Lex.getLoc();
2019 Result = Entry.first;
2024 case lltok::LocalVarID: {
2026 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2028 // If the type hasn't been defined yet, create a forward definition and
2029 // remember where that forward def'n was seen (in case it never is defined).
2031 Entry.first = StructType::create(Context);
2032 Entry.second = Lex.getLoc();
2034 Result = Entry.first;
2040 // Parse the type suffixes.
2042 switch (Lex.getKind()) {
2045 if (!AllowVoid && Result->isVoidTy())
2046 return Error(TypeLoc, "void type only allowed for function results");
2049 // Type ::= Type '*'
2051 if (Result->isLabelTy())
2052 return TokError("basic block pointers are invalid");
2053 if (Result->isVoidTy())
2054 return TokError("pointers to void are invalid - use i8* instead");
2055 if (!PointerType::isValidElementType(Result))
2056 return TokError("pointer to this type is invalid");
2057 Result = PointerType::getUnqual(Result);
2061 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2062 case lltok::kw_addrspace: {
2063 if (Result->isLabelTy())
2064 return TokError("basic block pointers are invalid");
2065 if (Result->isVoidTy())
2066 return TokError("pointers to void are invalid; use i8* instead");
2067 if (!PointerType::isValidElementType(Result))
2068 return TokError("pointer to this type is invalid");
2070 if (ParseOptionalAddrSpace(AddrSpace) ||
2071 ParseToken(lltok::star, "expected '*' in address space"))
2074 Result = PointerType::get(Result, AddrSpace);
2078 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2080 if (ParseFunctionType(Result))
2087 /// ParseParameterList
2089 /// ::= '(' Arg (',' Arg)* ')'
2091 /// ::= Type OptionalAttributes Value OptionalAttributes
2092 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2093 PerFunctionState &PFS, bool IsMustTailCall,
2094 bool InVarArgsFunc) {
2095 if (ParseToken(lltok::lparen, "expected '(' in call"))
2098 unsigned AttrIndex = 1;
2099 while (Lex.getKind() != lltok::rparen) {
2100 // If this isn't the first argument, we need a comma.
2101 if (!ArgList.empty() &&
2102 ParseToken(lltok::comma, "expected ',' in argument list"))
2105 // Parse an ellipsis if this is a musttail call in a variadic function.
2106 if (Lex.getKind() == lltok::dotdotdot) {
2107 const char *Msg = "unexpected ellipsis in argument list for ";
2108 if (!IsMustTailCall)
2109 return TokError(Twine(Msg) + "non-musttail call");
2111 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2112 Lex.Lex(); // Lex the '...', it is purely for readability.
2113 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2116 // Parse the argument.
2118 Type *ArgTy = nullptr;
2119 AttrBuilder ArgAttrs;
2121 if (ParseType(ArgTy, ArgLoc))
2124 if (ArgTy->isMetadataTy()) {
2125 if (ParseMetadataAsValue(V, PFS))
2128 // Otherwise, handle normal operands.
2129 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2132 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
2137 if (IsMustTailCall && InVarArgsFunc)
2138 return TokError("expected '...' at end of argument list for musttail call "
2139 "in varargs function");
2141 Lex.Lex(); // Lex the ')'.
2145 /// ParseOptionalOperandBundles
2147 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2150 /// ::= bundle-tag '(' ')'
2151 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2153 /// bundle-tag ::= String Constant
2154 bool LLParser::ParseOptionalOperandBundles(
2155 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2156 LocTy BeginLoc = Lex.getLoc();
2157 if (!EatIfPresent(lltok::lsquare))
2160 while (Lex.getKind() != lltok::rsquare) {
2161 // If this isn't the first operand bundle, we need a comma.
2162 if (!BundleList.empty() &&
2163 ParseToken(lltok::comma, "expected ',' in input list"))
2167 if (ParseStringConstant(Tag))
2170 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2173 std::vector<Value *> Inputs;
2174 while (Lex.getKind() != lltok::rparen) {
2175 // If this isn't the first input, we need a comma.
2176 if (!Inputs.empty() &&
2177 ParseToken(lltok::comma, "expected ',' in input list"))
2181 Value *Input = nullptr;
2182 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2184 Inputs.push_back(Input);
2187 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2189 Lex.Lex(); // Lex the ')'.
2192 if (BundleList.empty())
2193 return Error(BeginLoc, "operand bundle set must not be empty");
2195 Lex.Lex(); // Lex the ']'.
2199 /// ParseArgumentList - Parse the argument list for a function type or function
2201 /// ::= '(' ArgTypeListI ')'
2205 /// ::= ArgTypeList ',' '...'
2206 /// ::= ArgType (',' ArgType)*
2208 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2211 assert(Lex.getKind() == lltok::lparen);
2212 Lex.Lex(); // eat the (.
2214 if (Lex.getKind() == lltok::rparen) {
2216 } else if (Lex.getKind() == lltok::dotdotdot) {
2220 LocTy TypeLoc = Lex.getLoc();
2221 Type *ArgTy = nullptr;
2225 if (ParseType(ArgTy) ||
2226 ParseOptionalParamAttrs(Attrs)) return true;
2228 if (ArgTy->isVoidTy())
2229 return Error(TypeLoc, "argument can not have void type");
2231 if (Lex.getKind() == lltok::LocalVar) {
2232 Name = Lex.getStrVal();
2236 if (!FunctionType::isValidArgumentType(ArgTy))
2237 return Error(TypeLoc, "invalid type for function argument");
2239 unsigned AttrIndex = 1;
2240 ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
2241 AttrIndex++, Attrs),
2244 while (EatIfPresent(lltok::comma)) {
2245 // Handle ... at end of arg list.
2246 if (EatIfPresent(lltok::dotdotdot)) {
2251 // Otherwise must be an argument type.
2252 TypeLoc = Lex.getLoc();
2253 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2255 if (ArgTy->isVoidTy())
2256 return Error(TypeLoc, "argument can not have void type");
2258 if (Lex.getKind() == lltok::LocalVar) {
2259 Name = Lex.getStrVal();
2265 if (!ArgTy->isFirstClassType())
2266 return Error(TypeLoc, "invalid type for function argument");
2268 ArgList.emplace_back(
2270 AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
2275 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2278 /// ParseFunctionType
2279 /// ::= Type ArgumentList OptionalAttrs
2280 bool LLParser::ParseFunctionType(Type *&Result) {
2281 assert(Lex.getKind() == lltok::lparen);
2283 if (!FunctionType::isValidReturnType(Result))
2284 return TokError("invalid function return type");
2286 SmallVector<ArgInfo, 8> ArgList;
2288 if (ParseArgumentList(ArgList, isVarArg))
2291 // Reject names on the arguments lists.
2292 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2293 if (!ArgList[i].Name.empty())
2294 return Error(ArgList[i].Loc, "argument name invalid in function type");
2295 if (ArgList[i].Attrs.hasAttributes(i + 1))
2296 return Error(ArgList[i].Loc,
2297 "argument attributes invalid in function type");
2300 SmallVector<Type*, 16> ArgListTy;
2301 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2302 ArgListTy.push_back(ArgList[i].Ty);
2304 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2308 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2310 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2311 SmallVector<Type*, 8> Elts;
2312 if (ParseStructBody(Elts)) return true;
2314 Result = StructType::get(Context, Elts, Packed);
2318 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2319 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2320 std::pair<Type*, LocTy> &Entry,
2322 // If the type was already defined, diagnose the redefinition.
2323 if (Entry.first && !Entry.second.isValid())
2324 return Error(TypeLoc, "redefinition of type");
2326 // If we have opaque, just return without filling in the definition for the
2327 // struct. This counts as a definition as far as the .ll file goes.
2328 if (EatIfPresent(lltok::kw_opaque)) {
2329 // This type is being defined, so clear the location to indicate this.
2330 Entry.second = SMLoc();
2332 // If this type number has never been uttered, create it.
2334 Entry.first = StructType::create(Context, Name);
2335 ResultTy = Entry.first;
2339 // If the type starts with '<', then it is either a packed struct or a vector.
2340 bool isPacked = EatIfPresent(lltok::less);
2342 // If we don't have a struct, then we have a random type alias, which we
2343 // accept for compatibility with old files. These types are not allowed to be
2344 // forward referenced and not allowed to be recursive.
2345 if (Lex.getKind() != lltok::lbrace) {
2347 return Error(TypeLoc, "forward references to non-struct type");
2351 return ParseArrayVectorType(ResultTy, true);
2352 return ParseType(ResultTy);
2355 // This type is being defined, so clear the location to indicate this.
2356 Entry.second = SMLoc();
2358 // If this type number has never been uttered, create it.
2360 Entry.first = StructType::create(Context, Name);
2362 StructType *STy = cast<StructType>(Entry.first);
2364 SmallVector<Type*, 8> Body;
2365 if (ParseStructBody(Body) ||
2366 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2369 STy->setBody(Body, isPacked);
2374 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2377 /// ::= '{' Type (',' Type)* '}'
2378 /// ::= '<' '{' '}' '>'
2379 /// ::= '<' '{' Type (',' Type)* '}' '>'
2380 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2381 assert(Lex.getKind() == lltok::lbrace);
2382 Lex.Lex(); // Consume the '{'
2384 // Handle the empty struct.
2385 if (EatIfPresent(lltok::rbrace))
2388 LocTy EltTyLoc = Lex.getLoc();
2390 if (ParseType(Ty)) return true;
2393 if (!StructType::isValidElementType(Ty))
2394 return Error(EltTyLoc, "invalid element type for struct");
2396 while (EatIfPresent(lltok::comma)) {
2397 EltTyLoc = Lex.getLoc();
2398 if (ParseType(Ty)) return true;
2400 if (!StructType::isValidElementType(Ty))
2401 return Error(EltTyLoc, "invalid element type for struct");
2406 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2409 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2410 /// token has already been consumed.
2412 /// ::= '[' APSINTVAL 'x' Types ']'
2413 /// ::= '<' APSINTVAL 'x' Types '>'
2414 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2415 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2416 Lex.getAPSIntVal().getBitWidth() > 64)
2417 return TokError("expected number in address space");
2419 LocTy SizeLoc = Lex.getLoc();
2420 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2423 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2426 LocTy TypeLoc = Lex.getLoc();
2427 Type *EltTy = nullptr;
2428 if (ParseType(EltTy)) return true;
2430 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2431 "expected end of sequential type"))
2436 return Error(SizeLoc, "zero element vector is illegal");
2437 if ((unsigned)Size != Size)
2438 return Error(SizeLoc, "size too large for vector");
2439 if (!VectorType::isValidElementType(EltTy))
2440 return Error(TypeLoc, "invalid vector element type");
2441 Result = VectorType::get(EltTy, unsigned(Size));
2443 if (!ArrayType::isValidElementType(EltTy))
2444 return Error(TypeLoc, "invalid array element type");
2445 Result = ArrayType::get(EltTy, Size);
2450 //===----------------------------------------------------------------------===//
2451 // Function Semantic Analysis.
2452 //===----------------------------------------------------------------------===//
2454 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2456 : P(p), F(f), FunctionNumber(functionNumber) {
2458 // Insert unnamed arguments into the NumberedVals list.
2459 for (Argument &A : F.args())
2461 NumberedVals.push_back(&A);
2464 LLParser::PerFunctionState::~PerFunctionState() {
2465 // If there were any forward referenced non-basicblock values, delete them.
2467 for (const auto &P : ForwardRefVals) {
2468 if (isa<BasicBlock>(P.second.first))
2470 P.second.first->replaceAllUsesWith(
2471 UndefValue::get(P.second.first->getType()));
2472 delete P.second.first;
2475 for (const auto &P : ForwardRefValIDs) {
2476 if (isa<BasicBlock>(P.second.first))
2478 P.second.first->replaceAllUsesWith(
2479 UndefValue::get(P.second.first->getType()));
2480 delete P.second.first;
2484 bool LLParser::PerFunctionState::FinishFunction() {
2485 if (!ForwardRefVals.empty())
2486 return P.Error(ForwardRefVals.begin()->second.second,
2487 "use of undefined value '%" + ForwardRefVals.begin()->first +
2489 if (!ForwardRefValIDs.empty())
2490 return P.Error(ForwardRefValIDs.begin()->second.second,
2491 "use of undefined value '%" +
2492 Twine(ForwardRefValIDs.begin()->first) + "'");
2496 /// GetVal - Get a value with the specified name or ID, creating a
2497 /// forward reference record if needed. This can return null if the value
2498 /// exists but does not have the right type.
2499 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2501 // Look this name up in the normal function symbol table.
2502 Value *Val = F.getValueSymbolTable().lookup(Name);
2504 // If this is a forward reference for the value, see if we already created a
2505 // forward ref record.
2507 auto I = ForwardRefVals.find(Name);
2508 if (I != ForwardRefVals.end())
2509 Val = I->second.first;
2512 // If we have the value in the symbol table or fwd-ref table, return it.
2514 if (Val->getType() == Ty) return Val;
2515 if (Ty->isLabelTy())
2516 P.Error(Loc, "'%" + Name + "' is not a basic block");
2518 P.Error(Loc, "'%" + Name + "' defined with type '" +
2519 getTypeString(Val->getType()) + "'");
2523 // Don't make placeholders with invalid type.
2524 if (!Ty->isFirstClassType()) {
2525 P.Error(Loc, "invalid use of a non-first-class type");
2529 // Otherwise, create a new forward reference for this value and remember it.
2531 if (Ty->isLabelTy()) {
2532 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2534 FwdVal = new Argument(Ty, Name);
2537 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2541 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
2542 // Look this name up in the normal function symbol table.
2543 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2545 // If this is a forward reference for the value, see if we already created a
2546 // forward ref record.
2548 auto I = ForwardRefValIDs.find(ID);
2549 if (I != ForwardRefValIDs.end())
2550 Val = I->second.first;
2553 // If we have the value in the symbol table or fwd-ref table, return it.
2555 if (Val->getType() == Ty) return Val;
2556 if (Ty->isLabelTy())
2557 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2559 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2560 getTypeString(Val->getType()) + "'");
2564 if (!Ty->isFirstClassType()) {
2565 P.Error(Loc, "invalid use of a non-first-class type");
2569 // Otherwise, create a new forward reference for this value and remember it.
2571 if (Ty->isLabelTy()) {
2572 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2574 FwdVal = new Argument(Ty);
2577 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2581 /// SetInstName - After an instruction is parsed and inserted into its
2582 /// basic block, this installs its name.
2583 bool LLParser::PerFunctionState::SetInstName(int NameID,
2584 const std::string &NameStr,
2585 LocTy NameLoc, Instruction *Inst) {
2586 // If this instruction has void type, it cannot have a name or ID specified.
2587 if (Inst->getType()->isVoidTy()) {
2588 if (NameID != -1 || !NameStr.empty())
2589 return P.Error(NameLoc, "instructions returning void cannot have a name");
2593 // If this was a numbered instruction, verify that the instruction is the
2594 // expected value and resolve any forward references.
2595 if (NameStr.empty()) {
2596 // If neither a name nor an ID was specified, just use the next ID.
2598 NameID = NumberedVals.size();
2600 if (unsigned(NameID) != NumberedVals.size())
2601 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2602 Twine(NumberedVals.size()) + "'");
2604 auto FI = ForwardRefValIDs.find(NameID);
2605 if (FI != ForwardRefValIDs.end()) {
2606 Value *Sentinel = FI->second.first;
2607 if (Sentinel->getType() != Inst->getType())
2608 return P.Error(NameLoc, "instruction forward referenced with type '" +
2609 getTypeString(FI->second.first->getType()) + "'");
2611 Sentinel->replaceAllUsesWith(Inst);
2613 ForwardRefValIDs.erase(FI);
2616 NumberedVals.push_back(Inst);
2620 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2621 auto FI = ForwardRefVals.find(NameStr);
2622 if (FI != ForwardRefVals.end()) {
2623 Value *Sentinel = FI->second.first;
2624 if (Sentinel->getType() != Inst->getType())
2625 return P.Error(NameLoc, "instruction forward referenced with type '" +
2626 getTypeString(FI->second.first->getType()) + "'");
2628 Sentinel->replaceAllUsesWith(Inst);
2630 ForwardRefVals.erase(FI);
2633 // Set the name on the instruction.
2634 Inst->setName(NameStr);
2636 if (Inst->getName() != NameStr)
2637 return P.Error(NameLoc, "multiple definition of local value named '" +
2642 /// GetBB - Get a basic block with the specified name or ID, creating a
2643 /// forward reference record if needed.
2644 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2646 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2647 Type::getLabelTy(F.getContext()), Loc));
2650 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2651 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2652 Type::getLabelTy(F.getContext()), Loc));
2655 /// DefineBB - Define the specified basic block, which is either named or
2656 /// unnamed. If there is an error, this returns null otherwise it returns
2657 /// the block being defined.
2658 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2662 BB = GetBB(NumberedVals.size(), Loc);
2664 BB = GetBB(Name, Loc);
2665 if (!BB) return nullptr; // Already diagnosed error.
2667 // Move the block to the end of the function. Forward ref'd blocks are
2668 // inserted wherever they happen to be referenced.
2669 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2671 // Remove the block from forward ref sets.
2673 ForwardRefValIDs.erase(NumberedVals.size());
2674 NumberedVals.push_back(BB);
2676 // BB forward references are already in the function symbol table.
2677 ForwardRefVals.erase(Name);
2683 //===----------------------------------------------------------------------===//
2685 //===----------------------------------------------------------------------===//
2687 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2688 /// type implied. For example, if we parse "4" we don't know what integer type
2689 /// it has. The value will later be combined with its type and checked for
2690 /// sanity. PFS is used to convert function-local operands of metadata (since
2691 /// metadata operands are not just parsed here but also converted to values).
2692 /// PFS can be null when we are not parsing metadata values inside a function.
2693 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2694 ID.Loc = Lex.getLoc();
2695 switch (Lex.getKind()) {
2696 default: return TokError("expected value token");
2697 case lltok::GlobalID: // @42
2698 ID.UIntVal = Lex.getUIntVal();
2699 ID.Kind = ValID::t_GlobalID;
2701 case lltok::GlobalVar: // @foo
2702 ID.StrVal = Lex.getStrVal();
2703 ID.Kind = ValID::t_GlobalName;
2705 case lltok::LocalVarID: // %42
2706 ID.UIntVal = Lex.getUIntVal();
2707 ID.Kind = ValID::t_LocalID;
2709 case lltok::LocalVar: // %foo
2710 ID.StrVal = Lex.getStrVal();
2711 ID.Kind = ValID::t_LocalName;
2714 ID.APSIntVal = Lex.getAPSIntVal();
2715 ID.Kind = ValID::t_APSInt;
2717 case lltok::APFloat:
2718 ID.APFloatVal = Lex.getAPFloatVal();
2719 ID.Kind = ValID::t_APFloat;
2721 case lltok::kw_true:
2722 ID.ConstantVal = ConstantInt::getTrue(Context);
2723 ID.Kind = ValID::t_Constant;
2725 case lltok::kw_false:
2726 ID.ConstantVal = ConstantInt::getFalse(Context);
2727 ID.Kind = ValID::t_Constant;
2729 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2730 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2731 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2732 case lltok::kw_none: ID.Kind = ValID::t_None; break;
2734 case lltok::lbrace: {
2735 // ValID ::= '{' ConstVector '}'
2737 SmallVector<Constant*, 16> Elts;
2738 if (ParseGlobalValueVector(Elts) ||
2739 ParseToken(lltok::rbrace, "expected end of struct constant"))
2742 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2743 ID.UIntVal = Elts.size();
2744 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2745 Elts.size() * sizeof(Elts[0]));
2746 ID.Kind = ValID::t_ConstantStruct;
2750 // ValID ::= '<' ConstVector '>' --> Vector.
2751 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2753 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2755 SmallVector<Constant*, 16> Elts;
2756 LocTy FirstEltLoc = Lex.getLoc();
2757 if (ParseGlobalValueVector(Elts) ||
2759 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2760 ParseToken(lltok::greater, "expected end of constant"))
2763 if (isPackedStruct) {
2764 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
2765 memcpy(ID.ConstantStructElts.get(), Elts.data(),
2766 Elts.size() * sizeof(Elts[0]));
2767 ID.UIntVal = Elts.size();
2768 ID.Kind = ValID::t_PackedConstantStruct;
2773 return Error(ID.Loc, "constant vector must not be empty");
2775 if (!Elts[0]->getType()->isIntegerTy() &&
2776 !Elts[0]->getType()->isFloatingPointTy() &&
2777 !Elts[0]->getType()->isPointerTy())
2778 return Error(FirstEltLoc,
2779 "vector elements must have integer, pointer or floating point type");
2781 // Verify that all the vector elements have the same type.
2782 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2783 if (Elts[i]->getType() != Elts[0]->getType())
2784 return Error(FirstEltLoc,
2785 "vector element #" + Twine(i) +
2786 " is not of type '" + getTypeString(Elts[0]->getType()));
2788 ID.ConstantVal = ConstantVector::get(Elts);
2789 ID.Kind = ValID::t_Constant;
2792 case lltok::lsquare: { // Array Constant
2794 SmallVector<Constant*, 16> Elts;
2795 LocTy FirstEltLoc = Lex.getLoc();
2796 if (ParseGlobalValueVector(Elts) ||
2797 ParseToken(lltok::rsquare, "expected end of array constant"))
2800 // Handle empty element.
2802 // Use undef instead of an array because it's inconvenient to determine
2803 // the element type at this point, there being no elements to examine.
2804 ID.Kind = ValID::t_EmptyArray;
2808 if (!Elts[0]->getType()->isFirstClassType())
2809 return Error(FirstEltLoc, "invalid array element type: " +
2810 getTypeString(Elts[0]->getType()));
2812 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2814 // Verify all elements are correct type!
2815 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2816 if (Elts[i]->getType() != Elts[0]->getType())
2817 return Error(FirstEltLoc,
2818 "array element #" + Twine(i) +
2819 " is not of type '" + getTypeString(Elts[0]->getType()));
2822 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2823 ID.Kind = ValID::t_Constant;
2826 case lltok::kw_c: // c "foo"
2828 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2830 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2831 ID.Kind = ValID::t_Constant;
2834 case lltok::kw_asm: {
2835 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2837 bool HasSideEffect, AlignStack, AsmDialect;
2839 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2840 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2841 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2842 ParseStringConstant(ID.StrVal) ||
2843 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2844 ParseToken(lltok::StringConstant, "expected constraint string"))
2846 ID.StrVal2 = Lex.getStrVal();
2847 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2848 (unsigned(AsmDialect)<<2);
2849 ID.Kind = ValID::t_InlineAsm;
2853 case lltok::kw_blockaddress: {
2854 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2859 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2861 ParseToken(lltok::comma, "expected comma in block address expression")||
2862 ParseValID(Label) ||
2863 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2866 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2867 return Error(Fn.Loc, "expected function name in blockaddress");
2868 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2869 return Error(Label.Loc, "expected basic block name in blockaddress");
2871 // Try to find the function (but skip it if it's forward-referenced).
2872 GlobalValue *GV = nullptr;
2873 if (Fn.Kind == ValID::t_GlobalID) {
2874 if (Fn.UIntVal < NumberedVals.size())
2875 GV = NumberedVals[Fn.UIntVal];
2876 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2877 GV = M->getNamedValue(Fn.StrVal);
2879 Function *F = nullptr;
2881 // Confirm that it's actually a function with a definition.
2882 if (!isa<Function>(GV))
2883 return Error(Fn.Loc, "expected function name in blockaddress");
2884 F = cast<Function>(GV);
2885 if (F->isDeclaration())
2886 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2890 // Make a global variable as a placeholder for this reference.
2891 GlobalValue *&FwdRef =
2892 ForwardRefBlockAddresses.insert(std::make_pair(
2894 std::map<ValID, GlobalValue *>()))
2895 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2898 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2899 GlobalValue::InternalLinkage, nullptr, "");
2900 ID.ConstantVal = FwdRef;
2901 ID.Kind = ValID::t_Constant;
2905 // We found the function; now find the basic block. Don't use PFS, since we
2906 // might be inside a constant expression.
2908 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2909 if (Label.Kind == ValID::t_LocalID)
2910 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2912 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2914 return Error(Label.Loc, "referenced value is not a basic block");
2916 if (Label.Kind == ValID::t_LocalID)
2917 return Error(Label.Loc, "cannot take address of numeric label after "
2918 "the function is defined");
2919 BB = dyn_cast_or_null<BasicBlock>(
2920 F->getValueSymbolTable().lookup(Label.StrVal));
2922 return Error(Label.Loc, "referenced value is not a basic block");
2925 ID.ConstantVal = BlockAddress::get(F, BB);
2926 ID.Kind = ValID::t_Constant;
2930 case lltok::kw_trunc:
2931 case lltok::kw_zext:
2932 case lltok::kw_sext:
2933 case lltok::kw_fptrunc:
2934 case lltok::kw_fpext:
2935 case lltok::kw_bitcast:
2936 case lltok::kw_addrspacecast:
2937 case lltok::kw_uitofp:
2938 case lltok::kw_sitofp:
2939 case lltok::kw_fptoui:
2940 case lltok::kw_fptosi:
2941 case lltok::kw_inttoptr:
2942 case lltok::kw_ptrtoint: {
2943 unsigned Opc = Lex.getUIntVal();
2944 Type *DestTy = nullptr;
2947 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2948 ParseGlobalTypeAndValue(SrcVal) ||
2949 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2950 ParseType(DestTy) ||
2951 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2953 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2954 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2955 getTypeString(SrcVal->getType()) + "' to '" +
2956 getTypeString(DestTy) + "'");
2957 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2959 ID.Kind = ValID::t_Constant;
2962 case lltok::kw_extractvalue: {
2965 SmallVector<unsigned, 4> Indices;
2966 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2967 ParseGlobalTypeAndValue(Val) ||
2968 ParseIndexList(Indices) ||
2969 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2972 if (!Val->getType()->isAggregateType())
2973 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2974 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2975 return Error(ID.Loc, "invalid indices for extractvalue");
2976 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2977 ID.Kind = ValID::t_Constant;
2980 case lltok::kw_insertvalue: {
2982 Constant *Val0, *Val1;
2983 SmallVector<unsigned, 4> Indices;
2984 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2985 ParseGlobalTypeAndValue(Val0) ||
2986 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2987 ParseGlobalTypeAndValue(Val1) ||
2988 ParseIndexList(Indices) ||
2989 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2991 if (!Val0->getType()->isAggregateType())
2992 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2994 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2996 return Error(ID.Loc, "invalid indices for insertvalue");
2997 if (IndexedType != Val1->getType())
2998 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2999 getTypeString(Val1->getType()) +
3000 "' instead of '" + getTypeString(IndexedType) +
3002 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3003 ID.Kind = ValID::t_Constant;
3006 case lltok::kw_icmp:
3007 case lltok::kw_fcmp: {
3008 unsigned PredVal, Opc = Lex.getUIntVal();
3009 Constant *Val0, *Val1;
3011 if (ParseCmpPredicate(PredVal, Opc) ||
3012 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3013 ParseGlobalTypeAndValue(Val0) ||
3014 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3015 ParseGlobalTypeAndValue(Val1) ||
3016 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3019 if (Val0->getType() != Val1->getType())
3020 return Error(ID.Loc, "compare operands must have the same type");
3022 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3024 if (Opc == Instruction::FCmp) {
3025 if (!Val0->getType()->isFPOrFPVectorTy())
3026 return Error(ID.Loc, "fcmp requires floating point operands");
3027 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3029 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3030 if (!Val0->getType()->isIntOrIntVectorTy() &&
3031 !Val0->getType()->getScalarType()->isPointerTy())
3032 return Error(ID.Loc, "icmp requires pointer or integer operands");
3033 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3035 ID.Kind = ValID::t_Constant;
3039 // Binary Operators.
3041 case lltok::kw_fadd:
3043 case lltok::kw_fsub:
3045 case lltok::kw_fmul:
3046 case lltok::kw_udiv:
3047 case lltok::kw_sdiv:
3048 case lltok::kw_fdiv:
3049 case lltok::kw_urem:
3050 case lltok::kw_srem:
3051 case lltok::kw_frem:
3053 case lltok::kw_lshr:
3054 case lltok::kw_ashr: {
3058 unsigned Opc = Lex.getUIntVal();
3059 Constant *Val0, *Val1;
3061 LocTy ModifierLoc = Lex.getLoc();
3062 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3063 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3064 if (EatIfPresent(lltok::kw_nuw))
3066 if (EatIfPresent(lltok::kw_nsw)) {
3068 if (EatIfPresent(lltok::kw_nuw))
3071 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3072 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3073 if (EatIfPresent(lltok::kw_exact))
3076 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3077 ParseGlobalTypeAndValue(Val0) ||
3078 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3079 ParseGlobalTypeAndValue(Val1) ||
3080 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3082 if (Val0->getType() != Val1->getType())
3083 return Error(ID.Loc, "operands of constexpr must have same type");
3084 if (!Val0->getType()->isIntOrIntVectorTy()) {
3086 return Error(ModifierLoc, "nuw only applies to integer operations");
3088 return Error(ModifierLoc, "nsw only applies to integer operations");
3090 // Check that the type is valid for the operator.
3092 case Instruction::Add:
3093 case Instruction::Sub:
3094 case Instruction::Mul:
3095 case Instruction::UDiv:
3096 case Instruction::SDiv:
3097 case Instruction::URem:
3098 case Instruction::SRem:
3099 case Instruction::Shl:
3100 case Instruction::AShr:
3101 case Instruction::LShr:
3102 if (!Val0->getType()->isIntOrIntVectorTy())
3103 return Error(ID.Loc, "constexpr requires integer operands");
3105 case Instruction::FAdd:
3106 case Instruction::FSub:
3107 case Instruction::FMul:
3108 case Instruction::FDiv:
3109 case Instruction::FRem:
3110 if (!Val0->getType()->isFPOrFPVectorTy())
3111 return Error(ID.Loc, "constexpr requires fp operands");
3113 default: llvm_unreachable("Unknown binary operator!");
3116 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3117 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3118 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3119 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3121 ID.Kind = ValID::t_Constant;
3125 // Logical Operations
3128 case lltok::kw_xor: {
3129 unsigned Opc = Lex.getUIntVal();
3130 Constant *Val0, *Val1;
3132 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3133 ParseGlobalTypeAndValue(Val0) ||
3134 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3135 ParseGlobalTypeAndValue(Val1) ||
3136 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3138 if (Val0->getType() != Val1->getType())
3139 return Error(ID.Loc, "operands of constexpr must have same type");
3140 if (!Val0->getType()->isIntOrIntVectorTy())
3141 return Error(ID.Loc,
3142 "constexpr requires integer or integer vector operands");
3143 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3144 ID.Kind = ValID::t_Constant;
3148 case lltok::kw_getelementptr:
3149 case lltok::kw_shufflevector:
3150 case lltok::kw_insertelement:
3151 case lltok::kw_extractelement:
3152 case lltok::kw_select: {
3153 unsigned Opc = Lex.getUIntVal();
3154 SmallVector<Constant*, 16> Elts;
3155 bool InBounds = false;
3159 if (Opc == Instruction::GetElementPtr)
3160 InBounds = EatIfPresent(lltok::kw_inbounds);
3162 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3165 LocTy ExplicitTypeLoc = Lex.getLoc();
3166 if (Opc == Instruction::GetElementPtr) {
3167 if (ParseType(Ty) ||
3168 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3172 if (ParseGlobalValueVector(Elts) ||
3173 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3176 if (Opc == Instruction::GetElementPtr) {
3177 if (Elts.size() == 0 ||
3178 !Elts[0]->getType()->getScalarType()->isPointerTy())
3179 return Error(ID.Loc, "base of getelementptr must be a pointer");
3181 Type *BaseType = Elts[0]->getType();
3182 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3183 if (Ty != BasePointerType->getElementType())
3186 "explicit pointee type doesn't match operand's pointee type");
3188 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3189 for (Constant *Val : Indices) {
3190 Type *ValTy = Val->getType();
3191 if (!ValTy->getScalarType()->isIntegerTy())
3192 return Error(ID.Loc, "getelementptr index must be an integer");
3193 if (ValTy->isVectorTy() != BaseType->isVectorTy())
3194 return Error(ID.Loc, "getelementptr index type missmatch");
3195 if (ValTy->isVectorTy()) {
3196 unsigned ValNumEl = ValTy->getVectorNumElements();
3197 unsigned PtrNumEl = BaseType->getVectorNumElements();
3198 if (ValNumEl != PtrNumEl)
3201 "getelementptr vector index has a wrong number of elements");
3205 SmallPtrSet<Type*, 4> Visited;
3206 if (!Indices.empty() && !Ty->isSized(&Visited))
3207 return Error(ID.Loc, "base element of getelementptr must be sized");
3209 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3210 return Error(ID.Loc, "invalid getelementptr indices");
3212 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
3213 } else if (Opc == Instruction::Select) {
3214 if (Elts.size() != 3)
3215 return Error(ID.Loc, "expected three operands to select");
3216 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3218 return Error(ID.Loc, Reason);
3219 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3220 } else if (Opc == Instruction::ShuffleVector) {
3221 if (Elts.size() != 3)
3222 return Error(ID.Loc, "expected three operands to shufflevector");
3223 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3224 return Error(ID.Loc, "invalid operands to shufflevector");
3226 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3227 } else if (Opc == Instruction::ExtractElement) {
3228 if (Elts.size() != 2)
3229 return Error(ID.Loc, "expected two operands to extractelement");
3230 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3231 return Error(ID.Loc, "invalid extractelement operands");
3232 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3234 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3235 if (Elts.size() != 3)
3236 return Error(ID.Loc, "expected three operands to insertelement");
3237 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3238 return Error(ID.Loc, "invalid insertelement operands");
3240 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3243 ID.Kind = ValID::t_Constant;
3252 /// ParseGlobalValue - Parse a global value with the specified type.
3253 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3257 bool Parsed = ParseValID(ID) ||
3258 ConvertValIDToValue(Ty, ID, V, nullptr);
3259 if (V && !(C = dyn_cast<Constant>(V)))
3260 return Error(ID.Loc, "global values must be constants");
3264 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3266 return ParseType(Ty) ||
3267 ParseGlobalValue(Ty, V);
3270 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3273 LocTy KwLoc = Lex.getLoc();
3274 if (!EatIfPresent(lltok::kw_comdat))
3277 if (EatIfPresent(lltok::lparen)) {
3278 if (Lex.getKind() != lltok::ComdatVar)
3279 return TokError("expected comdat variable");
3280 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3282 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3285 if (GlobalName.empty())
3286 return TokError("comdat cannot be unnamed");
3287 C = getComdat(GlobalName, KwLoc);
3293 /// ParseGlobalValueVector
3295 /// ::= TypeAndValue (',' TypeAndValue)*
3296 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
3298 if (Lex.getKind() == lltok::rbrace ||
3299 Lex.getKind() == lltok::rsquare ||
3300 Lex.getKind() == lltok::greater ||
3301 Lex.getKind() == lltok::rparen)
3305 if (ParseGlobalTypeAndValue(C)) return true;
3308 while (EatIfPresent(lltok::comma)) {
3309 if (ParseGlobalTypeAndValue(C)) return true;
3316 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3317 SmallVector<Metadata *, 16> Elts;
3318 if (ParseMDNodeVector(Elts))
3321 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3328 /// ::= !DILocation(...)
3329 bool LLParser::ParseMDNode(MDNode *&N) {
3330 if (Lex.getKind() == lltok::MetadataVar)
3331 return ParseSpecializedMDNode(N);
3333 return ParseToken(lltok::exclaim, "expected '!' here") ||
3337 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3339 if (Lex.getKind() == lltok::lbrace)
3340 return ParseMDTuple(N);
3343 return ParseMDNodeID(N);
3348 /// Structure to represent an optional metadata field.
3349 template <class FieldTy> struct MDFieldImpl {
3350 typedef MDFieldImpl ImplTy;
3354 void assign(FieldTy Val) {
3356 this->Val = std::move(Val);
3359 explicit MDFieldImpl(FieldTy Default)
3360 : Val(std::move(Default)), Seen(false) {}
3363 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3366 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3367 : ImplTy(Default), Max(Max) {}
3370 struct LineField : public MDUnsignedField {
3371 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3374 struct ColumnField : public MDUnsignedField {
3375 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3378 struct DwarfTagField : public MDUnsignedField {
3379 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3380 DwarfTagField(dwarf::Tag DefaultTag)
3381 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3384 struct DwarfMacinfoTypeField : public MDUnsignedField {
3385 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3386 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3387 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3390 struct DwarfAttEncodingField : public MDUnsignedField {
3391 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3394 struct DwarfVirtualityField : public MDUnsignedField {
3395 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3398 struct DwarfLangField : public MDUnsignedField {
3399 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3402 struct DwarfCCField : public MDUnsignedField {
3403 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3406 struct EmissionKindField : public MDUnsignedField {
3407 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3410 struct DIFlagField : public MDUnsignedField {
3411 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3414 struct MDSignedField : public MDFieldImpl<int64_t> {
3418 MDSignedField(int64_t Default = 0)
3419 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3420 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3421 : ImplTy(Default), Min(Min), Max(Max) {}
3424 struct MDBoolField : public MDFieldImpl<bool> {
3425 MDBoolField(bool Default = false) : ImplTy(Default) {}
3428 struct MDField : public MDFieldImpl<Metadata *> {
3431 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3434 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3435 MDConstant() : ImplTy(nullptr) {}
3438 struct MDStringField : public MDFieldImpl<MDString *> {
3440 MDStringField(bool AllowEmpty = true)
3441 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3444 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3445 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3448 } // end anonymous namespace
3453 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3454 MDUnsignedField &Result) {
3455 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3456 return TokError("expected unsigned integer");
3458 auto &U = Lex.getAPSIntVal();
3459 if (U.ugt(Result.Max))
3460 return TokError("value for '" + Name + "' too large, limit is " +
3462 Result.assign(U.getZExtValue());
3463 assert(Result.Val <= Result.Max && "Expected value in range");
3469 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3470 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3473 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3474 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3478 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3479 if (Lex.getKind() == lltok::APSInt)
3480 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3482 if (Lex.getKind() != lltok::DwarfTag)
3483 return TokError("expected DWARF tag");
3485 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3486 if (Tag == dwarf::DW_TAG_invalid)
3487 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3488 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3496 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3497 DwarfMacinfoTypeField &Result) {
3498 if (Lex.getKind() == lltok::APSInt)
3499 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3501 if (Lex.getKind() != lltok::DwarfMacinfo)
3502 return TokError("expected DWARF macinfo type");
3504 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3505 if (Macinfo == dwarf::DW_MACINFO_invalid)
3507 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3508 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3510 Result.assign(Macinfo);
3516 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3517 DwarfVirtualityField &Result) {
3518 if (Lex.getKind() == lltok::APSInt)
3519 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3521 if (Lex.getKind() != lltok::DwarfVirtuality)
3522 return TokError("expected DWARF virtuality code");
3524 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3525 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3526 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3527 Lex.getStrVal() + "'");
3528 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3529 Result.assign(Virtuality);
3535 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3536 if (Lex.getKind() == lltok::APSInt)
3537 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3539 if (Lex.getKind() != lltok::DwarfLang)
3540 return TokError("expected DWARF language");
3542 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3544 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3546 assert(Lang <= Result.Max && "Expected valid DWARF language");
3547 Result.assign(Lang);
3553 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3554 if (Lex.getKind() == lltok::APSInt)
3555 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3557 if (Lex.getKind() != lltok::DwarfCC)
3558 return TokError("expected DWARF calling convention");
3560 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3562 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3564 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3571 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3572 if (Lex.getKind() == lltok::APSInt)
3573 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3575 if (Lex.getKind() != lltok::EmissionKind)
3576 return TokError("expected emission kind");
3578 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3580 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3582 assert(*Kind <= Result.Max && "Expected valid emission kind");
3583 Result.assign(*Kind);
3589 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3590 DwarfAttEncodingField &Result) {
3591 if (Lex.getKind() == lltok::APSInt)
3592 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3594 if (Lex.getKind() != lltok::DwarfAttEncoding)
3595 return TokError("expected DWARF type attribute encoding");
3597 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3599 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3600 Lex.getStrVal() + "'");
3601 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3602 Result.assign(Encoding);
3609 /// ::= DIFlagVector
3610 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3612 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3613 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3615 // Parser for a single flag.
3616 auto parseFlag = [&](unsigned &Val) {
3617 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3618 return ParseUInt32(Val);
3620 if (Lex.getKind() != lltok::DIFlag)
3621 return TokError("expected debug info flag");
3623 Val = DINode::getFlag(Lex.getStrVal());
3625 return TokError(Twine("invalid debug info flag flag '") +
3626 Lex.getStrVal() + "'");
3631 // Parse the flags and combine them together.
3632 unsigned Combined = 0;
3638 } while (EatIfPresent(lltok::bar));
3640 Result.assign(Combined);
3645 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3646 MDSignedField &Result) {
3647 if (Lex.getKind() != lltok::APSInt)
3648 return TokError("expected signed integer");
3650 auto &S = Lex.getAPSIntVal();
3652 return TokError("value for '" + Name + "' too small, limit is " +
3655 return TokError("value for '" + Name + "' too large, limit is " +
3657 Result.assign(S.getExtValue());
3658 assert(Result.Val >= Result.Min && "Expected value in range");
3659 assert(Result.Val <= Result.Max && "Expected value in range");
3665 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3666 switch (Lex.getKind()) {
3668 return TokError("expected 'true' or 'false'");
3669 case lltok::kw_true:
3670 Result.assign(true);
3672 case lltok::kw_false:
3673 Result.assign(false);
3681 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3682 if (Lex.getKind() == lltok::kw_null) {
3683 if (!Result.AllowNull)
3684 return TokError("'" + Name + "' cannot be null");
3686 Result.assign(nullptr);
3691 if (ParseMetadata(MD, nullptr))
3699 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3701 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3704 Result.assign(cast<ConstantAsMetadata>(MD));
3709 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3710 LocTy ValueLoc = Lex.getLoc();
3712 if (ParseStringConstant(S))
3715 if (!Result.AllowEmpty && S.empty())
3716 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3718 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3723 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3724 SmallVector<Metadata *, 4> MDs;
3725 if (ParseMDNodeVector(MDs))
3728 Result.assign(std::move(MDs));
3732 } // end namespace llvm
3734 template <class ParserTy>
3735 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3737 if (Lex.getKind() != lltok::LabelStr)
3738 return TokError("expected field label here");
3742 } while (EatIfPresent(lltok::comma));
3747 template <class ParserTy>
3748 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3749 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3752 if (ParseToken(lltok::lparen, "expected '(' here"))
3754 if (Lex.getKind() != lltok::rparen)
3755 if (ParseMDFieldsImplBody(parseField))
3758 ClosingLoc = Lex.getLoc();
3759 return ParseToken(lltok::rparen, "expected ')' here");
3762 template <class FieldTy>
3763 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3765 return TokError("field '" + Name + "' cannot be specified more than once");
3767 LocTy Loc = Lex.getLoc();
3769 return ParseMDField(Loc, Name, Result);
3772 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3773 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3775 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3776 if (Lex.getStrVal() == #CLASS) \
3777 return Parse##CLASS(N, IsDistinct);
3778 #include "llvm/IR/Metadata.def"
3780 return TokError("expected metadata type");
3783 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3784 #define NOP_FIELD(NAME, TYPE, INIT)
3785 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3787 return Error(ClosingLoc, "missing required field '" #NAME "'");
3788 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3789 if (Lex.getStrVal() == #NAME) \
3790 return ParseMDField(#NAME, NAME);
3791 #define PARSE_MD_FIELDS() \
3792 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3795 if (ParseMDFieldsImpl([&]() -> bool { \
3796 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3797 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3800 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3802 #define GET_OR_DISTINCT(CLASS, ARGS) \
3803 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3805 /// ParseDILocationFields:
3806 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3807 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3808 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3809 OPTIONAL(line, LineField, ); \
3810 OPTIONAL(column, ColumnField, ); \
3811 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3812 OPTIONAL(inlinedAt, MDField, );
3814 #undef VISIT_MD_FIELDS
3816 Result = GET_OR_DISTINCT(
3817 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3821 /// ParseGenericDINode:
3822 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3823 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3824 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3825 REQUIRED(tag, DwarfTagField, ); \
3826 OPTIONAL(header, MDStringField, ); \
3827 OPTIONAL(operands, MDFieldList, );
3829 #undef VISIT_MD_FIELDS
3831 Result = GET_OR_DISTINCT(GenericDINode,
3832 (Context, tag.Val, header.Val, operands.Val));
3836 /// ParseDISubrange:
3837 /// ::= !DISubrange(count: 30, lowerBound: 2)
3838 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3839 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3840 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3841 OPTIONAL(lowerBound, MDSignedField, );
3843 #undef VISIT_MD_FIELDS
3845 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3849 /// ParseDIEnumerator:
3850 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3851 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3852 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3853 REQUIRED(name, MDStringField, ); \
3854 REQUIRED(value, MDSignedField, );
3856 #undef VISIT_MD_FIELDS
3858 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3862 /// ParseDIBasicType:
3863 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3864 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3865 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3866 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3867 OPTIONAL(name, MDStringField, ); \
3868 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3869 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3870 OPTIONAL(encoding, DwarfAttEncodingField, );
3872 #undef VISIT_MD_FIELDS
3874 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3875 align.Val, encoding.Val));
3879 /// ParseDIDerivedType:
3880 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3881 /// line: 7, scope: !1, baseType: !2, size: 32,
3882 /// align: 32, offset: 0, flags: 0, extraData: !3)
3883 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3884 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3885 REQUIRED(tag, DwarfTagField, ); \
3886 OPTIONAL(name, MDStringField, ); \
3887 OPTIONAL(file, MDField, ); \
3888 OPTIONAL(line, LineField, ); \
3889 OPTIONAL(scope, MDField, ); \
3890 REQUIRED(baseType, MDField, ); \
3891 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3892 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3893 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3894 OPTIONAL(flags, DIFlagField, ); \
3895 OPTIONAL(extraData, MDField, );
3897 #undef VISIT_MD_FIELDS
3899 Result = GET_OR_DISTINCT(DIDerivedType,
3900 (Context, tag.Val, name.Val, file.Val, line.Val,
3901 scope.Val, baseType.Val, size.Val, align.Val,
3902 offset.Val, flags.Val, extraData.Val));
3906 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3907 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3908 REQUIRED(tag, DwarfTagField, ); \
3909 OPTIONAL(name, MDStringField, ); \
3910 OPTIONAL(file, MDField, ); \
3911 OPTIONAL(line, LineField, ); \
3912 OPTIONAL(scope, MDField, ); \
3913 OPTIONAL(baseType, MDField, ); \
3914 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3915 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3916 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3917 OPTIONAL(flags, DIFlagField, ); \
3918 OPTIONAL(elements, MDField, ); \
3919 OPTIONAL(runtimeLang, DwarfLangField, ); \
3920 OPTIONAL(vtableHolder, MDField, ); \
3921 OPTIONAL(templateParams, MDField, ); \
3922 OPTIONAL(identifier, MDStringField, );
3924 #undef VISIT_MD_FIELDS
3926 // If this has an identifier try to build an ODR type.
3928 if (auto *CT = DICompositeType::buildODRType(
3929 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
3930 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3931 elements.Val, runtimeLang.Val, vtableHolder.Val,
3932 templateParams.Val)) {
3937 // Create a new node, and save it in the context if it belongs in the type
3939 Result = GET_OR_DISTINCT(
3941 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3942 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3943 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3947 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3948 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3949 OPTIONAL(flags, DIFlagField, ); \
3950 OPTIONAL(cc, DwarfCCField, ); \
3951 REQUIRED(types, MDField, );
3953 #undef VISIT_MD_FIELDS
3955 Result = GET_OR_DISTINCT(DISubroutineType,
3956 (Context, flags.Val, cc.Val, types.Val));
3960 /// ParseDIFileType:
3961 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3962 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3963 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3964 REQUIRED(filename, MDStringField, ); \
3965 REQUIRED(directory, MDStringField, );
3967 #undef VISIT_MD_FIELDS
3969 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3973 /// ParseDICompileUnit:
3974 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3975 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3976 /// splitDebugFilename: "abc.debug",
3977 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
3978 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
3979 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3981 return Lex.Error("missing 'distinct', required for !DICompileUnit");
3983 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3984 REQUIRED(language, DwarfLangField, ); \
3985 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3986 OPTIONAL(producer, MDStringField, ); \
3987 OPTIONAL(isOptimized, MDBoolField, ); \
3988 OPTIONAL(flags, MDStringField, ); \
3989 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3990 OPTIONAL(splitDebugFilename, MDStringField, ); \
3991 OPTIONAL(emissionKind, EmissionKindField, ); \
3992 OPTIONAL(enums, MDField, ); \
3993 OPTIONAL(retainedTypes, MDField, ); \
3994 OPTIONAL(globals, MDField, ); \
3995 OPTIONAL(imports, MDField, ); \
3996 OPTIONAL(macros, MDField, ); \
3997 OPTIONAL(dwoId, MDUnsignedField, ); \
3998 OPTIONAL(splitDebugInlining, MDBoolField, = true);
4000 #undef VISIT_MD_FIELDS
4002 Result = DICompileUnit::getDistinct(
4003 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4004 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4005 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4006 splitDebugInlining.Val);
4010 /// ParseDISubprogram:
4011 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4012 /// file: !1, line: 7, type: !2, isLocal: false,
4013 /// isDefinition: true, scopeLine: 8, containingType: !3,
4014 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4015 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4016 /// isOptimized: false, templateParams: !4, declaration: !5,
4018 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4019 auto Loc = Lex.getLoc();
4020 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4021 OPTIONAL(scope, MDField, ); \
4022 OPTIONAL(name, MDStringField, ); \
4023 OPTIONAL(linkageName, MDStringField, ); \
4024 OPTIONAL(file, MDField, ); \
4025 OPTIONAL(line, LineField, ); \
4026 OPTIONAL(type, MDField, ); \
4027 OPTIONAL(isLocal, MDBoolField, ); \
4028 OPTIONAL(isDefinition, MDBoolField, (true)); \
4029 OPTIONAL(scopeLine, LineField, ); \
4030 OPTIONAL(containingType, MDField, ); \
4031 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4032 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4033 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4034 OPTIONAL(flags, DIFlagField, ); \
4035 OPTIONAL(isOptimized, MDBoolField, ); \
4036 OPTIONAL(unit, MDField, ); \
4037 OPTIONAL(templateParams, MDField, ); \
4038 OPTIONAL(declaration, MDField, ); \
4039 OPTIONAL(variables, MDField, );
4041 #undef VISIT_MD_FIELDS
4043 if (isDefinition.Val && !IsDistinct)
4046 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4048 Result = GET_OR_DISTINCT(
4049 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4050 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4051 scopeLine.Val, containingType.Val, virtuality.Val,
4052 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4053 isOptimized.Val, unit.Val, templateParams.Val,
4054 declaration.Val, variables.Val));
4058 /// ParseDILexicalBlock:
4059 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4060 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4061 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4062 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4063 OPTIONAL(file, MDField, ); \
4064 OPTIONAL(line, LineField, ); \
4065 OPTIONAL(column, ColumnField, );
4067 #undef VISIT_MD_FIELDS
4069 Result = GET_OR_DISTINCT(
4070 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4074 /// ParseDILexicalBlockFile:
4075 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4076 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4077 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4078 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4079 OPTIONAL(file, MDField, ); \
4080 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4082 #undef VISIT_MD_FIELDS
4084 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4085 (Context, scope.Val, file.Val, discriminator.Val));
4089 /// ParseDINamespace:
4090 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4091 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4092 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4093 REQUIRED(scope, MDField, ); \
4094 OPTIONAL(file, MDField, ); \
4095 OPTIONAL(name, MDStringField, ); \
4096 OPTIONAL(line, LineField, );
4098 #undef VISIT_MD_FIELDS
4100 Result = GET_OR_DISTINCT(DINamespace,
4101 (Context, scope.Val, file.Val, name.Val, line.Val));
4106 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4107 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4108 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4109 REQUIRED(type, DwarfMacinfoTypeField, ); \
4110 REQUIRED(line, LineField, ); \
4111 REQUIRED(name, MDStringField, ); \
4112 OPTIONAL(value, MDStringField, );
4114 #undef VISIT_MD_FIELDS
4116 Result = GET_OR_DISTINCT(DIMacro,
4117 (Context, type.Val, line.Val, name.Val, value.Val));
4121 /// ParseDIMacroFile:
4122 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4123 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4124 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4125 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4126 REQUIRED(line, LineField, ); \
4127 REQUIRED(file, MDField, ); \
4128 OPTIONAL(nodes, MDField, );
4130 #undef VISIT_MD_FIELDS
4132 Result = GET_OR_DISTINCT(DIMacroFile,
4133 (Context, type.Val, line.Val, file.Val, nodes.Val));
4138 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4139 /// includePath: "/usr/include", isysroot: "/")
4140 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4141 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4142 REQUIRED(scope, MDField, ); \
4143 REQUIRED(name, MDStringField, ); \
4144 OPTIONAL(configMacros, MDStringField, ); \
4145 OPTIONAL(includePath, MDStringField, ); \
4146 OPTIONAL(isysroot, MDStringField, );
4148 #undef VISIT_MD_FIELDS
4150 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4151 configMacros.Val, includePath.Val, isysroot.Val));
4155 /// ParseDITemplateTypeParameter:
4156 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4157 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4158 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4159 OPTIONAL(name, MDStringField, ); \
4160 REQUIRED(type, MDField, );
4162 #undef VISIT_MD_FIELDS
4165 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4169 /// ParseDITemplateValueParameter:
4170 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4171 /// name: "V", type: !1, value: i32 7)
4172 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4173 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4174 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4175 OPTIONAL(name, MDStringField, ); \
4176 OPTIONAL(type, MDField, ); \
4177 REQUIRED(value, MDField, );
4179 #undef VISIT_MD_FIELDS
4181 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4182 (Context, tag.Val, name.Val, type.Val, value.Val));
4186 /// ParseDIGlobalVariable:
4187 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4188 /// file: !1, line: 7, type: !2, isLocal: false,
4189 /// isDefinition: true, variable: i32* @foo,
4190 /// declaration: !3)
4191 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4192 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4193 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4194 OPTIONAL(scope, MDField, ); \
4195 OPTIONAL(linkageName, MDStringField, ); \
4196 OPTIONAL(file, MDField, ); \
4197 OPTIONAL(line, LineField, ); \
4198 OPTIONAL(type, MDField, ); \
4199 OPTIONAL(isLocal, MDBoolField, ); \
4200 OPTIONAL(isDefinition, MDBoolField, (true)); \
4201 OPTIONAL(variable, MDConstant, ); \
4202 OPTIONAL(declaration, MDField, );
4204 #undef VISIT_MD_FIELDS
4206 Result = GET_OR_DISTINCT(DIGlobalVariable,
4207 (Context, scope.Val, name.Val, linkageName.Val,
4208 file.Val, line.Val, type.Val, isLocal.Val,
4209 isDefinition.Val, variable.Val, declaration.Val));
4213 /// ParseDILocalVariable:
4214 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4215 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4216 /// ::= !DILocalVariable(scope: !0, name: "foo",
4217 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
4218 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4219 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4220 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4221 OPTIONAL(name, MDStringField, ); \
4222 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4223 OPTIONAL(file, MDField, ); \
4224 OPTIONAL(line, LineField, ); \
4225 OPTIONAL(type, MDField, ); \
4226 OPTIONAL(flags, DIFlagField, );
4228 #undef VISIT_MD_FIELDS
4230 Result = GET_OR_DISTINCT(DILocalVariable,
4231 (Context, scope.Val, name.Val, file.Val, line.Val,
4232 type.Val, arg.Val, flags.Val));
4236 /// ParseDIExpression:
4237 /// ::= !DIExpression(0, 7, -1)
4238 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4239 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4242 if (ParseToken(lltok::lparen, "expected '(' here"))
4245 SmallVector<uint64_t, 8> Elements;
4246 if (Lex.getKind() != lltok::rparen)
4248 if (Lex.getKind() == lltok::DwarfOp) {
4249 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4251 Elements.push_back(Op);
4254 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4257 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4258 return TokError("expected unsigned integer");
4260 auto &U = Lex.getAPSIntVal();
4261 if (U.ugt(UINT64_MAX))
4262 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4263 Elements.push_back(U.getZExtValue());
4265 } while (EatIfPresent(lltok::comma));
4267 if (ParseToken(lltok::rparen, "expected ')' here"))
4270 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4274 /// ParseDIObjCProperty:
4275 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4276 /// getter: "getFoo", attributes: 7, type: !2)
4277 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4278 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4279 OPTIONAL(name, MDStringField, ); \
4280 OPTIONAL(file, MDField, ); \
4281 OPTIONAL(line, LineField, ); \
4282 OPTIONAL(setter, MDStringField, ); \
4283 OPTIONAL(getter, MDStringField, ); \
4284 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4285 OPTIONAL(type, MDField, );
4287 #undef VISIT_MD_FIELDS
4289 Result = GET_OR_DISTINCT(DIObjCProperty,
4290 (Context, name.Val, file.Val, line.Val, setter.Val,
4291 getter.Val, attributes.Val, type.Val));
4295 /// ParseDIImportedEntity:
4296 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4297 /// line: 7, name: "foo")
4298 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4299 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4300 REQUIRED(tag, DwarfTagField, ); \
4301 REQUIRED(scope, MDField, ); \
4302 OPTIONAL(entity, MDField, ); \
4303 OPTIONAL(line, LineField, ); \
4304 OPTIONAL(name, MDStringField, );
4306 #undef VISIT_MD_FIELDS
4308 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
4309 entity.Val, line.Val, name.Val));
4313 #undef PARSE_MD_FIELD
4315 #undef REQUIRE_FIELD
4316 #undef DECLARE_FIELD
4318 /// ParseMetadataAsValue
4319 /// ::= metadata i32 %local
4320 /// ::= metadata i32 @global
4321 /// ::= metadata i32 7
4323 /// ::= metadata !{...}
4324 /// ::= metadata !"string"
4325 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4326 // Note: the type 'metadata' has already been parsed.
4328 if (ParseMetadata(MD, &PFS))
4331 V = MetadataAsValue::get(Context, MD);
4335 /// ParseValueAsMetadata
4339 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4340 PerFunctionState *PFS) {
4343 if (ParseType(Ty, TypeMsg, Loc))
4345 if (Ty->isMetadataTy())
4346 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4349 if (ParseValue(Ty, V, PFS))
4352 MD = ValueAsMetadata::get(V);
4363 /// ::= !DILocation(...)
4364 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4365 if (Lex.getKind() == lltok::MetadataVar) {
4367 if (ParseSpecializedMDNode(N))
4375 if (Lex.getKind() != lltok::exclaim)
4376 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4379 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4383 // ::= '!' STRINGCONSTANT
4384 if (Lex.getKind() == lltok::StringConstant) {
4386 if (ParseMDString(S))
4396 if (ParseMDNodeTail(N))
4402 //===----------------------------------------------------------------------===//
4403 // Function Parsing.
4404 //===----------------------------------------------------------------------===//
4406 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
4407 PerFunctionState *PFS) {
4408 if (Ty->isFunctionTy())
4409 return Error(ID.Loc, "functions are not values, refer to them as pointers");
4412 case ValID::t_LocalID:
4413 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4414 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
4415 return V == nullptr;
4416 case ValID::t_LocalName:
4417 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
4418 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
4419 return V == nullptr;
4420 case ValID::t_InlineAsm: {
4421 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
4422 return Error(ID.Loc, "invalid type for inline asm constraint string");
4423 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
4424 (ID.UIntVal >> 1) & 1,
4425 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
4428 case ValID::t_GlobalName:
4429 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
4430 return V == nullptr;
4431 case ValID::t_GlobalID:
4432 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
4433 return V == nullptr;
4434 case ValID::t_APSInt:
4435 if (!Ty->isIntegerTy())
4436 return Error(ID.Loc, "integer constant must have integer type");
4437 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
4438 V = ConstantInt::get(Context, ID.APSIntVal);
4440 case ValID::t_APFloat:
4441 if (!Ty->isFloatingPointTy() ||
4442 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
4443 return Error(ID.Loc, "floating point constant invalid for type");
4445 // The lexer has no type info, so builds all half, float, and double FP
4446 // constants as double. Fix this here. Long double does not need this.
4447 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
4450 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
4452 else if (Ty->isFloatTy())
4453 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
4456 V = ConstantFP::get(Context, ID.APFloatVal);
4458 if (V->getType() != Ty)
4459 return Error(ID.Loc, "floating point constant does not have type '" +
4460 getTypeString(Ty) + "'");
4464 if (!Ty->isPointerTy())
4465 return Error(ID.Loc, "null must be a pointer type");
4466 V = ConstantPointerNull::get(cast<PointerType>(Ty));
4468 case ValID::t_Undef:
4469 // FIXME: LabelTy should not be a first-class type.
4470 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4471 return Error(ID.Loc, "invalid type for undef constant");
4472 V = UndefValue::get(Ty);
4474 case ValID::t_EmptyArray:
4475 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4476 return Error(ID.Loc, "invalid empty array initializer");
4477 V = UndefValue::get(Ty);
4480 // FIXME: LabelTy should not be a first-class type.
4481 if (!Ty->isFirstClassType() || Ty->isLabelTy())
4482 return Error(ID.Loc, "invalid type for null constant");
4483 V = Constant::getNullValue(Ty);
4486 if (!Ty->isTokenTy())
4487 return Error(ID.Loc, "invalid type for none constant");
4488 V = Constant::getNullValue(Ty);
4490 case ValID::t_Constant:
4491 if (ID.ConstantVal->getType() != Ty)
4492 return Error(ID.Loc, "constant expression type mismatch");
4496 case ValID::t_ConstantStruct:
4497 case ValID::t_PackedConstantStruct:
4498 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4499 if (ST->getNumElements() != ID.UIntVal)
4500 return Error(ID.Loc,
4501 "initializer with struct type has wrong # elements");
4502 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4503 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4505 // Verify that the elements are compatible with the structtype.
4506 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4507 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4508 return Error(ID.Loc, "element " + Twine(i) +
4509 " of struct initializer doesn't match struct element type");
4511 V = ConstantStruct::get(
4512 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
4514 return Error(ID.Loc, "constant expression type mismatch");
4517 llvm_unreachable("Invalid ValID");
4520 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
4523 auto Loc = Lex.getLoc();
4524 if (ParseValID(ID, /*PFS=*/nullptr))
4527 case ValID::t_APSInt:
4528 case ValID::t_APFloat:
4529 case ValID::t_Undef:
4530 case ValID::t_Constant:
4531 case ValID::t_ConstantStruct:
4532 case ValID::t_PackedConstantStruct: {
4534 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
4536 assert(isa<Constant>(V) && "Expected a constant value");
4537 C = cast<Constant>(V);
4541 return Error(Loc, "expected a constant value");
4545 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4548 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4551 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4553 return ParseType(Ty) ||
4554 ParseValue(Ty, V, PFS);
4557 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4558 PerFunctionState &PFS) {
4561 if (ParseTypeAndValue(V, PFS)) return true;
4562 if (!isa<BasicBlock>(V))
4563 return Error(Loc, "expected a basic block");
4564 BB = cast<BasicBlock>(V);
4569 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4570 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4571 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
4572 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4573 // Parse the linkage.
4574 LocTy LinkageLoc = Lex.getLoc();
4577 unsigned Visibility;
4578 unsigned DLLStorageClass;
4579 AttrBuilder RetAttrs;
4582 Type *RetType = nullptr;
4583 LocTy RetTypeLoc = Lex.getLoc();
4584 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4585 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4586 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4589 // Verify that the linkage is ok.
4590 switch ((GlobalValue::LinkageTypes)Linkage) {
4591 case GlobalValue::ExternalLinkage:
4592 break; // always ok.
4593 case GlobalValue::ExternalWeakLinkage:
4595 return Error(LinkageLoc, "invalid linkage for function definition");
4597 case GlobalValue::PrivateLinkage:
4598 case GlobalValue::InternalLinkage:
4599 case GlobalValue::AvailableExternallyLinkage:
4600 case GlobalValue::LinkOnceAnyLinkage:
4601 case GlobalValue::LinkOnceODRLinkage:
4602 case GlobalValue::WeakAnyLinkage:
4603 case GlobalValue::WeakODRLinkage:
4605 return Error(LinkageLoc, "invalid linkage for function declaration");
4607 case GlobalValue::AppendingLinkage:
4608 case GlobalValue::CommonLinkage:
4609 return Error(LinkageLoc, "invalid function linkage type");
4612 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4613 return Error(LinkageLoc,
4614 "symbol with local linkage must have default visibility");
4616 if (!FunctionType::isValidReturnType(RetType))
4617 return Error(RetTypeLoc, "invalid function return type");
4619 LocTy NameLoc = Lex.getLoc();
4621 std::string FunctionName;
4622 if (Lex.getKind() == lltok::GlobalVar) {
4623 FunctionName = Lex.getStrVal();
4624 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4625 unsigned NameID = Lex.getUIntVal();
4627 if (NameID != NumberedVals.size())
4628 return TokError("function expected to be numbered '%" +
4629 Twine(NumberedVals.size()) + "'");
4631 return TokError("expected function name");
4636 if (Lex.getKind() != lltok::lparen)
4637 return TokError("expected '(' in function argument list");
4639 SmallVector<ArgInfo, 8> ArgList;
4641 AttrBuilder FuncAttrs;
4642 std::vector<unsigned> FwdRefAttrGrps;
4644 std::string Section;
4647 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4648 LocTy UnnamedAddrLoc;
4649 Constant *Prefix = nullptr;
4650 Constant *Prologue = nullptr;
4651 Constant *PersonalityFn = nullptr;
4654 if (ParseArgumentList(ArgList, isVarArg) ||
4655 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4656 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4658 (EatIfPresent(lltok::kw_section) &&
4659 ParseStringConstant(Section)) ||
4660 parseOptionalComdat(FunctionName, C) ||
4661 ParseOptionalAlignment(Alignment) ||
4662 (EatIfPresent(lltok::kw_gc) &&
4663 ParseStringConstant(GC)) ||
4664 (EatIfPresent(lltok::kw_prefix) &&
4665 ParseGlobalTypeAndValue(Prefix)) ||
4666 (EatIfPresent(lltok::kw_prologue) &&
4667 ParseGlobalTypeAndValue(Prologue)) ||
4668 (EatIfPresent(lltok::kw_personality) &&
4669 ParseGlobalTypeAndValue(PersonalityFn)))
4672 if (FuncAttrs.contains(Attribute::Builtin))
4673 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4675 // If the alignment was parsed as an attribute, move to the alignment field.
4676 if (FuncAttrs.hasAlignmentAttr()) {
4677 Alignment = FuncAttrs.getAlignment();
4678 FuncAttrs.removeAttribute(Attribute::Alignment);
4681 // Okay, if we got here, the function is syntactically valid. Convert types
4682 // and do semantic checks.
4683 std::vector<Type*> ParamTypeList;
4684 SmallVector<AttributeSet, 8> Attrs;
4686 if (RetAttrs.hasAttributes())
4687 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4688 AttributeSet::ReturnIndex,
4691 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4692 ParamTypeList.push_back(ArgList[i].Ty);
4693 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4694 AttrBuilder B(ArgList[i].Attrs, i + 1);
4695 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4699 if (FuncAttrs.hasAttributes())
4700 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4701 AttributeSet::FunctionIndex,
4704 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4706 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4707 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4710 FunctionType::get(RetType, ParamTypeList, isVarArg);
4711 PointerType *PFT = PointerType::getUnqual(FT);
4714 if (!FunctionName.empty()) {
4715 // If this was a definition of a forward reference, remove the definition
4716 // from the forward reference table and fill in the forward ref.
4717 auto FRVI = ForwardRefVals.find(FunctionName);
4718 if (FRVI != ForwardRefVals.end()) {
4719 Fn = M->getFunction(FunctionName);
4721 return Error(FRVI->second.second, "invalid forward reference to "
4722 "function as global value!");
4723 if (Fn->getType() != PFT)
4724 return Error(FRVI->second.second, "invalid forward reference to "
4725 "function '" + FunctionName + "' with wrong type!");
4727 ForwardRefVals.erase(FRVI);
4728 } else if ((Fn = M->getFunction(FunctionName))) {
4729 // Reject redefinitions.
4730 return Error(NameLoc, "invalid redefinition of function '" +
4731 FunctionName + "'");
4732 } else if (M->getNamedValue(FunctionName)) {
4733 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4737 // If this is a definition of a forward referenced function, make sure the
4739 auto I = ForwardRefValIDs.find(NumberedVals.size());
4740 if (I != ForwardRefValIDs.end()) {
4741 Fn = cast<Function>(I->second.first);
4742 if (Fn->getType() != PFT)
4743 return Error(NameLoc, "type of definition and forward reference of '@" +
4744 Twine(NumberedVals.size()) + "' disagree");
4745 ForwardRefValIDs.erase(I);
4750 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4751 else // Move the forward-reference to the correct spot in the module.
4752 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4754 if (FunctionName.empty())
4755 NumberedVals.push_back(Fn);
4757 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4758 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4759 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4760 Fn->setCallingConv(CC);
4761 Fn->setAttributes(PAL);
4762 Fn->setUnnamedAddr(UnnamedAddr);
4763 Fn->setAlignment(Alignment);
4764 Fn->setSection(Section);
4766 Fn->setPersonalityFn(PersonalityFn);
4767 if (!GC.empty()) Fn->setGC(GC);
4768 Fn->setPrefixData(Prefix);
4769 Fn->setPrologueData(Prologue);
4770 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4772 // Add all of the arguments we parsed to the function.
4773 Function::arg_iterator ArgIt = Fn->arg_begin();
4774 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4775 // If the argument has a name, insert it into the argument symbol table.
4776 if (ArgList[i].Name.empty()) continue;
4778 // Set the name, if it conflicted, it will be auto-renamed.
4779 ArgIt->setName(ArgList[i].Name);
4781 if (ArgIt->getName() != ArgList[i].Name)
4782 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4783 ArgList[i].Name + "'");
4789 // Check the declaration has no block address forward references.
4791 if (FunctionName.empty()) {
4792 ID.Kind = ValID::t_GlobalID;
4793 ID.UIntVal = NumberedVals.size() - 1;
4795 ID.Kind = ValID::t_GlobalName;
4796 ID.StrVal = FunctionName;
4798 auto Blocks = ForwardRefBlockAddresses.find(ID);
4799 if (Blocks != ForwardRefBlockAddresses.end())
4800 return Error(Blocks->first.Loc,
4801 "cannot take blockaddress inside a declaration");
4805 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4807 if (FunctionNumber == -1) {
4808 ID.Kind = ValID::t_GlobalName;
4809 ID.StrVal = F.getName();
4811 ID.Kind = ValID::t_GlobalID;
4812 ID.UIntVal = FunctionNumber;
4815 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4816 if (Blocks == P.ForwardRefBlockAddresses.end())
4819 for (const auto &I : Blocks->second) {
4820 const ValID &BBID = I.first;
4821 GlobalValue *GV = I.second;
4823 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4824 "Expected local id or name");
4826 if (BBID.Kind == ValID::t_LocalName)
4827 BB = GetBB(BBID.StrVal, BBID.Loc);
4829 BB = GetBB(BBID.UIntVal, BBID.Loc);
4831 return P.Error(BBID.Loc, "referenced value is not a basic block");
4833 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4834 GV->eraseFromParent();
4837 P.ForwardRefBlockAddresses.erase(Blocks);
4841 /// ParseFunctionBody
4842 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4843 bool LLParser::ParseFunctionBody(Function &Fn) {
4844 if (Lex.getKind() != lltok::lbrace)
4845 return TokError("expected '{' in function body");
4846 Lex.Lex(); // eat the {.
4848 int FunctionNumber = -1;
4849 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4851 PerFunctionState PFS(*this, Fn, FunctionNumber);
4853 // Resolve block addresses and allow basic blocks to be forward-declared
4854 // within this function.
4855 if (PFS.resolveForwardRefBlockAddresses())
4857 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4859 // We need at least one basic block.
4860 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4861 return TokError("function body requires at least one basic block");
4863 while (Lex.getKind() != lltok::rbrace &&
4864 Lex.getKind() != lltok::kw_uselistorder)
4865 if (ParseBasicBlock(PFS)) return true;
4867 while (Lex.getKind() != lltok::rbrace)
4868 if (ParseUseListOrder(&PFS))
4874 // Verify function is ok.
4875 return PFS.FinishFunction();
4879 /// ::= LabelStr? Instruction*
4880 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4881 // If this basic block starts out with a name, remember it.
4883 LocTy NameLoc = Lex.getLoc();
4884 if (Lex.getKind() == lltok::LabelStr) {
4885 Name = Lex.getStrVal();
4889 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4891 return Error(NameLoc,
4892 "unable to create block named '" + Name + "'");
4894 std::string NameStr;
4896 // Parse the instructions in this block until we get a terminator.
4899 // This instruction may have three possibilities for a name: a) none
4900 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4901 LocTy NameLoc = Lex.getLoc();
4905 if (Lex.getKind() == lltok::LocalVarID) {
4906 NameID = Lex.getUIntVal();
4908 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4910 } else if (Lex.getKind() == lltok::LocalVar) {
4911 NameStr = Lex.getStrVal();
4913 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4917 switch (ParseInstruction(Inst, BB, PFS)) {
4918 default: llvm_unreachable("Unknown ParseInstruction result!");
4919 case InstError: return true;
4921 BB->getInstList().push_back(Inst);
4923 // With a normal result, we check to see if the instruction is followed by
4924 // a comma and metadata.
4925 if (EatIfPresent(lltok::comma))
4926 if (ParseInstructionMetadata(*Inst))
4929 case InstExtraComma:
4930 BB->getInstList().push_back(Inst);
4932 // If the instruction parser ate an extra comma at the end of it, it
4933 // *must* be followed by metadata.
4934 if (ParseInstructionMetadata(*Inst))
4939 // Set the name on the instruction.
4940 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4941 } while (!isa<TerminatorInst>(Inst));
4946 //===----------------------------------------------------------------------===//
4947 // Instruction Parsing.
4948 //===----------------------------------------------------------------------===//
4950 /// ParseInstruction - Parse one of the many different instructions.
4952 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4953 PerFunctionState &PFS) {
4954 lltok::Kind Token = Lex.getKind();
4955 if (Token == lltok::Eof)
4956 return TokError("found end of file when expecting more instructions");
4957 LocTy Loc = Lex.getLoc();
4958 unsigned KeywordVal = Lex.getUIntVal();
4959 Lex.Lex(); // Eat the keyword.
4962 default: return Error(Loc, "expected instruction opcode");
4963 // Terminator Instructions.
4964 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4965 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4966 case lltok::kw_br: return ParseBr(Inst, PFS);
4967 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4968 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4969 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4970 case lltok::kw_resume: return ParseResume(Inst, PFS);
4971 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
4972 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
4973 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
4974 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
4975 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
4976 // Binary Operators.
4980 case lltok::kw_shl: {
4981 bool NUW = EatIfPresent(lltok::kw_nuw);
4982 bool NSW = EatIfPresent(lltok::kw_nsw);
4983 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4985 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4987 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4988 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4991 case lltok::kw_fadd:
4992 case lltok::kw_fsub:
4993 case lltok::kw_fmul:
4994 case lltok::kw_fdiv:
4995 case lltok::kw_frem: {
4996 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4997 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5001 Inst->setFastMathFlags(FMF);
5005 case lltok::kw_sdiv:
5006 case lltok::kw_udiv:
5007 case lltok::kw_lshr:
5008 case lltok::kw_ashr: {
5009 bool Exact = EatIfPresent(lltok::kw_exact);
5011 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5012 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5016 case lltok::kw_urem:
5017 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5020 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5021 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5022 case lltok::kw_fcmp: {
5023 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5024 int Res = ParseCompare(Inst, PFS, KeywordVal);
5028 Inst->setFastMathFlags(FMF);
5033 case lltok::kw_trunc:
5034 case lltok::kw_zext:
5035 case lltok::kw_sext:
5036 case lltok::kw_fptrunc:
5037 case lltok::kw_fpext:
5038 case lltok::kw_bitcast:
5039 case lltok::kw_addrspacecast:
5040 case lltok::kw_uitofp:
5041 case lltok::kw_sitofp:
5042 case lltok::kw_fptoui:
5043 case lltok::kw_fptosi:
5044 case lltok::kw_inttoptr:
5045 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5047 case lltok::kw_select: return ParseSelect(Inst, PFS);
5048 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5049 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5050 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5051 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5052 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5053 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5055 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5056 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5057 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5058 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5060 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5061 case lltok::kw_load: return ParseLoad(Inst, PFS);
5062 case lltok::kw_store: return ParseStore(Inst, PFS);
5063 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5064 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5065 case lltok::kw_fence: return ParseFence(Inst, PFS);
5066 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5067 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5068 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5072 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5073 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5074 if (Opc == Instruction::FCmp) {
5075 switch (Lex.getKind()) {
5076 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5077 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5078 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5079 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5080 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5081 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5082 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5083 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5084 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5085 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5086 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5087 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5088 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5089 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5090 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5091 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5092 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5095 switch (Lex.getKind()) {
5096 default: return TokError("expected icmp predicate (e.g. 'eq')");
5097 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5098 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5099 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5100 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5101 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5102 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5103 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5104 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5105 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5106 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5113 //===----------------------------------------------------------------------===//
5114 // Terminator Instructions.
5115 //===----------------------------------------------------------------------===//
5117 /// ParseRet - Parse a return instruction.
5118 /// ::= 'ret' void (',' !dbg, !1)*
5119 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5120 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5121 PerFunctionState &PFS) {
5122 SMLoc TypeLoc = Lex.getLoc();
5124 if (ParseType(Ty, true /*void allowed*/)) return true;
5126 Type *ResType = PFS.getFunction().getReturnType();
5128 if (Ty->isVoidTy()) {
5129 if (!ResType->isVoidTy())
5130 return Error(TypeLoc, "value doesn't match function result type '" +
5131 getTypeString(ResType) + "'");
5133 Inst = ReturnInst::Create(Context);
5138 if (ParseValue(Ty, RV, PFS)) return true;
5140 if (ResType != RV->getType())
5141 return Error(TypeLoc, "value doesn't match function result type '" +
5142 getTypeString(ResType) + "'");
5144 Inst = ReturnInst::Create(Context, RV);
5149 /// ::= 'br' TypeAndValue
5150 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5151 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5154 BasicBlock *Op1, *Op2;
5155 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5157 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5158 Inst = BranchInst::Create(BB);
5162 if (Op0->getType() != Type::getInt1Ty(Context))
5163 return Error(Loc, "branch condition must have 'i1' type");
5165 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5166 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5167 ParseToken(lltok::comma, "expected ',' after true destination") ||
5168 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5171 Inst = BranchInst::Create(Op1, Op2, Op0);
5177 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5179 /// ::= (TypeAndValue ',' TypeAndValue)*
5180 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5181 LocTy CondLoc, BBLoc;
5183 BasicBlock *DefaultBB;
5184 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5185 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5186 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5187 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5190 if (!Cond->getType()->isIntegerTy())
5191 return Error(CondLoc, "switch condition must have integer type");
5193 // Parse the jump table pairs.
5194 SmallPtrSet<Value*, 32> SeenCases;
5195 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5196 while (Lex.getKind() != lltok::rsquare) {
5200 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5201 ParseToken(lltok::comma, "expected ',' after case value") ||
5202 ParseTypeAndBasicBlock(DestBB, PFS))
5205 if (!SeenCases.insert(Constant).second)
5206 return Error(CondLoc, "duplicate case value in switch");
5207 if (!isa<ConstantInt>(Constant))
5208 return Error(CondLoc, "case value is not a constant integer");
5210 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5213 Lex.Lex(); // Eat the ']'.
5215 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5216 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5217 SI->addCase(Table[i].first, Table[i].second);
5224 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5225 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5228 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5229 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5230 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5233 if (!Address->getType()->isPointerTy())
5234 return Error(AddrLoc, "indirectbr address must have pointer type");
5236 // Parse the destination list.
5237 SmallVector<BasicBlock*, 16> DestList;
5239 if (Lex.getKind() != lltok::rsquare) {
5241 if (ParseTypeAndBasicBlock(DestBB, PFS))
5243 DestList.push_back(DestBB);
5245 while (EatIfPresent(lltok::comma)) {
5246 if (ParseTypeAndBasicBlock(DestBB, PFS))
5248 DestList.push_back(DestBB);
5252 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5255 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5256 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5257 IBI->addDestination(DestList[i]);
5263 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5264 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5265 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5266 LocTy CallLoc = Lex.getLoc();
5267 AttrBuilder RetAttrs, FnAttrs;
5268 std::vector<unsigned> FwdRefAttrGrps;
5271 Type *RetType = nullptr;
5274 SmallVector<ParamInfo, 16> ArgList;
5275 SmallVector<OperandBundleDef, 2> BundleList;
5277 BasicBlock *NormalBB, *UnwindBB;
5278 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5279 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5280 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5281 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5283 ParseOptionalOperandBundles(BundleList, PFS) ||
5284 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5285 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5286 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5287 ParseTypeAndBasicBlock(UnwindBB, PFS))
5290 // If RetType is a non-function pointer type, then this is the short syntax
5291 // for the call, which means that RetType is just the return type. Infer the
5292 // rest of the function argument types from the arguments that are present.
5293 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5295 // Pull out the types of all of the arguments...
5296 std::vector<Type*> ParamTypes;
5297 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5298 ParamTypes.push_back(ArgList[i].V->getType());
5300 if (!FunctionType::isValidReturnType(RetType))
5301 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5303 Ty = FunctionType::get(RetType, ParamTypes, false);
5308 // Look up the callee.
5310 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5313 // Set up the Attribute for the function.
5314 SmallVector<AttributeSet, 8> Attrs;
5315 if (RetAttrs.hasAttributes())
5316 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5317 AttributeSet::ReturnIndex,
5320 SmallVector<Value*, 8> Args;
5322 // Loop through FunctionType's arguments and ensure they are specified
5323 // correctly. Also, gather any parameter attributes.
5324 FunctionType::param_iterator I = Ty->param_begin();
5325 FunctionType::param_iterator E = Ty->param_end();
5326 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5327 Type *ExpectedTy = nullptr;
5330 } else if (!Ty->isVarArg()) {
5331 return Error(ArgList[i].Loc, "too many arguments specified");
5334 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5335 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5336 getTypeString(ExpectedTy) + "'");
5337 Args.push_back(ArgList[i].V);
5338 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5339 AttrBuilder B(ArgList[i].Attrs, i + 1);
5340 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5345 return Error(CallLoc, "not enough parameters specified for call");
5347 if (FnAttrs.hasAttributes()) {
5348 if (FnAttrs.hasAlignmentAttr())
5349 return Error(CallLoc, "invoke instructions may not have an alignment");
5351 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5352 AttributeSet::FunctionIndex,
5356 // Finish off the Attribute and check them
5357 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5360 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5361 II->setCallingConv(CC);
5362 II->setAttributes(PAL);
5363 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5369 /// ::= 'resume' TypeAndValue
5370 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5371 Value *Exn; LocTy ExnLoc;
5372 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5375 ResumeInst *RI = ResumeInst::Create(Exn);
5380 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5381 PerFunctionState &PFS) {
5382 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5385 while (Lex.getKind() != lltok::rsquare) {
5386 // If this isn't the first argument, we need a comma.
5387 if (!Args.empty() &&
5388 ParseToken(lltok::comma, "expected ',' in argument list"))
5391 // Parse the argument.
5393 Type *ArgTy = nullptr;
5394 if (ParseType(ArgTy, ArgLoc))
5398 if (ArgTy->isMetadataTy()) {
5399 if (ParseMetadataAsValue(V, PFS))
5402 if (ParseValue(ArgTy, V, PFS))
5408 Lex.Lex(); // Lex the ']'.
5413 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
5414 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
5415 Value *CleanupPad = nullptr;
5417 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
5420 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
5423 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
5426 BasicBlock *UnwindBB = nullptr;
5427 if (Lex.getKind() == lltok::kw_to) {
5429 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
5432 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5437 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
5442 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
5443 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
5444 Value *CatchPad = nullptr;
5446 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
5449 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
5453 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
5454 ParseTypeAndBasicBlock(BB, PFS))
5457 Inst = CatchReturnInst::Create(CatchPad, BB);
5461 /// ParseCatchSwitch
5462 /// ::= 'catchswitch' within Parent
5463 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5467 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
5470 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5471 Lex.getKind() != lltok::LocalVarID)
5472 return TokError("expected scope value for catchswitch");
5474 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5477 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
5480 SmallVector<BasicBlock *, 32> Table;
5483 if (ParseTypeAndBasicBlock(DestBB, PFS))
5485 Table.push_back(DestBB);
5486 } while (EatIfPresent(lltok::comma));
5488 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
5491 if (ParseToken(lltok::kw_unwind,
5492 "expected 'unwind' after catchswitch scope"))
5495 BasicBlock *UnwindBB = nullptr;
5496 if (EatIfPresent(lltok::kw_to)) {
5497 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
5500 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5505 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
5506 for (BasicBlock *DestBB : Table)
5507 CatchSwitch->addHandler(DestBB);
5513 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
5514 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
5515 Value *CatchSwitch = nullptr;
5517 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
5520 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
5521 return TokError("expected scope value for catchpad");
5523 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
5526 SmallVector<Value *, 8> Args;
5527 if (ParseExceptionArgs(Args, PFS))
5530 Inst = CatchPadInst::Create(CatchSwitch, Args);
5535 /// ::= 'cleanuppad' within Parent ParamList
5536 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
5537 Value *ParentPad = nullptr;
5539 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
5542 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
5543 Lex.getKind() != lltok::LocalVarID)
5544 return TokError("expected scope value for cleanuppad");
5546 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
5549 SmallVector<Value *, 8> Args;
5550 if (ParseExceptionArgs(Args, PFS))
5553 Inst = CleanupPadInst::Create(ParentPad, Args);
5557 //===----------------------------------------------------------------------===//
5558 // Binary Operators.
5559 //===----------------------------------------------------------------------===//
5562 /// ::= ArithmeticOps TypeAndValue ',' Value
5564 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
5565 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
5566 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
5567 unsigned Opc, unsigned OperandType) {
5568 LocTy Loc; Value *LHS, *RHS;
5569 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5570 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
5571 ParseValue(LHS->getType(), RHS, PFS))
5575 switch (OperandType) {
5576 default: llvm_unreachable("Unknown operand type!");
5577 case 0: // int or FP.
5578 Valid = LHS->getType()->isIntOrIntVectorTy() ||
5579 LHS->getType()->isFPOrFPVectorTy();
5581 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
5582 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
5586 return Error(Loc, "invalid operand type for instruction");
5588 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5593 /// ::= ArithmeticOps TypeAndValue ',' Value {
5594 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
5596 LocTy Loc; Value *LHS, *RHS;
5597 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5598 ParseToken(lltok::comma, "expected ',' in logical operation") ||
5599 ParseValue(LHS->getType(), RHS, PFS))
5602 if (!LHS->getType()->isIntOrIntVectorTy())
5603 return Error(Loc,"instruction requires integer or integer vector operands");
5605 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5610 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
5611 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
5612 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
5614 // Parse the integer/fp comparison predicate.
5618 if (ParseCmpPredicate(Pred, Opc) ||
5619 ParseTypeAndValue(LHS, Loc, PFS) ||
5620 ParseToken(lltok::comma, "expected ',' after compare value") ||
5621 ParseValue(LHS->getType(), RHS, PFS))
5624 if (Opc == Instruction::FCmp) {
5625 if (!LHS->getType()->isFPOrFPVectorTy())
5626 return Error(Loc, "fcmp requires floating point operands");
5627 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5629 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
5630 if (!LHS->getType()->isIntOrIntVectorTy() &&
5631 !LHS->getType()->getScalarType()->isPointerTy())
5632 return Error(Loc, "icmp requires integer operands");
5633 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
5638 //===----------------------------------------------------------------------===//
5639 // Other Instructions.
5640 //===----------------------------------------------------------------------===//
5644 /// ::= CastOpc TypeAndValue 'to' Type
5645 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
5649 Type *DestTy = nullptr;
5650 if (ParseTypeAndValue(Op, Loc, PFS) ||
5651 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
5655 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
5656 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
5657 return Error(Loc, "invalid cast opcode for cast from '" +
5658 getTypeString(Op->getType()) + "' to '" +
5659 getTypeString(DestTy) + "'");
5661 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
5666 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5667 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
5669 Value *Op0, *Op1, *Op2;
5670 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5671 ParseToken(lltok::comma, "expected ',' after select condition") ||
5672 ParseTypeAndValue(Op1, PFS) ||
5673 ParseToken(lltok::comma, "expected ',' after select value") ||
5674 ParseTypeAndValue(Op2, PFS))
5677 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
5678 return Error(Loc, Reason);
5680 Inst = SelectInst::Create(Op0, Op1, Op2);
5685 /// ::= 'va_arg' TypeAndValue ',' Type
5686 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
5688 Type *EltTy = nullptr;
5690 if (ParseTypeAndValue(Op, PFS) ||
5691 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
5692 ParseType(EltTy, TypeLoc))
5695 if (!EltTy->isFirstClassType())
5696 return Error(TypeLoc, "va_arg requires operand with first class type");
5698 Inst = new VAArgInst(Op, EltTy);
5702 /// ParseExtractElement
5703 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
5704 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5707 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5708 ParseToken(lltok::comma, "expected ',' after extract value") ||
5709 ParseTypeAndValue(Op1, PFS))
5712 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5713 return Error(Loc, "invalid extractelement operands");
5715 Inst = ExtractElementInst::Create(Op0, Op1);
5719 /// ParseInsertElement
5720 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5721 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5723 Value *Op0, *Op1, *Op2;
5724 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5725 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5726 ParseTypeAndValue(Op1, PFS) ||
5727 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5728 ParseTypeAndValue(Op2, PFS))
5731 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5732 return Error(Loc, "invalid insertelement operands");
5734 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5738 /// ParseShuffleVector
5739 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5740 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5742 Value *Op0, *Op1, *Op2;
5743 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5744 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5745 ParseTypeAndValue(Op1, PFS) ||
5746 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5747 ParseTypeAndValue(Op2, PFS))
5750 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5751 return Error(Loc, "invalid shufflevector operands");
5753 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5758 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5759 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5760 Type *Ty = nullptr; LocTy TypeLoc;
5763 if (ParseType(Ty, TypeLoc) ||
5764 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5765 ParseValue(Ty, Op0, PFS) ||
5766 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5767 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5768 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5771 bool AteExtraComma = false;
5772 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5775 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5777 if (!EatIfPresent(lltok::comma))
5780 if (Lex.getKind() == lltok::MetadataVar) {
5781 AteExtraComma = true;
5785 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5786 ParseValue(Ty, Op0, PFS) ||
5787 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5788 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5789 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5793 if (!Ty->isFirstClassType())
5794 return Error(TypeLoc, "phi node must have first class type");
5796 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5797 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5798 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5800 return AteExtraComma ? InstExtraComma : InstNormal;
5804 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5806 /// ::= 'catch' TypeAndValue
5808 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5809 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5810 Type *Ty = nullptr; LocTy TyLoc;
5812 if (ParseType(Ty, TyLoc))
5815 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
5816 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5818 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5819 LandingPadInst::ClauseType CT;
5820 if (EatIfPresent(lltok::kw_catch))
5821 CT = LandingPadInst::Catch;
5822 else if (EatIfPresent(lltok::kw_filter))
5823 CT = LandingPadInst::Filter;
5825 return TokError("expected 'catch' or 'filter' clause type");
5829 if (ParseTypeAndValue(V, VLoc, PFS))
5832 // A 'catch' type expects a non-array constant. A filter clause expects an
5834 if (CT == LandingPadInst::Catch) {
5835 if (isa<ArrayType>(V->getType()))
5836 Error(VLoc, "'catch' clause has an invalid type");
5838 if (!isa<ArrayType>(V->getType()))
5839 Error(VLoc, "'filter' clause has an invalid type");
5842 Constant *CV = dyn_cast<Constant>(V);
5844 return Error(VLoc, "clause argument must be a constant");
5848 Inst = LP.release();
5853 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
5854 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5855 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
5856 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5857 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
5858 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5859 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
5860 /// OptionalAttrs Type Value ParameterList OptionalAttrs
5861 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5862 CallInst::TailCallKind TCK) {
5863 AttrBuilder RetAttrs, FnAttrs;
5864 std::vector<unsigned> FwdRefAttrGrps;
5867 Type *RetType = nullptr;
5870 SmallVector<ParamInfo, 16> ArgList;
5871 SmallVector<OperandBundleDef, 2> BundleList;
5872 LocTy CallLoc = Lex.getLoc();
5874 if (TCK != CallInst::TCK_None &&
5875 ParseToken(lltok::kw_call,
5876 "expected 'tail call', 'musttail call', or 'notail call'"))
5879 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5881 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5882 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5883 ParseValID(CalleeID) ||
5884 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5885 PFS.getFunction().isVarArg()) ||
5886 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
5887 ParseOptionalOperandBundles(BundleList, PFS))
5890 if (FMF.any() && !RetType->isFPOrFPVectorTy())
5891 return Error(CallLoc, "fast-math-flags specified for call without "
5892 "floating-point scalar or vector return type");
5894 // If RetType is a non-function pointer type, then this is the short syntax
5895 // for the call, which means that RetType is just the return type. Infer the
5896 // rest of the function argument types from the arguments that are present.
5897 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5899 // Pull out the types of all of the arguments...
5900 std::vector<Type*> ParamTypes;
5901 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5902 ParamTypes.push_back(ArgList[i].V->getType());
5904 if (!FunctionType::isValidReturnType(RetType))
5905 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5907 Ty = FunctionType::get(RetType, ParamTypes, false);
5912 // Look up the callee.
5914 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5917 // Set up the Attribute for the function.
5918 SmallVector<AttributeSet, 8> Attrs;
5919 if (RetAttrs.hasAttributes())
5920 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5921 AttributeSet::ReturnIndex,
5924 SmallVector<Value*, 8> Args;
5926 // Loop through FunctionType's arguments and ensure they are specified
5927 // correctly. Also, gather any parameter attributes.
5928 FunctionType::param_iterator I = Ty->param_begin();
5929 FunctionType::param_iterator E = Ty->param_end();
5930 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5931 Type *ExpectedTy = nullptr;
5934 } else if (!Ty->isVarArg()) {
5935 return Error(ArgList[i].Loc, "too many arguments specified");
5938 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5939 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5940 getTypeString(ExpectedTy) + "'");
5941 Args.push_back(ArgList[i].V);
5942 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5943 AttrBuilder B(ArgList[i].Attrs, i + 1);
5944 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5949 return Error(CallLoc, "not enough parameters specified for call");
5951 if (FnAttrs.hasAttributes()) {
5952 if (FnAttrs.hasAlignmentAttr())
5953 return Error(CallLoc, "call instructions may not have an alignment");
5955 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5956 AttributeSet::FunctionIndex,
5960 // Finish off the Attribute and check them
5961 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5963 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
5964 CI->setTailCallKind(TCK);
5965 CI->setCallingConv(CC);
5967 CI->setFastMathFlags(FMF);
5968 CI->setAttributes(PAL);
5969 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5974 //===----------------------------------------------------------------------===//
5975 // Memory Instructions.
5976 //===----------------------------------------------------------------------===//
5979 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
5980 /// (',' 'align' i32)?
5981 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5982 Value *Size = nullptr;
5983 LocTy SizeLoc, TyLoc;
5984 unsigned Alignment = 0;
5987 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5988 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
5990 if (ParseType(Ty, TyLoc)) return true;
5992 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5993 return Error(TyLoc, "invalid type for alloca");
5995 bool AteExtraComma = false;
5996 if (EatIfPresent(lltok::comma)) {
5997 if (Lex.getKind() == lltok::kw_align) {
5998 if (ParseOptionalAlignment(Alignment)) return true;
5999 } else if (Lex.getKind() == lltok::MetadataVar) {
6000 AteExtraComma = true;
6002 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6003 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6008 if (Size && !Size->getType()->isIntegerTy())
6009 return Error(SizeLoc, "element count must have integer type");
6011 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
6012 AI->setUsedWithInAlloca(IsInAlloca);
6013 AI->setSwiftError(IsSwiftError);
6015 return AteExtraComma ? InstExtraComma : InstNormal;
6019 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6020 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6021 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6022 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6023 Value *Val; LocTy Loc;
6024 unsigned Alignment = 0;
6025 bool AteExtraComma = false;
6026 bool isAtomic = false;
6027 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6028 SynchronizationScope Scope = CrossThread;
6030 if (Lex.getKind() == lltok::kw_atomic) {
6035 bool isVolatile = false;
6036 if (Lex.getKind() == lltok::kw_volatile) {
6042 LocTy ExplicitTypeLoc = Lex.getLoc();
6043 if (ParseType(Ty) ||
6044 ParseToken(lltok::comma, "expected comma after load's type") ||
6045 ParseTypeAndValue(Val, Loc, PFS) ||
6046 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6047 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6050 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6051 return Error(Loc, "load operand must be a pointer to a first class type");
6052 if (isAtomic && !Alignment)
6053 return Error(Loc, "atomic load must have explicit non-zero alignment");
6054 if (Ordering == AtomicOrdering::Release ||
6055 Ordering == AtomicOrdering::AcquireRelease)
6056 return Error(Loc, "atomic load cannot use Release ordering");
6058 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6059 return Error(ExplicitTypeLoc,
6060 "explicit pointee type doesn't match operand's pointee type");
6062 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
6063 return AteExtraComma ? InstExtraComma : InstNormal;
6068 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6069 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6070 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6071 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6072 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6073 unsigned Alignment = 0;
6074 bool AteExtraComma = false;
6075 bool isAtomic = false;
6076 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6077 SynchronizationScope Scope = CrossThread;
6079 if (Lex.getKind() == lltok::kw_atomic) {
6084 bool isVolatile = false;
6085 if (Lex.getKind() == lltok::kw_volatile) {
6090 if (ParseTypeAndValue(Val, Loc, PFS) ||
6091 ParseToken(lltok::comma, "expected ',' after store operand") ||
6092 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6093 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6094 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6097 if (!Ptr->getType()->isPointerTy())
6098 return Error(PtrLoc, "store operand must be a pointer");
6099 if (!Val->getType()->isFirstClassType())
6100 return Error(Loc, "store operand must be a first class value");
6101 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6102 return Error(Loc, "stored value and pointer type do not match");
6103 if (isAtomic && !Alignment)
6104 return Error(Loc, "atomic store must have explicit non-zero alignment");
6105 if (Ordering == AtomicOrdering::Acquire ||
6106 Ordering == AtomicOrdering::AcquireRelease)
6107 return Error(Loc, "atomic store cannot use Acquire ordering");
6109 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6110 return AteExtraComma ? InstExtraComma : InstNormal;
6114 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6115 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6116 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6117 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6118 bool AteExtraComma = false;
6119 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6120 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6121 SynchronizationScope Scope = CrossThread;
6122 bool isVolatile = false;
6123 bool isWeak = false;
6125 if (EatIfPresent(lltok::kw_weak))
6128 if (EatIfPresent(lltok::kw_volatile))
6131 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6132 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6133 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6134 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6135 ParseTypeAndValue(New, NewLoc, PFS) ||
6136 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
6137 ParseOrdering(FailureOrdering))
6140 if (SuccessOrdering == AtomicOrdering::Unordered ||
6141 FailureOrdering == AtomicOrdering::Unordered)
6142 return TokError("cmpxchg cannot be unordered");
6143 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6144 return TokError("cmpxchg failure argument shall be no stronger than the "
6145 "success argument");
6146 if (FailureOrdering == AtomicOrdering::Release ||
6147 FailureOrdering == AtomicOrdering::AcquireRelease)
6149 "cmpxchg failure ordering cannot include release semantics");
6150 if (!Ptr->getType()->isPointerTy())
6151 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6152 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6153 return Error(CmpLoc, "compare value and pointer type do not match");
6154 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6155 return Error(NewLoc, "new value and pointer type do not match");
6156 if (!New->getType()->isFirstClassType())
6157 return Error(NewLoc, "cmpxchg operand must be a first class value");
6158 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6159 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6160 CXI->setVolatile(isVolatile);
6161 CXI->setWeak(isWeak);
6163 return AteExtraComma ? InstExtraComma : InstNormal;
6167 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6168 /// 'singlethread'? AtomicOrdering
6169 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6170 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6171 bool AteExtraComma = false;
6172 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6173 SynchronizationScope Scope = CrossThread;
6174 bool isVolatile = false;
6175 AtomicRMWInst::BinOp Operation;
6177 if (EatIfPresent(lltok::kw_volatile))
6180 switch (Lex.getKind()) {
6181 default: return TokError("expected binary operation in atomicrmw");
6182 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6183 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6184 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6185 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6186 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6187 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6188 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6189 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6190 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6191 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6192 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6194 Lex.Lex(); // Eat the operation.
6196 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6197 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6198 ParseTypeAndValue(Val, ValLoc, PFS) ||
6199 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6202 if (Ordering == AtomicOrdering::Unordered)
6203 return TokError("atomicrmw cannot be unordered");
6204 if (!Ptr->getType()->isPointerTy())
6205 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6206 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6207 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6208 if (!Val->getType()->isIntegerTy())
6209 return Error(ValLoc, "atomicrmw operand must be an integer");
6210 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
6211 if (Size < 8 || (Size & (Size - 1)))
6212 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
6215 AtomicRMWInst *RMWI =
6216 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
6217 RMWI->setVolatile(isVolatile);
6219 return AteExtraComma ? InstExtraComma : InstNormal;
6223 /// ::= 'fence' 'singlethread'? AtomicOrdering
6224 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
6225 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6226 SynchronizationScope Scope = CrossThread;
6227 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
6230 if (Ordering == AtomicOrdering::Unordered)
6231 return TokError("fence cannot be unordered");
6232 if (Ordering == AtomicOrdering::Monotonic)
6233 return TokError("fence cannot be monotonic");
6235 Inst = new FenceInst(Context, Ordering, Scope);
6239 /// ParseGetElementPtr
6240 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6241 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
6242 Value *Ptr = nullptr;
6243 Value *Val = nullptr;
6246 bool InBounds = EatIfPresent(lltok::kw_inbounds);
6249 LocTy ExplicitTypeLoc = Lex.getLoc();
6250 if (ParseType(Ty) ||
6251 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
6252 ParseTypeAndValue(Ptr, Loc, PFS))
6255 Type *BaseType = Ptr->getType();
6256 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
6257 if (!BasePointerType)
6258 return Error(Loc, "base of getelementptr must be a pointer");
6260 if (Ty != BasePointerType->getElementType())
6261 return Error(ExplicitTypeLoc,
6262 "explicit pointee type doesn't match operand's pointee type");
6264 SmallVector<Value*, 16> Indices;
6265 bool AteExtraComma = false;
6266 // GEP returns a vector of pointers if at least one of parameters is a vector.
6267 // All vector parameters should have the same vector width.
6268 unsigned GEPWidth = BaseType->isVectorTy() ?
6269 BaseType->getVectorNumElements() : 0;
6271 while (EatIfPresent(lltok::comma)) {
6272 if (Lex.getKind() == lltok::MetadataVar) {
6273 AteExtraComma = true;
6276 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
6277 if (!Val->getType()->getScalarType()->isIntegerTy())
6278 return Error(EltLoc, "getelementptr index must be an integer");
6280 if (Val->getType()->isVectorTy()) {
6281 unsigned ValNumEl = Val->getType()->getVectorNumElements();
6282 if (GEPWidth && GEPWidth != ValNumEl)
6283 return Error(EltLoc,
6284 "getelementptr vector index has a wrong number of elements");
6285 GEPWidth = ValNumEl;
6287 Indices.push_back(Val);
6290 SmallPtrSet<Type*, 4> Visited;
6291 if (!Indices.empty() && !Ty->isSized(&Visited))
6292 return Error(Loc, "base element of getelementptr must be sized");
6294 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
6295 return Error(Loc, "invalid getelementptr indices");
6296 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
6298 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
6299 return AteExtraComma ? InstExtraComma : InstNormal;
6302 /// ParseExtractValue
6303 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6304 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
6305 Value *Val; LocTy Loc;
6306 SmallVector<unsigned, 4> Indices;
6308 if (ParseTypeAndValue(Val, Loc, PFS) ||
6309 ParseIndexList(Indices, AteExtraComma))
6312 if (!Val->getType()->isAggregateType())
6313 return Error(Loc, "extractvalue operand must be aggregate type");
6315 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
6316 return Error(Loc, "invalid indices for extractvalue");
6317 Inst = ExtractValueInst::Create(Val, Indices);
6318 return AteExtraComma ? InstExtraComma : InstNormal;
6321 /// ParseInsertValue
6322 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6323 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
6324 Value *Val0, *Val1; LocTy Loc0, Loc1;
6325 SmallVector<unsigned, 4> Indices;
6327 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6328 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
6329 ParseTypeAndValue(Val1, Loc1, PFS) ||
6330 ParseIndexList(Indices, AteExtraComma))
6333 if (!Val0->getType()->isAggregateType())
6334 return Error(Loc0, "insertvalue operand must be aggregate type");
6336 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
6338 return Error(Loc0, "invalid indices for insertvalue");
6339 if (IndexedType != Val1->getType())
6340 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
6341 getTypeString(Val1->getType()) + "' instead of '" +
6342 getTypeString(IndexedType) + "'");
6343 Inst = InsertValueInst::Create(Val0, Val1, Indices);
6344 return AteExtraComma ? InstExtraComma : InstNormal;
6347 //===----------------------------------------------------------------------===//
6348 // Embedded metadata.
6349 //===----------------------------------------------------------------------===//
6351 /// ParseMDNodeVector
6352 /// ::= { Element (',' Element)* }
6354 /// ::= 'null' | TypeAndValue
6355 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
6356 if (ParseToken(lltok::lbrace, "expected '{' here"))
6359 // Check for an empty list.
6360 if (EatIfPresent(lltok::rbrace))
6364 // Null is a special case since it is typeless.
6365 if (EatIfPresent(lltok::kw_null)) {
6366 Elts.push_back(nullptr);
6371 if (ParseMetadata(MD, nullptr))
6374 } while (EatIfPresent(lltok::comma));
6376 return ParseToken(lltok::rbrace, "expected end of metadata node");
6379 //===----------------------------------------------------------------------===//
6380 // Use-list order directives.
6381 //===----------------------------------------------------------------------===//
6382 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
6385 return Error(Loc, "value has no uses");
6387 unsigned NumUses = 0;
6388 SmallDenseMap<const Use *, unsigned, 16> Order;
6389 for (const Use &U : V->uses()) {
6390 if (++NumUses > Indexes.size())
6392 Order[&U] = Indexes[NumUses - 1];
6395 return Error(Loc, "value only has one use");
6396 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
6397 return Error(Loc, "wrong number of indexes, expected " +
6398 Twine(std::distance(V->use_begin(), V->use_end())));
6400 V->sortUseList([&](const Use &L, const Use &R) {
6401 return Order.lookup(&L) < Order.lookup(&R);
6406 /// ParseUseListOrderIndexes
6407 /// ::= '{' uint32 (',' uint32)+ '}'
6408 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
6409 SMLoc Loc = Lex.getLoc();
6410 if (ParseToken(lltok::lbrace, "expected '{' here"))
6412 if (Lex.getKind() == lltok::rbrace)
6413 return Lex.Error("expected non-empty list of uselistorder indexes");
6415 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
6416 // indexes should be distinct numbers in the range [0, size-1], and should
6418 unsigned Offset = 0;
6420 bool IsOrdered = true;
6421 assert(Indexes.empty() && "Expected empty order vector");
6424 if (ParseUInt32(Index))
6427 // Update consistency checks.
6428 Offset += Index - Indexes.size();
6429 Max = std::max(Max, Index);
6430 IsOrdered &= Index == Indexes.size();
6432 Indexes.push_back(Index);
6433 } while (EatIfPresent(lltok::comma));
6435 if (ParseToken(lltok::rbrace, "expected '}' here"))
6438 if (Indexes.size() < 2)
6439 return Error(Loc, "expected >= 2 uselistorder indexes");
6440 if (Offset != 0 || Max >= Indexes.size())
6441 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
6443 return Error(Loc, "expected uselistorder indexes to change the order");
6448 /// ParseUseListOrder
6449 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
6450 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6451 SMLoc Loc = Lex.getLoc();
6452 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
6456 SmallVector<unsigned, 16> Indexes;
6457 if (ParseTypeAndValue(V, PFS) ||
6458 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
6459 ParseUseListOrderIndexes(Indexes))
6462 return sortUseListOrder(V, Indexes, Loc);
6465 /// ParseUseListOrderBB
6466 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
6467 bool LLParser::ParseUseListOrderBB() {
6468 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
6469 SMLoc Loc = Lex.getLoc();
6473 SmallVector<unsigned, 16> Indexes;
6474 if (ParseValID(Fn) ||
6475 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6476 ParseValID(Label) ||
6477 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
6478 ParseUseListOrderIndexes(Indexes))
6481 // Check the function.
6483 if (Fn.Kind == ValID::t_GlobalName)
6484 GV = M->getNamedValue(Fn.StrVal);
6485 else if (Fn.Kind == ValID::t_GlobalID)
6486 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
6488 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6490 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
6491 auto *F = dyn_cast<Function>(GV);
6493 return Error(Fn.Loc, "expected function name in uselistorder_bb");
6494 if (F->isDeclaration())
6495 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
6497 // Check the basic block.
6498 if (Label.Kind == ValID::t_LocalID)
6499 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
6500 if (Label.Kind != ValID::t_LocalName)
6501 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
6502 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
6504 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
6505 if (!isa<BasicBlock>(V))
6506 return Error(Label.Loc, "expected basic block in uselistorder_bb");
6508 return sortUseListOrder(V, Indexes, Loc);