1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the parser class for .ll files.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/SlotMapping.h"
20 #include "llvm/BinaryFormat/Dwarf.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/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SaveAndRestore.h"
47 #include "llvm/Support/raw_ostream.h"
56 static std::string getTypeString(Type *T) {
58 raw_string_ostream Tmp(Result);
63 /// Run: module ::= toplevelentity*
64 bool LLParser::Run() {
68 if (Context.shouldDiscardValueNames())
71 "Can't read textual IR with a Context that discards named Values");
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
77 bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
90 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
92 restoreParsingState(Slots);
96 SMLoc Start = Lex.getLoc();
100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
106 void LLParser::restoreParsingState(const SlotMapping *Slots) {
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
113 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114 for (const auto &I : Slots->Types)
115 NumberedTypes.insert(
116 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
119 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121 bool LLParser::ValidateEndOfModule() {
124 // Handle any function attribute group forward references.
125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
133 if (Function *Fn = dyn_cast<Function>(V)) {
134 AttributeList AS = Fn->getAttributes();
135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
140 // If the alignment was parsed as an attribute, move to the alignment
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
147 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
148 AttributeSet::get(Context, FnAttrs));
149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
151 AttributeList AS = CI->getAttributes();
152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 CI->setAttributes(AS);
158 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
159 AttributeList AS = II->getAttributes();
160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
165 II->setAttributes(AS);
166 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
167 AttributeList AS = CBI->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 CBI->setAttributes(AS);
174 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
175 AttrBuilder Attrs(GV->getAttributes());
177 GV->setAttributes(AttributeSet::get(Context,Attrs));
179 llvm_unreachable("invalid object with forward attribute group reference");
183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses.empty())
186 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
187 "expected function name in blockaddress");
189 for (const auto &NT : NumberedTypes)
190 if (NT.second.second.isValid())
191 return Error(NT.second.second,
192 "use of undefined type '%" + Twine(NT.first) + "'");
194 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
195 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
196 if (I->second.second.isValid())
197 return Error(I->second.second,
198 "use of undefined type named '" + I->getKey() + "'");
200 if (!ForwardRefComdats.empty())
201 return Error(ForwardRefComdats.begin()->second,
202 "use of undefined comdat '$" +
203 ForwardRefComdats.begin()->first + "'");
205 if (!ForwardRefVals.empty())
206 return Error(ForwardRefVals.begin()->second.second,
207 "use of undefined value '@" + ForwardRefVals.begin()->first +
210 if (!ForwardRefValIDs.empty())
211 return Error(ForwardRefValIDs.begin()->second.second,
212 "use of undefined value '@" +
213 Twine(ForwardRefValIDs.begin()->first) + "'");
215 if (!ForwardRefMDNodes.empty())
216 return Error(ForwardRefMDNodes.begin()->second.second,
217 "use of undefined metadata '!" +
218 Twine(ForwardRefMDNodes.begin()->first) + "'");
220 // Resolve metadata cycles.
221 for (auto &N : NumberedMetadata) {
222 if (N.second && !N.second->isResolved())
223 N.second->resolveCycles();
226 for (auto *Inst : InstsWithTBAATag) {
227 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
228 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
229 auto *UpgradedMD = UpgradeTBAANode(*MD);
230 if (MD != UpgradedMD)
231 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
236 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
242 Function *F = &*FI++;
243 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
244 F->replaceAllUsesWith(Remangled.getValue());
245 F->eraseFromParent();
249 if (UpgradeDebugInfo)
250 llvm::UpgradeDebugInfo(*M);
252 UpgradeModuleFlags(*M);
253 UpgradeSectionAttributes(*M);
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots->GlobalValues = std::move(NumberedVals);
261 Slots->MetadataNodes = std::move(NumberedMetadata);
262 for (const auto &I : NamedTypes)
263 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
264 for (const auto &I : NumberedTypes)
265 Slots->Types.insert(std::make_pair(I.first, I.second.first));
270 /// Do final validity and sanity checks at the end of the index.
271 bool LLParser::ValidateEndOfIndex() {
275 if (!ForwardRefValueInfos.empty())
276 return Error(ForwardRefValueInfos.begin()->second.front().second,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos.begin()->first) + "'");
280 if (!ForwardRefAliasees.empty())
281 return Error(ForwardRefAliasees.begin()->second.front().second,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees.begin()->first) + "'");
285 if (!ForwardRefTypeIds.empty())
286 return Error(ForwardRefTypeIds.begin()->second.front().second,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds.begin()->first) + "'");
293 //===----------------------------------------------------------------------===//
294 // Top-Level Entities
295 //===----------------------------------------------------------------------===//
297 bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
301 switch (Lex.getKind()) {
304 case lltok::SummaryID:
305 if (ParseSummaryEntry())
308 case lltok::kw_source_filename:
309 if (ParseSourceFileName())
313 // Skip everything else
319 switch (Lex.getKind()) {
320 default: return TokError("expected top-level entity");
321 case lltok::Eof: return false;
322 case lltok::kw_declare: if (ParseDeclare()) return true; break;
323 case lltok::kw_define: if (ParseDefine()) return true; break;
324 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
326 case lltok::kw_source_filename:
327 if (ParseSourceFileName())
330 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
331 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
332 case lltok::LocalVar: if (ParseNamedType()) return true; break;
333 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
334 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
335 case lltok::ComdatVar: if (parseComdat()) return true; break;
336 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
337 case lltok::SummaryID:
338 if (ParseSummaryEntry())
341 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
342 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
343 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb:
345 if (ParseUseListOrderBB())
353 /// ::= 'module' 'asm' STRINGCONSTANT
354 bool LLParser::ParseModuleAsm() {
355 assert(Lex.getKind() == lltok::kw_module);
359 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr)) return true;
362 M->appendModuleInlineAsm(AsmStr);
367 /// ::= 'target' 'triple' '=' STRINGCONSTANT
368 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369 bool LLParser::ParseTargetDefinition() {
370 assert(Lex.getKind() == lltok::kw_target);
373 default: return TokError("unknown target property");
374 case lltok::kw_triple:
376 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377 ParseStringConstant(Str))
379 M->setTargetTriple(Str);
381 case lltok::kw_datalayout:
383 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str))
386 if (DataLayoutStr.empty())
387 M->setDataLayout(Str);
393 /// ::= 'source_filename' '=' STRINGCONSTANT
394 bool LLParser::ParseSourceFileName() {
395 assert(Lex.getKind() == lltok::kw_source_filename);
397 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName))
401 M->setSourceFileName(SourceFileName);
406 /// ::= 'deplibs' '=' '[' ']'
407 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408 /// FIXME: Remove in 4.0. Currently parse, but ignore.
409 bool LLParser::ParseDepLibs() {
410 assert(Lex.getKind() == lltok::kw_deplibs);
412 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
416 if (EatIfPresent(lltok::rsquare))
421 if (ParseStringConstant(Str)) return true;
422 } while (EatIfPresent(lltok::comma));
424 return ParseToken(lltok::rsquare, "expected ']' at end of list");
427 /// ParseUnnamedType:
428 /// ::= LocalVarID '=' 'type' type
429 bool LLParser::ParseUnnamedType() {
430 LocTy TypeLoc = Lex.getLoc();
431 unsigned TypeID = Lex.getUIntVal();
432 Lex.Lex(); // eat LocalVarID;
434 if (ParseToken(lltok::equal, "expected '=' after name") ||
435 ParseToken(lltok::kw_type, "expected 'type' after '='"))
438 Type *Result = nullptr;
439 if (ParseStructDefinition(TypeLoc, "",
440 NumberedTypes[TypeID], Result)) return true;
442 if (!isa<StructType>(Result)) {
443 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
445 return Error(TypeLoc, "non-struct types may not be recursive");
446 Entry.first = Result;
447 Entry.second = SMLoc();
454 /// ::= LocalVar '=' 'type' type
455 bool LLParser::ParseNamedType() {
456 std::string Name = Lex.getStrVal();
457 LocTy NameLoc = Lex.getLoc();
458 Lex.Lex(); // eat LocalVar.
460 if (ParseToken(lltok::equal, "expected '=' after name") ||
461 ParseToken(lltok::kw_type, "expected 'type' after name"))
464 Type *Result = nullptr;
465 if (ParseStructDefinition(NameLoc, Name,
466 NamedTypes[Name], Result)) return true;
468 if (!isa<StructType>(Result)) {
469 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
471 return Error(NameLoc, "non-struct types may not be recursive");
472 Entry.first = Result;
473 Entry.second = SMLoc();
480 /// ::= 'declare' FunctionHeader
481 bool LLParser::ParseDeclare() {
482 assert(Lex.getKind() == lltok::kw_declare);
485 std::vector<std::pair<unsigned, MDNode *>> MDs;
486 while (Lex.getKind() == lltok::MetadataVar) {
489 if (ParseMetadataAttachment(MDK, N))
491 MDs.push_back({MDK, N});
495 if (ParseFunctionHeader(F, false))
498 F->addMetadata(MD.first, *MD.second);
503 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504 bool LLParser::ParseDefine() {
505 assert(Lex.getKind() == lltok::kw_define);
509 return ParseFunctionHeader(F, true) ||
510 ParseOptionalFunctionMetadata(*F) ||
511 ParseFunctionBody(*F);
517 bool LLParser::ParseGlobalType(bool &IsConstant) {
518 if (Lex.getKind() == lltok::kw_constant)
520 else if (Lex.getKind() == lltok::kw_global)
524 return TokError("expected 'global' or 'constant'");
530 bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr &UnnamedAddr) {
532 if (EatIfPresent(lltok::kw_unnamed_addr))
533 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
535 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
537 UnnamedAddr = GlobalValue::UnnamedAddr::None;
541 /// ParseUnnamedGlobal:
542 /// OptionalVisibility (ALIAS | IFUNC) ...
543 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544 /// OptionalDLLStorageClass
545 /// ... -> global variable
546 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548 /// OptionalDLLStorageClass
549 /// ... -> global variable
550 bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID = NumberedVals.size();
553 LocTy NameLoc = Lex.getLoc();
555 // Handle the GlobalID form.
556 if (Lex.getKind() == lltok::GlobalID) {
557 if (Lex.getUIntVal() != VarID)
558 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
560 Lex.Lex(); // eat GlobalID;
562 if (ParseToken(lltok::equal, "expected '=' after name"))
567 unsigned Linkage, Visibility, DLLStorageClass;
569 GlobalVariable::ThreadLocalMode TLM;
570 GlobalVariable::UnnamedAddr UnnamedAddr;
571 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
573 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
576 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
577 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
578 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
580 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
581 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
584 /// ParseNamedGlobal:
585 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587 /// OptionalVisibility OptionalDLLStorageClass
588 /// ... -> global variable
589 bool LLParser::ParseNamedGlobal() {
590 assert(Lex.getKind() == lltok::GlobalVar);
591 LocTy NameLoc = Lex.getLoc();
592 std::string Name = Lex.getStrVal();
596 unsigned Linkage, Visibility, DLLStorageClass;
598 GlobalVariable::ThreadLocalMode TLM;
599 GlobalVariable::UnnamedAddr UnnamedAddr;
600 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
603 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
606 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
607 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
608 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
610 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
611 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
614 bool LLParser::parseComdat() {
615 assert(Lex.getKind() == lltok::ComdatVar);
616 std::string Name = Lex.getStrVal();
617 LocTy NameLoc = Lex.getLoc();
620 if (ParseToken(lltok::equal, "expected '=' here"))
623 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624 return TokError("expected comdat type");
626 Comdat::SelectionKind SK;
627 switch (Lex.getKind()) {
629 return TokError("unknown selection kind");
633 case lltok::kw_exactmatch:
634 SK = Comdat::ExactMatch;
636 case lltok::kw_largest:
637 SK = Comdat::Largest;
639 case lltok::kw_noduplicates:
640 SK = Comdat::NoDuplicates;
642 case lltok::kw_samesize:
643 SK = Comdat::SameSize;
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
651 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
652 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
655 if (I != ComdatSymTab.end())
658 C = M->getOrInsertComdat(Name);
659 C->setSelectionKind(SK);
665 // ::= '!' STRINGCONSTANT
666 bool LLParser::ParseMDString(MDString *&Result) {
668 if (ParseStringConstant(Str)) return true;
669 Result = MDString::get(Context, Str);
674 // ::= '!' MDNodeNumber
675 bool LLParser::ParseMDNodeID(MDNode *&Result) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc = Lex.getLoc();
679 if (ParseUInt32(MID))
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata.count(MID)) {
684 Result = NumberedMetadata[MID];
688 // Otherwise, create MDNode forward reference.
689 auto &FwdRef = ForwardRefMDNodes[MID];
690 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
692 Result = FwdRef.first.get();
693 NumberedMetadata[MID].reset(Result);
697 /// ParseNamedMetadata:
698 /// !foo = !{ !1, !2 }
699 bool LLParser::ParseNamedMetadata() {
700 assert(Lex.getKind() == lltok::MetadataVar);
701 std::string Name = Lex.getStrVal();
704 if (ParseToken(lltok::equal, "expected '=' here") ||
705 ParseToken(lltok::exclaim, "Expected '!' here") ||
706 ParseToken(lltok::lbrace, "Expected '{' here"))
709 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
710 if (Lex.getKind() != lltok::rbrace)
713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex.getKind() == lltok::MetadataVar &&
717 Lex.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N, /*IsDistinct=*/false))
720 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
725 } while (EatIfPresent(lltok::comma));
727 return ParseToken(lltok::rbrace, "expected end of metadata node");
730 /// ParseStandaloneMetadata:
732 bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex.getKind() == lltok::exclaim);
735 unsigned MetadataID = 0;
738 if (ParseUInt32(MetadataID) ||
739 ParseToken(lltok::equal, "expected '=' here"))
742 // Detect common error, from old metadata syntax.
743 if (Lex.getKind() == lltok::Type)
744 return TokError("unexpected type in metadata definition");
746 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
747 if (Lex.getKind() == lltok::MetadataVar) {
748 if (ParseSpecializedMDNode(Init, IsDistinct))
750 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751 ParseMDTuple(Init, IsDistinct))
754 // See if this was forward referenced, if so, handle it.
755 auto FI = ForwardRefMDNodes.find(MetadataID);
756 if (FI != ForwardRefMDNodes.end()) {
757 FI->second.first->replaceAllUsesWith(Init);
758 ForwardRefMDNodes.erase(FI);
760 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
762 if (NumberedMetadata.count(MetadataID))
763 return TokError("Metadata id is already used");
764 NumberedMetadata[MetadataID].reset(Init);
770 // Skips a single module summary entry.
771 bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
776 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
777 Lex.getKind() != lltok::kw_typeid)
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
781 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen = 1;
788 switch (Lex.getKind()) {
796 return TokError("found end of file while parsing summary entry");
798 // Skip everything in between parentheses.
802 } while (NumOpenParen > 0);
807 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808 bool LLParser::ParseSummaryEntry() {
809 assert(Lex.getKind() == lltok::SummaryID);
810 unsigned SummaryID = Lex.getUIntVal();
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex.setIgnoreColonInIdentifiers(true);
817 if (ParseToken(lltok::equal, "expected '=' here"))
820 // If we don't have an index object, skip the summary entry.
822 return SkipModuleSummaryEntry();
825 switch (Lex.getKind()) {
827 result = ParseGVEntry(SummaryID);
829 case lltok::kw_module:
830 result = ParseModuleEntry(SummaryID);
832 case lltok::kw_typeid:
833 result = ParseTypeIdEntry(SummaryID);
835 case lltok::kw_typeidCompatibleVTable:
836 result = ParseTypeIdCompatibleVtableEntry(SummaryID);
839 result = Error(Lex.getLoc(), "unexpected summary kind");
842 Lex.setIgnoreColonInIdentifiers(false);
846 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
847 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
848 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
851 // If there was an explicit dso_local, update GV. In the absence of an explicit
852 // dso_local we keep the default value.
853 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
855 GV.setDSOLocal(true);
858 /// parseIndirectSymbol:
859 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
860 /// OptionalVisibility OptionalDLLStorageClass
861 /// OptionalThreadLocal OptionalUnnamedAddr
862 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
867 /// IndirectSymbolAttr
868 /// ::= ',' 'partition' StringConstant
870 /// Everything through OptionalUnnamedAddr has already been parsed.
872 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
873 unsigned L, unsigned Visibility,
874 unsigned DLLStorageClass, bool DSOLocal,
875 GlobalVariable::ThreadLocalMode TLM,
876 GlobalVariable::UnnamedAddr UnnamedAddr) {
878 if (Lex.getKind() == lltok::kw_alias)
880 else if (Lex.getKind() == lltok::kw_ifunc)
883 llvm_unreachable("Not an alias or ifunc!");
886 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
888 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
889 return Error(NameLoc, "invalid linkage type for alias");
891 if (!isValidVisibilityForLinkage(Visibility, L))
892 return Error(NameLoc,
893 "symbol with local linkage must have default visibility");
896 LocTy ExplicitTypeLoc = Lex.getLoc();
898 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
902 LocTy AliaseeLoc = Lex.getLoc();
903 if (Lex.getKind() != lltok::kw_bitcast &&
904 Lex.getKind() != lltok::kw_getelementptr &&
905 Lex.getKind() != lltok::kw_addrspacecast &&
906 Lex.getKind() != lltok::kw_inttoptr) {
907 if (ParseGlobalTypeAndValue(Aliasee))
910 // The bitcast dest type is not present, it is implied by the dest type.
914 if (ID.Kind != ValID::t_Constant)
915 return Error(AliaseeLoc, "invalid aliasee");
916 Aliasee = ID.ConstantVal;
919 Type *AliaseeType = Aliasee->getType();
920 auto *PTy = dyn_cast<PointerType>(AliaseeType);
922 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
923 unsigned AddrSpace = PTy->getAddressSpace();
925 if (IsAlias && Ty != PTy->getElementType())
928 "explicit pointee type doesn't match operand's pointee type");
930 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
933 "explicit pointee type should be a function type");
935 GlobalValue *GVal = nullptr;
937 // See if the alias was forward referenced, if so, prepare to replace the
938 // forward reference.
940 GVal = M->getNamedValue(Name);
942 if (!ForwardRefVals.erase(Name))
943 return Error(NameLoc, "redefinition of global '@" + Name + "'");
946 auto I = ForwardRefValIDs.find(NumberedVals.size());
947 if (I != ForwardRefValIDs.end()) {
948 GVal = I->second.first;
949 ForwardRefValIDs.erase(I);
953 // Okay, create the alias but do not insert it into the module yet.
954 std::unique_ptr<GlobalIndirectSymbol> GA;
956 GA.reset(GlobalAlias::create(Ty, AddrSpace,
957 (GlobalValue::LinkageTypes)Linkage, Name,
958 Aliasee, /*Parent*/ nullptr));
960 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
961 (GlobalValue::LinkageTypes)Linkage, Name,
962 Aliasee, /*Parent*/ nullptr));
963 GA->setThreadLocalMode(TLM);
964 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
965 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
966 GA->setUnnamedAddr(UnnamedAddr);
967 maybeSetDSOLocal(DSOLocal, *GA);
969 // At this point we've parsed everything except for the IndirectSymbolAttrs.
970 // Now parse them if there are any.
971 while (Lex.getKind() == lltok::comma) {
974 if (Lex.getKind() == lltok::kw_partition) {
976 GA->setPartition(Lex.getStrVal());
977 if (ParseToken(lltok::StringConstant, "expected partition string"))
980 return TokError("unknown alias or ifunc property!");
985 NumberedVals.push_back(GA.get());
988 // Verify that types agree.
989 if (GVal->getType() != GA->getType())
992 "forward reference and definition of alias have different types");
994 // If they agree, just RAUW the old value with the alias and remove the
996 GVal->replaceAllUsesWith(GA.get());
997 GVal->eraseFromParent();
1000 // Insert into the module, we know its name won't collide now.
1002 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1004 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1005 assert(GA->getName() == Name && "Should not be a name conflict!");
1007 // The module owns this now
1014 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1015 /// OptionalVisibility OptionalDLLStorageClass
1016 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1017 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1018 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1019 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1020 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1021 /// Const OptionalAttrs
1023 /// Everything up to and including OptionalUnnamedAddr has been parsed
1026 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
1027 unsigned Linkage, bool HasLinkage,
1028 unsigned Visibility, unsigned DLLStorageClass,
1029 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1030 GlobalVariable::UnnamedAddr UnnamedAddr) {
1031 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1032 return Error(NameLoc,
1033 "symbol with local linkage must have default visibility");
1036 bool IsConstant, IsExternallyInitialized;
1037 LocTy IsExternallyInitializedLoc;
1041 if (ParseOptionalAddrSpace(AddrSpace) ||
1042 ParseOptionalToken(lltok::kw_externally_initialized,
1043 IsExternallyInitialized,
1044 &IsExternallyInitializedLoc) ||
1045 ParseGlobalType(IsConstant) ||
1046 ParseType(Ty, TyLoc))
1049 // If the linkage is specified and is external, then no initializer is
1051 Constant *Init = nullptr;
1053 !GlobalValue::isValidDeclarationLinkage(
1054 (GlobalValue::LinkageTypes)Linkage)) {
1055 if (ParseGlobalValue(Ty, Init))
1059 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1060 return Error(TyLoc, "invalid type for global variable");
1062 GlobalValue *GVal = nullptr;
1064 // See if the global was forward referenced, if so, use the global.
1065 if (!Name.empty()) {
1066 GVal = M->getNamedValue(Name);
1068 if (!ForwardRefVals.erase(Name))
1069 return Error(NameLoc, "redefinition of global '@" + Name + "'");
1072 auto I = ForwardRefValIDs.find(NumberedVals.size());
1073 if (I != ForwardRefValIDs.end()) {
1074 GVal = I->second.first;
1075 ForwardRefValIDs.erase(I);
1081 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1082 Name, nullptr, GlobalVariable::NotThreadLocal,
1085 if (GVal->getValueType() != Ty)
1087 "forward reference and definition of global have different types");
1089 GV = cast<GlobalVariable>(GVal);
1091 // Move the forward-reference to the correct spot in the module.
1092 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1096 NumberedVals.push_back(GV);
1098 // Set the parsed properties on the global.
1100 GV->setInitializer(Init);
1101 GV->setConstant(IsConstant);
1102 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1103 maybeSetDSOLocal(DSOLocal, *GV);
1104 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1105 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1106 GV->setExternallyInitialized(IsExternallyInitialized);
1107 GV->setThreadLocalMode(TLM);
1108 GV->setUnnamedAddr(UnnamedAddr);
1110 // Parse attributes on the global.
1111 while (Lex.getKind() == lltok::comma) {
1114 if (Lex.getKind() == lltok::kw_section) {
1116 GV->setSection(Lex.getStrVal());
1117 if (ParseToken(lltok::StringConstant, "expected global section string"))
1119 } else if (Lex.getKind() == lltok::kw_partition) {
1121 GV->setPartition(Lex.getStrVal());
1122 if (ParseToken(lltok::StringConstant, "expected partition string"))
1124 } else if (Lex.getKind() == lltok::kw_align) {
1126 if (ParseOptionalAlignment(Alignment)) return true;
1127 GV->setAlignment(Alignment);
1128 } else if (Lex.getKind() == lltok::MetadataVar) {
1129 if (ParseGlobalObjectMetadataAttachment(*GV))
1133 if (parseOptionalComdat(Name, C))
1138 return TokError("unknown global variable property!");
1144 std::vector<unsigned> FwdRefAttrGrps;
1145 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1147 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1148 GV->setAttributes(AttributeSet::get(Context, Attrs));
1149 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1155 /// ParseUnnamedAttrGrp
1156 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1157 bool LLParser::ParseUnnamedAttrGrp() {
1158 assert(Lex.getKind() == lltok::kw_attributes);
1159 LocTy AttrGrpLoc = Lex.getLoc();
1162 if (Lex.getKind() != lltok::AttrGrpID)
1163 return TokError("expected attribute group id");
1165 unsigned VarID = Lex.getUIntVal();
1166 std::vector<unsigned> unused;
1170 if (ParseToken(lltok::equal, "expected '=' here") ||
1171 ParseToken(lltok::lbrace, "expected '{' here") ||
1172 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1174 ParseToken(lltok::rbrace, "expected end of attribute group"))
1177 if (!NumberedAttrBuilders[VarID].hasAttributes())
1178 return Error(AttrGrpLoc, "attribute group has no attributes");
1183 /// ParseFnAttributeValuePairs
1184 /// ::= <attr> | <attr> '=' <value>
1185 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1186 std::vector<unsigned> &FwdRefAttrGrps,
1187 bool inAttrGrp, LocTy &BuiltinLoc) {
1188 bool HaveError = false;
1193 lltok::Kind Token = Lex.getKind();
1194 if (Token == lltok::kw_builtin)
1195 BuiltinLoc = Lex.getLoc();
1198 if (!inAttrGrp) return HaveError;
1199 return Error(Lex.getLoc(), "unterminated attribute group");
1204 case lltok::AttrGrpID: {
1205 // Allow a function to reference an attribute group:
1207 // define void @foo() #1 { ... }
1211 "cannot have an attribute group reference in an attribute group");
1213 unsigned AttrGrpNum = Lex.getUIntVal();
1214 if (inAttrGrp) break;
1216 // Save the reference to the attribute group. We'll fill it in later.
1217 FwdRefAttrGrps.push_back(AttrGrpNum);
1220 // Target-dependent attributes:
1221 case lltok::StringConstant: {
1222 if (ParseStringAttribute(B))
1227 // Target-independent attributes:
1228 case lltok::kw_align: {
1229 // As a hack, we allow function alignment to be initially parsed as an
1230 // attribute on a function declaration/definition or added to an attribute
1231 // group and later moved to the alignment field.
1235 if (ParseToken(lltok::equal, "expected '=' here") ||
1236 ParseUInt32(Alignment))
1239 if (ParseOptionalAlignment(Alignment))
1242 B.addAlignmentAttr(Alignment);
1245 case lltok::kw_alignstack: {
1249 if (ParseToken(lltok::equal, "expected '=' here") ||
1250 ParseUInt32(Alignment))
1253 if (ParseOptionalStackAlignment(Alignment))
1256 B.addStackAlignmentAttr(Alignment);
1259 case lltok::kw_allocsize: {
1260 unsigned ElemSizeArg;
1261 Optional<unsigned> NumElemsArg;
1262 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1263 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1265 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1268 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1269 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1270 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1271 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1272 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1273 case lltok::kw_inaccessiblememonly:
1274 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1275 case lltok::kw_inaccessiblemem_or_argmemonly:
1276 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1277 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1278 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1279 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1280 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1281 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1282 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1283 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1284 case lltok::kw_noimplicitfloat:
1285 B.addAttribute(Attribute::NoImplicitFloat); break;
1286 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1287 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1288 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1289 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1290 case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1291 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1292 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1293 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1294 case lltok::kw_optforfuzzing:
1295 B.addAttribute(Attribute::OptForFuzzing); break;
1296 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1297 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1298 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1299 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1300 case lltok::kw_returns_twice:
1301 B.addAttribute(Attribute::ReturnsTwice); break;
1302 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1303 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1304 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1305 case lltok::kw_sspstrong:
1306 B.addAttribute(Attribute::StackProtectStrong); break;
1307 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1308 case lltok::kw_shadowcallstack:
1309 B.addAttribute(Attribute::ShadowCallStack); break;
1310 case lltok::kw_sanitize_address:
1311 B.addAttribute(Attribute::SanitizeAddress); break;
1312 case lltok::kw_sanitize_hwaddress:
1313 B.addAttribute(Attribute::SanitizeHWAddress); break;
1314 case lltok::kw_sanitize_memtag:
1315 B.addAttribute(Attribute::SanitizeMemTag); break;
1316 case lltok::kw_sanitize_thread:
1317 B.addAttribute(Attribute::SanitizeThread); break;
1318 case lltok::kw_sanitize_memory:
1319 B.addAttribute(Attribute::SanitizeMemory); break;
1320 case lltok::kw_speculative_load_hardening:
1321 B.addAttribute(Attribute::SpeculativeLoadHardening);
1323 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1324 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1325 case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1326 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1329 case lltok::kw_inreg:
1330 case lltok::kw_signext:
1331 case lltok::kw_zeroext:
1334 "invalid use of attribute on a function");
1336 case lltok::kw_byval:
1337 case lltok::kw_dereferenceable:
1338 case lltok::kw_dereferenceable_or_null:
1339 case lltok::kw_inalloca:
1340 case lltok::kw_nest:
1341 case lltok::kw_noalias:
1342 case lltok::kw_nocapture:
1343 case lltok::kw_nonnull:
1344 case lltok::kw_returned:
1345 case lltok::kw_sret:
1346 case lltok::kw_swifterror:
1347 case lltok::kw_swiftself:
1348 case lltok::kw_immarg:
1351 "invalid use of parameter-only attribute on a function");
1359 //===----------------------------------------------------------------------===//
1360 // GlobalValue Reference/Resolution Routines.
1361 //===----------------------------------------------------------------------===//
1363 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1364 const std::string &Name) {
1365 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1366 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1367 PTy->getAddressSpace(), Name, M);
1369 return new GlobalVariable(*M, PTy->getElementType(), false,
1370 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1371 nullptr, GlobalVariable::NotThreadLocal,
1372 PTy->getAddressSpace());
1375 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1376 Value *Val, bool IsCall) {
1377 if (Val->getType() == Ty)
1379 // For calls we also accept variables in the program address space.
1380 Type *SuggestedTy = Ty;
1381 if (IsCall && isa<PointerType>(Ty)) {
1382 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1383 M->getDataLayout().getProgramAddressSpace());
1384 SuggestedTy = TyInProgAS;
1385 if (Val->getType() == TyInProgAS)
1388 if (Ty->isLabelTy())
1389 Error(Loc, "'" + Name + "' is not a basic block");
1391 Error(Loc, "'" + Name + "' defined with type '" +
1392 getTypeString(Val->getType()) + "' but expected '" +
1393 getTypeString(SuggestedTy) + "'");
1397 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1398 /// forward reference record if needed. This can return null if the value
1399 /// exists but does not have the right type.
1400 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1401 LocTy Loc, bool IsCall) {
1402 PointerType *PTy = dyn_cast<PointerType>(Ty);
1404 Error(Loc, "global variable reference must have pointer type");
1408 // Look this name up in the normal function symbol table.
1410 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1412 // If this is a forward reference for the value, see if we already created a
1413 // forward ref record.
1415 auto I = ForwardRefVals.find(Name);
1416 if (I != ForwardRefVals.end())
1417 Val = I->second.first;
1420 // If we have the value in the symbol table or fwd-ref table, return it.
1422 return cast_or_null<GlobalValue>(
1423 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1425 // Otherwise, create a new forward reference for this value and remember it.
1426 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1427 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1431 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1433 PointerType *PTy = dyn_cast<PointerType>(Ty);
1435 Error(Loc, "global variable reference must have pointer type");
1439 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1441 // If this is a forward reference for the value, see if we already created a
1442 // forward ref record.
1444 auto I = ForwardRefValIDs.find(ID);
1445 if (I != ForwardRefValIDs.end())
1446 Val = I->second.first;
1449 // If we have the value in the symbol table or fwd-ref table, return it.
1451 return cast_or_null<GlobalValue>(
1452 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1454 // Otherwise, create a new forward reference for this value and remember it.
1455 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1456 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1460 //===----------------------------------------------------------------------===//
1461 // Comdat Reference/Resolution Routines.
1462 //===----------------------------------------------------------------------===//
1464 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1465 // Look this name up in the comdat symbol table.
1466 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1467 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1468 if (I != ComdatSymTab.end())
1471 // Otherwise, create a new forward reference for this value and remember it.
1472 Comdat *C = M->getOrInsertComdat(Name);
1473 ForwardRefComdats[Name] = Loc;
1477 //===----------------------------------------------------------------------===//
1479 //===----------------------------------------------------------------------===//
1481 /// ParseToken - If the current token has the specified kind, eat it and return
1482 /// success. Otherwise, emit the specified error and return failure.
1483 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1484 if (Lex.getKind() != T)
1485 return TokError(ErrMsg);
1490 /// ParseStringConstant
1491 /// ::= StringConstant
1492 bool LLParser::ParseStringConstant(std::string &Result) {
1493 if (Lex.getKind() != lltok::StringConstant)
1494 return TokError("expected string constant");
1495 Result = Lex.getStrVal();
1502 bool LLParser::ParseUInt32(uint32_t &Val) {
1503 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1504 return TokError("expected integer");
1505 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1506 if (Val64 != unsigned(Val64))
1507 return TokError("expected 32-bit integer (too large)");
1515 bool LLParser::ParseUInt64(uint64_t &Val) {
1516 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1517 return TokError("expected integer");
1518 Val = Lex.getAPSIntVal().getLimitedValue();
1524 /// := 'localdynamic'
1525 /// := 'initialexec'
1527 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1528 switch (Lex.getKind()) {
1530 return TokError("expected localdynamic, initialexec or localexec");
1531 case lltok::kw_localdynamic:
1532 TLM = GlobalVariable::LocalDynamicTLSModel;
1534 case lltok::kw_initialexec:
1535 TLM = GlobalVariable::InitialExecTLSModel;
1537 case lltok::kw_localexec:
1538 TLM = GlobalVariable::LocalExecTLSModel;
1546 /// ParseOptionalThreadLocal
1548 /// := 'thread_local'
1549 /// := 'thread_local' '(' tlsmodel ')'
1550 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1551 TLM = GlobalVariable::NotThreadLocal;
1552 if (!EatIfPresent(lltok::kw_thread_local))
1555 TLM = GlobalVariable::GeneralDynamicTLSModel;
1556 if (Lex.getKind() == lltok::lparen) {
1558 return ParseTLSModel(TLM) ||
1559 ParseToken(lltok::rparen, "expected ')' after thread local model");
1564 /// ParseOptionalAddrSpace
1566 /// := 'addrspace' '(' uint32 ')'
1567 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1568 AddrSpace = DefaultAS;
1569 if (!EatIfPresent(lltok::kw_addrspace))
1571 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1572 ParseUInt32(AddrSpace) ||
1573 ParseToken(lltok::rparen, "expected ')' in address space");
1576 /// ParseStringAttribute
1577 /// := StringConstant
1578 /// := StringConstant '=' StringConstant
1579 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1580 std::string Attr = Lex.getStrVal();
1583 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1585 B.addAttribute(Attr, Val);
1589 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1590 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1591 bool HaveError = false;
1596 lltok::Kind Token = Lex.getKind();
1598 default: // End of attributes.
1600 case lltok::StringConstant: {
1601 if (ParseStringAttribute(B))
1605 case lltok::kw_align: {
1607 if (ParseOptionalAlignment(Alignment))
1609 B.addAlignmentAttr(Alignment);
1612 case lltok::kw_byval: {
1614 if (ParseByValWithOptionalType(Ty))
1619 case lltok::kw_dereferenceable: {
1621 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1623 B.addDereferenceableAttr(Bytes);
1626 case lltok::kw_dereferenceable_or_null: {
1628 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1630 B.addDereferenceableOrNullAttr(Bytes);
1633 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1634 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1635 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1636 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1637 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1638 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1639 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1640 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1641 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1642 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1643 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1644 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1645 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1646 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1647 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1648 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1650 case lltok::kw_alignstack:
1651 case lltok::kw_alwaysinline:
1652 case lltok::kw_argmemonly:
1653 case lltok::kw_builtin:
1654 case lltok::kw_inlinehint:
1655 case lltok::kw_jumptable:
1656 case lltok::kw_minsize:
1657 case lltok::kw_naked:
1658 case lltok::kw_nobuiltin:
1659 case lltok::kw_noduplicate:
1660 case lltok::kw_noimplicitfloat:
1661 case lltok::kw_noinline:
1662 case lltok::kw_nonlazybind:
1663 case lltok::kw_noredzone:
1664 case lltok::kw_noreturn:
1665 case lltok::kw_nocf_check:
1666 case lltok::kw_nounwind:
1667 case lltok::kw_optforfuzzing:
1668 case lltok::kw_optnone:
1669 case lltok::kw_optsize:
1670 case lltok::kw_returns_twice:
1671 case lltok::kw_sanitize_address:
1672 case lltok::kw_sanitize_hwaddress:
1673 case lltok::kw_sanitize_memtag:
1674 case lltok::kw_sanitize_memory:
1675 case lltok::kw_sanitize_thread:
1676 case lltok::kw_speculative_load_hardening:
1678 case lltok::kw_sspreq:
1679 case lltok::kw_sspstrong:
1680 case lltok::kw_safestack:
1681 case lltok::kw_shadowcallstack:
1682 case lltok::kw_strictfp:
1683 case lltok::kw_uwtable:
1684 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1692 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1693 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1694 bool HaveError = false;
1699 lltok::Kind Token = Lex.getKind();
1701 default: // End of attributes.
1703 case lltok::StringConstant: {
1704 if (ParseStringAttribute(B))
1708 case lltok::kw_dereferenceable: {
1710 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1712 B.addDereferenceableAttr(Bytes);
1715 case lltok::kw_dereferenceable_or_null: {
1717 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1719 B.addDereferenceableOrNullAttr(Bytes);
1722 case lltok::kw_align: {
1724 if (ParseOptionalAlignment(Alignment))
1726 B.addAlignmentAttr(Alignment);
1729 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1730 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1731 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1732 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1733 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1736 case lltok::kw_byval:
1737 case lltok::kw_inalloca:
1738 case lltok::kw_nest:
1739 case lltok::kw_nocapture:
1740 case lltok::kw_returned:
1741 case lltok::kw_sret:
1742 case lltok::kw_swifterror:
1743 case lltok::kw_swiftself:
1744 case lltok::kw_immarg:
1745 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1748 case lltok::kw_alignstack:
1749 case lltok::kw_alwaysinline:
1750 case lltok::kw_argmemonly:
1751 case lltok::kw_builtin:
1752 case lltok::kw_cold:
1753 case lltok::kw_inlinehint:
1754 case lltok::kw_jumptable:
1755 case lltok::kw_minsize:
1756 case lltok::kw_naked:
1757 case lltok::kw_nobuiltin:
1758 case lltok::kw_noduplicate:
1759 case lltok::kw_noimplicitfloat:
1760 case lltok::kw_noinline:
1761 case lltok::kw_nonlazybind:
1762 case lltok::kw_noredzone:
1763 case lltok::kw_noreturn:
1764 case lltok::kw_nocf_check:
1765 case lltok::kw_nounwind:
1766 case lltok::kw_optforfuzzing:
1767 case lltok::kw_optnone:
1768 case lltok::kw_optsize:
1769 case lltok::kw_returns_twice:
1770 case lltok::kw_sanitize_address:
1771 case lltok::kw_sanitize_hwaddress:
1772 case lltok::kw_sanitize_memtag:
1773 case lltok::kw_sanitize_memory:
1774 case lltok::kw_sanitize_thread:
1775 case lltok::kw_speculative_load_hardening:
1777 case lltok::kw_sspreq:
1778 case lltok::kw_sspstrong:
1779 case lltok::kw_safestack:
1780 case lltok::kw_shadowcallstack:
1781 case lltok::kw_strictfp:
1782 case lltok::kw_uwtable:
1783 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1786 case lltok::kw_readnone:
1787 case lltok::kw_readonly:
1788 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1795 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1800 return GlobalValue::ExternalLinkage;
1801 case lltok::kw_private:
1802 return GlobalValue::PrivateLinkage;
1803 case lltok::kw_internal:
1804 return GlobalValue::InternalLinkage;
1805 case lltok::kw_weak:
1806 return GlobalValue::WeakAnyLinkage;
1807 case lltok::kw_weak_odr:
1808 return GlobalValue::WeakODRLinkage;
1809 case lltok::kw_linkonce:
1810 return GlobalValue::LinkOnceAnyLinkage;
1811 case lltok::kw_linkonce_odr:
1812 return GlobalValue::LinkOnceODRLinkage;
1813 case lltok::kw_available_externally:
1814 return GlobalValue::AvailableExternallyLinkage;
1815 case lltok::kw_appending:
1816 return GlobalValue::AppendingLinkage;
1817 case lltok::kw_common:
1818 return GlobalValue::CommonLinkage;
1819 case lltok::kw_extern_weak:
1820 return GlobalValue::ExternalWeakLinkage;
1821 case lltok::kw_external:
1822 return GlobalValue::ExternalLinkage;
1826 /// ParseOptionalLinkage
1833 /// ::= 'linkonce_odr'
1834 /// ::= 'available_externally'
1837 /// ::= 'extern_weak'
1839 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1840 unsigned &Visibility,
1841 unsigned &DLLStorageClass,
1843 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1846 ParseOptionalDSOLocal(DSOLocal);
1847 ParseOptionalVisibility(Visibility);
1848 ParseOptionalDLLStorageClass(DLLStorageClass);
1850 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1851 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1857 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1858 switch (Lex.getKind()) {
1862 case lltok::kw_dso_local:
1866 case lltok::kw_dso_preemptable:
1873 /// ParseOptionalVisibility
1879 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1880 switch (Lex.getKind()) {
1882 Res = GlobalValue::DefaultVisibility;
1884 case lltok::kw_default:
1885 Res = GlobalValue::DefaultVisibility;
1887 case lltok::kw_hidden:
1888 Res = GlobalValue::HiddenVisibility;
1890 case lltok::kw_protected:
1891 Res = GlobalValue::ProtectedVisibility;
1897 /// ParseOptionalDLLStorageClass
1902 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1903 switch (Lex.getKind()) {
1905 Res = GlobalValue::DefaultStorageClass;
1907 case lltok::kw_dllimport:
1908 Res = GlobalValue::DLLImportStorageClass;
1910 case lltok::kw_dllexport:
1911 Res = GlobalValue::DLLExportStorageClass;
1917 /// ParseOptionalCallingConv
1921 /// ::= 'intel_ocl_bicc'
1923 /// ::= 'x86_stdcallcc'
1924 /// ::= 'x86_fastcallcc'
1925 /// ::= 'x86_thiscallcc'
1926 /// ::= 'x86_vectorcallcc'
1927 /// ::= 'arm_apcscc'
1928 /// ::= 'arm_aapcscc'
1929 /// ::= 'arm_aapcs_vfpcc'
1930 /// ::= 'aarch64_vector_pcs'
1931 /// ::= 'msp430_intrcc'
1932 /// ::= 'avr_intrcc'
1933 /// ::= 'avr_signalcc'
1934 /// ::= 'ptx_kernel'
1935 /// ::= 'ptx_device'
1937 /// ::= 'spir_kernel'
1938 /// ::= 'x86_64_sysvcc'
1940 /// ::= 'webkit_jscc'
1942 /// ::= 'preserve_mostcc'
1943 /// ::= 'preserve_allcc'
1946 /// ::= 'x86_intrcc'
1949 /// ::= 'cxx_fast_tlscc'
1957 /// ::= 'amdgpu_kernel'
1960 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1961 switch (Lex.getKind()) {
1962 default: CC = CallingConv::C; return false;
1963 case lltok::kw_ccc: CC = CallingConv::C; break;
1964 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1965 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1966 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1967 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1968 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1969 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1970 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1971 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1972 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1973 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1974 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1975 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1976 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1977 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1978 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1979 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1980 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1981 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1982 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1983 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1984 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1985 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1986 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1987 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1988 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1989 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1990 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1991 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1992 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1993 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1994 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1995 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1996 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1997 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1998 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1999 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2000 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2001 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2002 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2003 case lltok::kw_cc: {
2005 return ParseUInt32(CC);
2013 /// ParseMetadataAttachment
2015 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2016 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2018 std::string Name = Lex.getStrVal();
2019 Kind = M->getMDKindID(Name);
2022 return ParseMDNode(MD);
2025 /// ParseInstructionMetadata
2026 /// ::= !dbg !42 (',' !dbg !57)*
2027 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
2029 if (Lex.getKind() != lltok::MetadataVar)
2030 return TokError("expected metadata after comma");
2034 if (ParseMetadataAttachment(MDK, N))
2037 Inst.setMetadata(MDK, N);
2038 if (MDK == LLVMContext::MD_tbaa)
2039 InstsWithTBAATag.push_back(&Inst);
2041 // If this is the end of the list, we're done.
2042 } while (EatIfPresent(lltok::comma));
2046 /// ParseGlobalObjectMetadataAttachment
2048 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2051 if (ParseMetadataAttachment(MDK, N))
2054 GO.addMetadata(MDK, *N);
2058 /// ParseOptionalFunctionMetadata
2060 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2061 while (Lex.getKind() == lltok::MetadataVar)
2062 if (ParseGlobalObjectMetadataAttachment(F))
2067 /// ParseOptionalAlignment
2070 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2072 if (!EatIfPresent(lltok::kw_align))
2074 LocTy AlignLoc = Lex.getLoc();
2075 if (ParseUInt32(Alignment)) return true;
2076 if (!isPowerOf2_32(Alignment))
2077 return Error(AlignLoc, "alignment is not a power of two");
2078 if (Alignment > Value::MaximumAlignment)
2079 return Error(AlignLoc, "huge alignments are not supported yet");
2083 /// ParseOptionalDerefAttrBytes
2085 /// ::= AttrKind '(' 4 ')'
2087 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2088 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2090 assert((AttrKind == lltok::kw_dereferenceable ||
2091 AttrKind == lltok::kw_dereferenceable_or_null) &&
2095 if (!EatIfPresent(AttrKind))
2097 LocTy ParenLoc = Lex.getLoc();
2098 if (!EatIfPresent(lltok::lparen))
2099 return Error(ParenLoc, "expected '('");
2100 LocTy DerefLoc = Lex.getLoc();
2101 if (ParseUInt64(Bytes)) return true;
2102 ParenLoc = Lex.getLoc();
2103 if (!EatIfPresent(lltok::rparen))
2104 return Error(ParenLoc, "expected ')'");
2106 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2110 /// ParseOptionalCommaAlign
2114 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2116 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2117 bool &AteExtraComma) {
2118 AteExtraComma = false;
2119 while (EatIfPresent(lltok::comma)) {
2120 // Metadata at the end is an early exit.
2121 if (Lex.getKind() == lltok::MetadataVar) {
2122 AteExtraComma = true;
2126 if (Lex.getKind() != lltok::kw_align)
2127 return Error(Lex.getLoc(), "expected metadata or 'align'");
2129 if (ParseOptionalAlignment(Alignment)) return true;
2135 /// ParseOptionalCommaAddrSpace
2137 /// ::= ',' addrspace(1)
2139 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2141 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2143 bool &AteExtraComma) {
2144 AteExtraComma = false;
2145 while (EatIfPresent(lltok::comma)) {
2146 // Metadata at the end is an early exit.
2147 if (Lex.getKind() == lltok::MetadataVar) {
2148 AteExtraComma = true;
2153 if (Lex.getKind() != lltok::kw_addrspace)
2154 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2156 if (ParseOptionalAddrSpace(AddrSpace))
2163 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2164 Optional<unsigned> &HowManyArg) {
2167 auto StartParen = Lex.getLoc();
2168 if (!EatIfPresent(lltok::lparen))
2169 return Error(StartParen, "expected '('");
2171 if (ParseUInt32(BaseSizeArg))
2174 if (EatIfPresent(lltok::comma)) {
2175 auto HowManyAt = Lex.getLoc();
2177 if (ParseUInt32(HowMany))
2179 if (HowMany == BaseSizeArg)
2180 return Error(HowManyAt,
2181 "'allocsize' indices can't refer to the same parameter");
2182 HowManyArg = HowMany;
2186 auto EndParen = Lex.getLoc();
2187 if (!EatIfPresent(lltok::rparen))
2188 return Error(EndParen, "expected ')'");
2192 /// ParseScopeAndOrdering
2193 /// if isAtomic: ::= SyncScope? AtomicOrdering
2196 /// This sets Scope and Ordering to the parsed values.
2197 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2198 AtomicOrdering &Ordering) {
2202 return ParseScope(SSID) || ParseOrdering(Ordering);
2206 /// ::= syncscope("singlethread" | "<target scope>")?
2208 /// This sets synchronization scope ID to the ID of the parsed value.
2209 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2210 SSID = SyncScope::System;
2211 if (EatIfPresent(lltok::kw_syncscope)) {
2212 auto StartParenAt = Lex.getLoc();
2213 if (!EatIfPresent(lltok::lparen))
2214 return Error(StartParenAt, "Expected '(' in syncscope");
2217 auto SSNAt = Lex.getLoc();
2218 if (ParseStringConstant(SSN))
2219 return Error(SSNAt, "Expected synchronization scope name");
2221 auto EndParenAt = Lex.getLoc();
2222 if (!EatIfPresent(lltok::rparen))
2223 return Error(EndParenAt, "Expected ')' in syncscope");
2225 SSID = Context.getOrInsertSyncScopeID(SSN);
2232 /// ::= AtomicOrdering
2234 /// This sets Ordering to the parsed value.
2235 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2236 switch (Lex.getKind()) {
2237 default: return TokError("Expected ordering on atomic instruction");
2238 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2239 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2240 // Not specified yet:
2241 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2242 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2243 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2244 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2245 case lltok::kw_seq_cst:
2246 Ordering = AtomicOrdering::SequentiallyConsistent;
2253 /// ParseOptionalStackAlignment
2255 /// ::= 'alignstack' '(' 4 ')'
2256 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2258 if (!EatIfPresent(lltok::kw_alignstack))
2260 LocTy ParenLoc = Lex.getLoc();
2261 if (!EatIfPresent(lltok::lparen))
2262 return Error(ParenLoc, "expected '('");
2263 LocTy AlignLoc = Lex.getLoc();
2264 if (ParseUInt32(Alignment)) return true;
2265 ParenLoc = Lex.getLoc();
2266 if (!EatIfPresent(lltok::rparen))
2267 return Error(ParenLoc, "expected ')'");
2268 if (!isPowerOf2_32(Alignment))
2269 return Error(AlignLoc, "stack alignment is not a power of two");
2273 /// ParseIndexList - This parses the index list for an insert/extractvalue
2274 /// instruction. This sets AteExtraComma in the case where we eat an extra
2275 /// comma at the end of the line and find that it is followed by metadata.
2276 /// Clients that don't allow metadata can call the version of this function that
2277 /// only takes one argument.
2280 /// ::= (',' uint32)+
2282 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2283 bool &AteExtraComma) {
2284 AteExtraComma = false;
2286 if (Lex.getKind() != lltok::comma)
2287 return TokError("expected ',' as start of index list");
2289 while (EatIfPresent(lltok::comma)) {
2290 if (Lex.getKind() == lltok::MetadataVar) {
2291 if (Indices.empty()) return TokError("expected index");
2292 AteExtraComma = true;
2296 if (ParseUInt32(Idx)) return true;
2297 Indices.push_back(Idx);
2303 //===----------------------------------------------------------------------===//
2305 //===----------------------------------------------------------------------===//
2307 /// ParseType - Parse a type.
2308 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2309 SMLoc TypeLoc = Lex.getLoc();
2310 switch (Lex.getKind()) {
2312 return TokError(Msg);
2314 // Type ::= 'float' | 'void' (etc)
2315 Result = Lex.getTyVal();
2319 // Type ::= StructType
2320 if (ParseAnonStructType(Result, false))
2323 case lltok::lsquare:
2324 // Type ::= '[' ... ']'
2325 Lex.Lex(); // eat the lsquare.
2326 if (ParseArrayVectorType(Result, false))
2329 case lltok::less: // Either vector or packed struct.
2330 // Type ::= '<' ... '>'
2332 if (Lex.getKind() == lltok::lbrace) {
2333 if (ParseAnonStructType(Result, true) ||
2334 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2336 } else if (ParseArrayVectorType(Result, true))
2339 case lltok::LocalVar: {
2341 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2343 // If the type hasn't been defined yet, create a forward definition and
2344 // remember where that forward def'n was seen (in case it never is defined).
2346 Entry.first = StructType::create(Context, Lex.getStrVal());
2347 Entry.second = Lex.getLoc();
2349 Result = Entry.first;
2354 case lltok::LocalVarID: {
2356 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2358 // If the type hasn't been defined yet, create a forward definition and
2359 // remember where that forward def'n was seen (in case it never is defined).
2361 Entry.first = StructType::create(Context);
2362 Entry.second = Lex.getLoc();
2364 Result = Entry.first;
2370 // Parse the type suffixes.
2372 switch (Lex.getKind()) {
2375 if (!AllowVoid && Result->isVoidTy())
2376 return Error(TypeLoc, "void type only allowed for function results");
2379 // Type ::= Type '*'
2381 if (Result->isLabelTy())
2382 return TokError("basic block pointers are invalid");
2383 if (Result->isVoidTy())
2384 return TokError("pointers to void are invalid - use i8* instead");
2385 if (!PointerType::isValidElementType(Result))
2386 return TokError("pointer to this type is invalid");
2387 Result = PointerType::getUnqual(Result);
2391 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2392 case lltok::kw_addrspace: {
2393 if (Result->isLabelTy())
2394 return TokError("basic block pointers are invalid");
2395 if (Result->isVoidTy())
2396 return TokError("pointers to void are invalid; use i8* instead");
2397 if (!PointerType::isValidElementType(Result))
2398 return TokError("pointer to this type is invalid");
2400 if (ParseOptionalAddrSpace(AddrSpace) ||
2401 ParseToken(lltok::star, "expected '*' in address space"))
2404 Result = PointerType::get(Result, AddrSpace);
2408 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2410 if (ParseFunctionType(Result))
2417 /// ParseParameterList
2419 /// ::= '(' Arg (',' Arg)* ')'
2421 /// ::= Type OptionalAttributes Value OptionalAttributes
2422 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2423 PerFunctionState &PFS, bool IsMustTailCall,
2424 bool InVarArgsFunc) {
2425 if (ParseToken(lltok::lparen, "expected '(' in call"))
2428 while (Lex.getKind() != lltok::rparen) {
2429 // If this isn't the first argument, we need a comma.
2430 if (!ArgList.empty() &&
2431 ParseToken(lltok::comma, "expected ',' in argument list"))
2434 // Parse an ellipsis if this is a musttail call in a variadic function.
2435 if (Lex.getKind() == lltok::dotdotdot) {
2436 const char *Msg = "unexpected ellipsis in argument list for ";
2437 if (!IsMustTailCall)
2438 return TokError(Twine(Msg) + "non-musttail call");
2440 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2441 Lex.Lex(); // Lex the '...', it is purely for readability.
2442 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2445 // Parse the argument.
2447 Type *ArgTy = nullptr;
2448 AttrBuilder ArgAttrs;
2450 if (ParseType(ArgTy, ArgLoc))
2453 if (ArgTy->isMetadataTy()) {
2454 if (ParseMetadataAsValue(V, PFS))
2457 // Otherwise, handle normal operands.
2458 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2461 ArgList.push_back(ParamInfo(
2462 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2465 if (IsMustTailCall && InVarArgsFunc)
2466 return TokError("expected '...' at end of argument list for musttail call "
2467 "in varargs function");
2469 Lex.Lex(); // Lex the ')'.
2473 /// ParseByValWithOptionalType
2476 bool LLParser::ParseByValWithOptionalType(Type *&Result) {
2478 if (!EatIfPresent(lltok::kw_byval))
2480 if (!EatIfPresent(lltok::lparen))
2482 if (ParseType(Result))
2484 if (!EatIfPresent(lltok::rparen))
2485 return Error(Lex.getLoc(), "expected ')'");
2489 /// ParseOptionalOperandBundles
2491 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2494 /// ::= bundle-tag '(' ')'
2495 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2497 /// bundle-tag ::= String Constant
2498 bool LLParser::ParseOptionalOperandBundles(
2499 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2500 LocTy BeginLoc = Lex.getLoc();
2501 if (!EatIfPresent(lltok::lsquare))
2504 while (Lex.getKind() != lltok::rsquare) {
2505 // If this isn't the first operand bundle, we need a comma.
2506 if (!BundleList.empty() &&
2507 ParseToken(lltok::comma, "expected ',' in input list"))
2511 if (ParseStringConstant(Tag))
2514 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2517 std::vector<Value *> Inputs;
2518 while (Lex.getKind() != lltok::rparen) {
2519 // If this isn't the first input, we need a comma.
2520 if (!Inputs.empty() &&
2521 ParseToken(lltok::comma, "expected ',' in input list"))
2525 Value *Input = nullptr;
2526 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2528 Inputs.push_back(Input);
2531 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2533 Lex.Lex(); // Lex the ')'.
2536 if (BundleList.empty())
2537 return Error(BeginLoc, "operand bundle set must not be empty");
2539 Lex.Lex(); // Lex the ']'.
2543 /// ParseArgumentList - Parse the argument list for a function type or function
2545 /// ::= '(' ArgTypeListI ')'
2549 /// ::= ArgTypeList ',' '...'
2550 /// ::= ArgType (',' ArgType)*
2552 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2555 assert(Lex.getKind() == lltok::lparen);
2556 Lex.Lex(); // eat the (.
2558 if (Lex.getKind() == lltok::rparen) {
2560 } else if (Lex.getKind() == lltok::dotdotdot) {
2564 LocTy TypeLoc = Lex.getLoc();
2565 Type *ArgTy = nullptr;
2569 if (ParseType(ArgTy) ||
2570 ParseOptionalParamAttrs(Attrs)) return true;
2572 if (ArgTy->isVoidTy())
2573 return Error(TypeLoc, "argument can not have void type");
2575 if (Lex.getKind() == lltok::LocalVar) {
2576 Name = Lex.getStrVal();
2580 if (!FunctionType::isValidArgumentType(ArgTy))
2581 return Error(TypeLoc, "invalid type for function argument");
2583 ArgList.emplace_back(TypeLoc, ArgTy,
2584 AttributeSet::get(ArgTy->getContext(), Attrs),
2587 while (EatIfPresent(lltok::comma)) {
2588 // Handle ... at end of arg list.
2589 if (EatIfPresent(lltok::dotdotdot)) {
2594 // Otherwise must be an argument type.
2595 TypeLoc = Lex.getLoc();
2596 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2598 if (ArgTy->isVoidTy())
2599 return Error(TypeLoc, "argument can not have void type");
2601 if (Lex.getKind() == lltok::LocalVar) {
2602 Name = Lex.getStrVal();
2608 if (!ArgTy->isFirstClassType())
2609 return Error(TypeLoc, "invalid type for function argument");
2611 ArgList.emplace_back(TypeLoc, ArgTy,
2612 AttributeSet::get(ArgTy->getContext(), Attrs),
2617 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2620 /// ParseFunctionType
2621 /// ::= Type ArgumentList OptionalAttrs
2622 bool LLParser::ParseFunctionType(Type *&Result) {
2623 assert(Lex.getKind() == lltok::lparen);
2625 if (!FunctionType::isValidReturnType(Result))
2626 return TokError("invalid function return type");
2628 SmallVector<ArgInfo, 8> ArgList;
2630 if (ParseArgumentList(ArgList, isVarArg))
2633 // Reject names on the arguments lists.
2634 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2635 if (!ArgList[i].Name.empty())
2636 return Error(ArgList[i].Loc, "argument name invalid in function type");
2637 if (ArgList[i].Attrs.hasAttributes())
2638 return Error(ArgList[i].Loc,
2639 "argument attributes invalid in function type");
2642 SmallVector<Type*, 16> ArgListTy;
2643 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2644 ArgListTy.push_back(ArgList[i].Ty);
2646 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2650 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2652 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2653 SmallVector<Type*, 8> Elts;
2654 if (ParseStructBody(Elts)) return true;
2656 Result = StructType::get(Context, Elts, Packed);
2660 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2661 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2662 std::pair<Type*, LocTy> &Entry,
2664 // If the type was already defined, diagnose the redefinition.
2665 if (Entry.first && !Entry.second.isValid())
2666 return Error(TypeLoc, "redefinition of type");
2668 // If we have opaque, just return without filling in the definition for the
2669 // struct. This counts as a definition as far as the .ll file goes.
2670 if (EatIfPresent(lltok::kw_opaque)) {
2671 // This type is being defined, so clear the location to indicate this.
2672 Entry.second = SMLoc();
2674 // If this type number has never been uttered, create it.
2676 Entry.first = StructType::create(Context, Name);
2677 ResultTy = Entry.first;
2681 // If the type starts with '<', then it is either a packed struct or a vector.
2682 bool isPacked = EatIfPresent(lltok::less);
2684 // If we don't have a struct, then we have a random type alias, which we
2685 // accept for compatibility with old files. These types are not allowed to be
2686 // forward referenced and not allowed to be recursive.
2687 if (Lex.getKind() != lltok::lbrace) {
2689 return Error(TypeLoc, "forward references to non-struct type");
2693 return ParseArrayVectorType(ResultTy, true);
2694 return ParseType(ResultTy);
2697 // This type is being defined, so clear the location to indicate this.
2698 Entry.second = SMLoc();
2700 // If this type number has never been uttered, create it.
2702 Entry.first = StructType::create(Context, Name);
2704 StructType *STy = cast<StructType>(Entry.first);
2706 SmallVector<Type*, 8> Body;
2707 if (ParseStructBody(Body) ||
2708 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2711 STy->setBody(Body, isPacked);
2716 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2719 /// ::= '{' Type (',' Type)* '}'
2720 /// ::= '<' '{' '}' '>'
2721 /// ::= '<' '{' Type (',' Type)* '}' '>'
2722 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2723 assert(Lex.getKind() == lltok::lbrace);
2724 Lex.Lex(); // Consume the '{'
2726 // Handle the empty struct.
2727 if (EatIfPresent(lltok::rbrace))
2730 LocTy EltTyLoc = Lex.getLoc();
2732 if (ParseType(Ty)) return true;
2735 if (!StructType::isValidElementType(Ty))
2736 return Error(EltTyLoc, "invalid element type for struct");
2738 while (EatIfPresent(lltok::comma)) {
2739 EltTyLoc = Lex.getLoc();
2740 if (ParseType(Ty)) return true;
2742 if (!StructType::isValidElementType(Ty))
2743 return Error(EltTyLoc, "invalid element type for struct");
2748 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2751 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2752 /// token has already been consumed.
2754 /// ::= '[' APSINTVAL 'x' Types ']'
2755 /// ::= '<' APSINTVAL 'x' Types '>'
2756 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2757 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2758 bool Scalable = false;
2760 if (isVector && Lex.getKind() == lltok::kw_vscale) {
2761 Lex.Lex(); // consume the 'vscale'
2762 if (ParseToken(lltok::kw_x, "expected 'x' after vscale"))
2768 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2769 Lex.getAPSIntVal().getBitWidth() > 64)
2770 return TokError("expected number in address space");
2772 LocTy SizeLoc = Lex.getLoc();
2773 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2776 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2779 LocTy TypeLoc = Lex.getLoc();
2780 Type *EltTy = nullptr;
2781 if (ParseType(EltTy)) return true;
2783 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2784 "expected end of sequential type"))
2789 return Error(SizeLoc, "zero element vector is illegal");
2790 if ((unsigned)Size != Size)
2791 return Error(SizeLoc, "size too large for vector");
2792 if (!VectorType::isValidElementType(EltTy))
2793 return Error(TypeLoc, "invalid vector element type");
2794 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2796 if (!ArrayType::isValidElementType(EltTy))
2797 return Error(TypeLoc, "invalid array element type");
2798 Result = ArrayType::get(EltTy, Size);
2803 //===----------------------------------------------------------------------===//
2804 // Function Semantic Analysis.
2805 //===----------------------------------------------------------------------===//
2807 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2809 : P(p), F(f), FunctionNumber(functionNumber) {
2811 // Insert unnamed arguments into the NumberedVals list.
2812 for (Argument &A : F.args())
2814 NumberedVals.push_back(&A);
2817 LLParser::PerFunctionState::~PerFunctionState() {
2818 // If there were any forward referenced non-basicblock values, delete them.
2820 for (const auto &P : ForwardRefVals) {
2821 if (isa<BasicBlock>(P.second.first))
2823 P.second.first->replaceAllUsesWith(
2824 UndefValue::get(P.second.first->getType()));
2825 P.second.first->deleteValue();
2828 for (const auto &P : ForwardRefValIDs) {
2829 if (isa<BasicBlock>(P.second.first))
2831 P.second.first->replaceAllUsesWith(
2832 UndefValue::get(P.second.first->getType()));
2833 P.second.first->deleteValue();
2837 bool LLParser::PerFunctionState::FinishFunction() {
2838 if (!ForwardRefVals.empty())
2839 return P.Error(ForwardRefVals.begin()->second.second,
2840 "use of undefined value '%" + ForwardRefVals.begin()->first +
2842 if (!ForwardRefValIDs.empty())
2843 return P.Error(ForwardRefValIDs.begin()->second.second,
2844 "use of undefined value '%" +
2845 Twine(ForwardRefValIDs.begin()->first) + "'");
2849 /// GetVal - Get a value with the specified name or ID, creating a
2850 /// forward reference record if needed. This can return null if the value
2851 /// exists but does not have the right type.
2852 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2853 LocTy Loc, bool IsCall) {
2854 // Look this name up in the normal function symbol table.
2855 Value *Val = F.getValueSymbolTable()->lookup(Name);
2857 // If this is a forward reference for the value, see if we already created a
2858 // forward ref record.
2860 auto I = ForwardRefVals.find(Name);
2861 if (I != ForwardRefVals.end())
2862 Val = I->second.first;
2865 // If we have the value in the symbol table or fwd-ref table, return it.
2867 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2869 // Don't make placeholders with invalid type.
2870 if (!Ty->isFirstClassType()) {
2871 P.Error(Loc, "invalid use of a non-first-class type");
2875 // Otherwise, create a new forward reference for this value and remember it.
2877 if (Ty->isLabelTy()) {
2878 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2880 FwdVal = new Argument(Ty, Name);
2883 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2887 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2889 // Look this name up in the normal function symbol table.
2890 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2892 // If this is a forward reference for the value, see if we already created a
2893 // forward ref record.
2895 auto I = ForwardRefValIDs.find(ID);
2896 if (I != ForwardRefValIDs.end())
2897 Val = I->second.first;
2900 // If we have the value in the symbol table or fwd-ref table, return it.
2902 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2904 if (!Ty->isFirstClassType()) {
2905 P.Error(Loc, "invalid use of a non-first-class type");
2909 // Otherwise, create a new forward reference for this value and remember it.
2911 if (Ty->isLabelTy()) {
2912 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2914 FwdVal = new Argument(Ty);
2917 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2921 /// SetInstName - After an instruction is parsed and inserted into its
2922 /// basic block, this installs its name.
2923 bool LLParser::PerFunctionState::SetInstName(int NameID,
2924 const std::string &NameStr,
2925 LocTy NameLoc, Instruction *Inst) {
2926 // If this instruction has void type, it cannot have a name or ID specified.
2927 if (Inst->getType()->isVoidTy()) {
2928 if (NameID != -1 || !NameStr.empty())
2929 return P.Error(NameLoc, "instructions returning void cannot have a name");
2933 // If this was a numbered instruction, verify that the instruction is the
2934 // expected value and resolve any forward references.
2935 if (NameStr.empty()) {
2936 // If neither a name nor an ID was specified, just use the next ID.
2938 NameID = NumberedVals.size();
2940 if (unsigned(NameID) != NumberedVals.size())
2941 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2942 Twine(NumberedVals.size()) + "'");
2944 auto FI = ForwardRefValIDs.find(NameID);
2945 if (FI != ForwardRefValIDs.end()) {
2946 Value *Sentinel = FI->second.first;
2947 if (Sentinel->getType() != Inst->getType())
2948 return P.Error(NameLoc, "instruction forward referenced with type '" +
2949 getTypeString(FI->second.first->getType()) + "'");
2951 Sentinel->replaceAllUsesWith(Inst);
2952 Sentinel->deleteValue();
2953 ForwardRefValIDs.erase(FI);
2956 NumberedVals.push_back(Inst);
2960 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2961 auto FI = ForwardRefVals.find(NameStr);
2962 if (FI != ForwardRefVals.end()) {
2963 Value *Sentinel = FI->second.first;
2964 if (Sentinel->getType() != Inst->getType())
2965 return P.Error(NameLoc, "instruction forward referenced with type '" +
2966 getTypeString(FI->second.first->getType()) + "'");
2968 Sentinel->replaceAllUsesWith(Inst);
2969 Sentinel->deleteValue();
2970 ForwardRefVals.erase(FI);
2973 // Set the name on the instruction.
2974 Inst->setName(NameStr);
2976 if (Inst->getName() != NameStr)
2977 return P.Error(NameLoc, "multiple definition of local value named '" +
2982 /// GetBB - Get a basic block with the specified name or ID, creating a
2983 /// forward reference record if needed.
2984 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2986 return dyn_cast_or_null<BasicBlock>(
2987 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2990 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2991 return dyn_cast_or_null<BasicBlock>(
2992 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2995 /// DefineBB - Define the specified basic block, which is either named or
2996 /// unnamed. If there is an error, this returns null otherwise it returns
2997 /// the block being defined.
2998 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2999 int NameID, LocTy Loc) {
3002 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3003 P.Error(Loc, "label expected to be numbered '" +
3004 Twine(NumberedVals.size()) + "'");
3007 BB = GetBB(NumberedVals.size(), Loc);
3009 P.Error(Loc, "unable to create block numbered '" +
3010 Twine(NumberedVals.size()) + "'");
3014 BB = GetBB(Name, Loc);
3016 P.Error(Loc, "unable to create block named '" + Name + "'");
3021 // Move the block to the end of the function. Forward ref'd blocks are
3022 // inserted wherever they happen to be referenced.
3023 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3025 // Remove the block from forward ref sets.
3027 ForwardRefValIDs.erase(NumberedVals.size());
3028 NumberedVals.push_back(BB);
3030 // BB forward references are already in the function symbol table.
3031 ForwardRefVals.erase(Name);
3037 //===----------------------------------------------------------------------===//
3039 //===----------------------------------------------------------------------===//
3041 /// ParseValID - Parse an abstract value that doesn't necessarily have a
3042 /// type implied. For example, if we parse "4" we don't know what integer type
3043 /// it has. The value will later be combined with its type and checked for
3044 /// sanity. PFS is used to convert function-local operands of metadata (since
3045 /// metadata operands are not just parsed here but also converted to values).
3046 /// PFS can be null when we are not parsing metadata values inside a function.
3047 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
3048 ID.Loc = Lex.getLoc();
3049 switch (Lex.getKind()) {
3050 default: return TokError("expected value token");
3051 case lltok::GlobalID: // @42
3052 ID.UIntVal = Lex.getUIntVal();
3053 ID.Kind = ValID::t_GlobalID;
3055 case lltok::GlobalVar: // @foo
3056 ID.StrVal = Lex.getStrVal();
3057 ID.Kind = ValID::t_GlobalName;
3059 case lltok::LocalVarID: // %42
3060 ID.UIntVal = Lex.getUIntVal();
3061 ID.Kind = ValID::t_LocalID;
3063 case lltok::LocalVar: // %foo
3064 ID.StrVal = Lex.getStrVal();
3065 ID.Kind = ValID::t_LocalName;
3068 ID.APSIntVal = Lex.getAPSIntVal();
3069 ID.Kind = ValID::t_APSInt;
3071 case lltok::APFloat:
3072 ID.APFloatVal = Lex.getAPFloatVal();
3073 ID.Kind = ValID::t_APFloat;
3075 case lltok::kw_true:
3076 ID.ConstantVal = ConstantInt::getTrue(Context);
3077 ID.Kind = ValID::t_Constant;
3079 case lltok::kw_false:
3080 ID.ConstantVal = ConstantInt::getFalse(Context);
3081 ID.Kind = ValID::t_Constant;
3083 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3084 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3085 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3086 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3088 case lltok::lbrace: {
3089 // ValID ::= '{' ConstVector '}'
3091 SmallVector<Constant*, 16> Elts;
3092 if (ParseGlobalValueVector(Elts) ||
3093 ParseToken(lltok::rbrace, "expected end of struct constant"))
3096 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3097 ID.UIntVal = Elts.size();
3098 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3099 Elts.size() * sizeof(Elts[0]));
3100 ID.Kind = ValID::t_ConstantStruct;
3104 // ValID ::= '<' ConstVector '>' --> Vector.
3105 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3107 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3109 SmallVector<Constant*, 16> Elts;
3110 LocTy FirstEltLoc = Lex.getLoc();
3111 if (ParseGlobalValueVector(Elts) ||
3113 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3114 ParseToken(lltok::greater, "expected end of constant"))
3117 if (isPackedStruct) {
3118 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3119 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3120 Elts.size() * sizeof(Elts[0]));
3121 ID.UIntVal = Elts.size();
3122 ID.Kind = ValID::t_PackedConstantStruct;
3127 return Error(ID.Loc, "constant vector must not be empty");
3129 if (!Elts[0]->getType()->isIntegerTy() &&
3130 !Elts[0]->getType()->isFloatingPointTy() &&
3131 !Elts[0]->getType()->isPointerTy())
3132 return Error(FirstEltLoc,
3133 "vector elements must have integer, pointer or floating point type");
3135 // Verify that all the vector elements have the same type.
3136 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3137 if (Elts[i]->getType() != Elts[0]->getType())
3138 return Error(FirstEltLoc,
3139 "vector element #" + Twine(i) +
3140 " is not of type '" + getTypeString(Elts[0]->getType()));
3142 ID.ConstantVal = ConstantVector::get(Elts);
3143 ID.Kind = ValID::t_Constant;
3146 case lltok::lsquare: { // Array Constant
3148 SmallVector<Constant*, 16> Elts;
3149 LocTy FirstEltLoc = Lex.getLoc();
3150 if (ParseGlobalValueVector(Elts) ||
3151 ParseToken(lltok::rsquare, "expected end of array constant"))
3154 // Handle empty element.
3156 // Use undef instead of an array because it's inconvenient to determine
3157 // the element type at this point, there being no elements to examine.
3158 ID.Kind = ValID::t_EmptyArray;
3162 if (!Elts[0]->getType()->isFirstClassType())
3163 return Error(FirstEltLoc, "invalid array element type: " +
3164 getTypeString(Elts[0]->getType()));
3166 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3168 // Verify all elements are correct type!
3169 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3170 if (Elts[i]->getType() != Elts[0]->getType())
3171 return Error(FirstEltLoc,
3172 "array element #" + Twine(i) +
3173 " is not of type '" + getTypeString(Elts[0]->getType()));
3176 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3177 ID.Kind = ValID::t_Constant;
3180 case lltok::kw_c: // c "foo"
3182 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3184 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3185 ID.Kind = ValID::t_Constant;
3188 case lltok::kw_asm: {
3189 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3191 bool HasSideEffect, AlignStack, AsmDialect;
3193 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3194 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3195 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3196 ParseStringConstant(ID.StrVal) ||
3197 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3198 ParseToken(lltok::StringConstant, "expected constraint string"))
3200 ID.StrVal2 = Lex.getStrVal();
3201 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3202 (unsigned(AsmDialect)<<2);
3203 ID.Kind = ValID::t_InlineAsm;
3207 case lltok::kw_blockaddress: {
3208 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3213 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3215 ParseToken(lltok::comma, "expected comma in block address expression")||
3216 ParseValID(Label) ||
3217 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3220 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3221 return Error(Fn.Loc, "expected function name in blockaddress");
3222 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3223 return Error(Label.Loc, "expected basic block name in blockaddress");
3225 // Try to find the function (but skip it if it's forward-referenced).
3226 GlobalValue *GV = nullptr;
3227 if (Fn.Kind == ValID::t_GlobalID) {
3228 if (Fn.UIntVal < NumberedVals.size())
3229 GV = NumberedVals[Fn.UIntVal];
3230 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3231 GV = M->getNamedValue(Fn.StrVal);
3233 Function *F = nullptr;
3235 // Confirm that it's actually a function with a definition.
3236 if (!isa<Function>(GV))
3237 return Error(Fn.Loc, "expected function name in blockaddress");
3238 F = cast<Function>(GV);
3239 if (F->isDeclaration())
3240 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3244 // Make a global variable as a placeholder for this reference.
3245 GlobalValue *&FwdRef =
3246 ForwardRefBlockAddresses.insert(std::make_pair(
3248 std::map<ValID, GlobalValue *>()))
3249 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3252 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3253 GlobalValue::InternalLinkage, nullptr, "");
3254 ID.ConstantVal = FwdRef;
3255 ID.Kind = ValID::t_Constant;
3259 // We found the function; now find the basic block. Don't use PFS, since we
3260 // might be inside a constant expression.
3262 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3263 if (Label.Kind == ValID::t_LocalID)
3264 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3266 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3268 return Error(Label.Loc, "referenced value is not a basic block");
3270 if (Label.Kind == ValID::t_LocalID)
3271 return Error(Label.Loc, "cannot take address of numeric label after "
3272 "the function is defined");
3273 BB = dyn_cast_or_null<BasicBlock>(
3274 F->getValueSymbolTable()->lookup(Label.StrVal));
3276 return Error(Label.Loc, "referenced value is not a basic block");
3279 ID.ConstantVal = BlockAddress::get(F, BB);
3280 ID.Kind = ValID::t_Constant;
3284 case lltok::kw_trunc:
3285 case lltok::kw_zext:
3286 case lltok::kw_sext:
3287 case lltok::kw_fptrunc:
3288 case lltok::kw_fpext:
3289 case lltok::kw_bitcast:
3290 case lltok::kw_addrspacecast:
3291 case lltok::kw_uitofp:
3292 case lltok::kw_sitofp:
3293 case lltok::kw_fptoui:
3294 case lltok::kw_fptosi:
3295 case lltok::kw_inttoptr:
3296 case lltok::kw_ptrtoint: {
3297 unsigned Opc = Lex.getUIntVal();
3298 Type *DestTy = nullptr;
3301 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3302 ParseGlobalTypeAndValue(SrcVal) ||
3303 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3304 ParseType(DestTy) ||
3305 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3307 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3308 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3309 getTypeString(SrcVal->getType()) + "' to '" +
3310 getTypeString(DestTy) + "'");
3311 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3313 ID.Kind = ValID::t_Constant;
3316 case lltok::kw_extractvalue: {
3319 SmallVector<unsigned, 4> Indices;
3320 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3321 ParseGlobalTypeAndValue(Val) ||
3322 ParseIndexList(Indices) ||
3323 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3326 if (!Val->getType()->isAggregateType())
3327 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3328 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3329 return Error(ID.Loc, "invalid indices for extractvalue");
3330 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3331 ID.Kind = ValID::t_Constant;
3334 case lltok::kw_insertvalue: {
3336 Constant *Val0, *Val1;
3337 SmallVector<unsigned, 4> Indices;
3338 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3339 ParseGlobalTypeAndValue(Val0) ||
3340 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3341 ParseGlobalTypeAndValue(Val1) ||
3342 ParseIndexList(Indices) ||
3343 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3345 if (!Val0->getType()->isAggregateType())
3346 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3348 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3350 return Error(ID.Loc, "invalid indices for insertvalue");
3351 if (IndexedType != Val1->getType())
3352 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3353 getTypeString(Val1->getType()) +
3354 "' instead of '" + getTypeString(IndexedType) +
3356 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3357 ID.Kind = ValID::t_Constant;
3360 case lltok::kw_icmp:
3361 case lltok::kw_fcmp: {
3362 unsigned PredVal, Opc = Lex.getUIntVal();
3363 Constant *Val0, *Val1;
3365 if (ParseCmpPredicate(PredVal, Opc) ||
3366 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3367 ParseGlobalTypeAndValue(Val0) ||
3368 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3369 ParseGlobalTypeAndValue(Val1) ||
3370 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3373 if (Val0->getType() != Val1->getType())
3374 return Error(ID.Loc, "compare operands must have the same type");
3376 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3378 if (Opc == Instruction::FCmp) {
3379 if (!Val0->getType()->isFPOrFPVectorTy())
3380 return Error(ID.Loc, "fcmp requires floating point operands");
3381 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3383 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3384 if (!Val0->getType()->isIntOrIntVectorTy() &&
3385 !Val0->getType()->isPtrOrPtrVectorTy())
3386 return Error(ID.Loc, "icmp requires pointer or integer operands");
3387 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3389 ID.Kind = ValID::t_Constant;
3394 case lltok::kw_fneg: {
3395 unsigned Opc = Lex.getUIntVal();
3398 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3399 ParseGlobalTypeAndValue(Val) ||
3400 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3403 // Check that the type is valid for the operator.
3405 case Instruction::FNeg:
3406 if (!Val->getType()->isFPOrFPVectorTy())
3407 return Error(ID.Loc, "constexpr requires fp operands");
3409 default: llvm_unreachable("Unknown unary operator!");
3412 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3414 ID.Kind = ValID::t_Constant;
3417 // Binary Operators.
3419 case lltok::kw_fadd:
3421 case lltok::kw_fsub:
3423 case lltok::kw_fmul:
3424 case lltok::kw_udiv:
3425 case lltok::kw_sdiv:
3426 case lltok::kw_fdiv:
3427 case lltok::kw_urem:
3428 case lltok::kw_srem:
3429 case lltok::kw_frem:
3431 case lltok::kw_lshr:
3432 case lltok::kw_ashr: {
3436 unsigned Opc = Lex.getUIntVal();
3437 Constant *Val0, *Val1;
3439 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3440 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3441 if (EatIfPresent(lltok::kw_nuw))
3443 if (EatIfPresent(lltok::kw_nsw)) {
3445 if (EatIfPresent(lltok::kw_nuw))
3448 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3449 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3450 if (EatIfPresent(lltok::kw_exact))
3453 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3454 ParseGlobalTypeAndValue(Val0) ||
3455 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3456 ParseGlobalTypeAndValue(Val1) ||
3457 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3459 if (Val0->getType() != Val1->getType())
3460 return Error(ID.Loc, "operands of constexpr must have same type");
3461 // Check that the type is valid for the operator.
3463 case Instruction::Add:
3464 case Instruction::Sub:
3465 case Instruction::Mul:
3466 case Instruction::UDiv:
3467 case Instruction::SDiv:
3468 case Instruction::URem:
3469 case Instruction::SRem:
3470 case Instruction::Shl:
3471 case Instruction::AShr:
3472 case Instruction::LShr:
3473 if (!Val0->getType()->isIntOrIntVectorTy())
3474 return Error(ID.Loc, "constexpr requires integer operands");
3476 case Instruction::FAdd:
3477 case Instruction::FSub:
3478 case Instruction::FMul:
3479 case Instruction::FDiv:
3480 case Instruction::FRem:
3481 if (!Val0->getType()->isFPOrFPVectorTy())
3482 return Error(ID.Loc, "constexpr requires fp operands");
3484 default: llvm_unreachable("Unknown binary operator!");
3487 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3488 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3489 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3490 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3492 ID.Kind = ValID::t_Constant;
3496 // Logical Operations
3499 case lltok::kw_xor: {
3500 unsigned Opc = Lex.getUIntVal();
3501 Constant *Val0, *Val1;
3503 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3504 ParseGlobalTypeAndValue(Val0) ||
3505 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3506 ParseGlobalTypeAndValue(Val1) ||
3507 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3509 if (Val0->getType() != Val1->getType())
3510 return Error(ID.Loc, "operands of constexpr must have same type");
3511 if (!Val0->getType()->isIntOrIntVectorTy())
3512 return Error(ID.Loc,
3513 "constexpr requires integer or integer vector operands");
3514 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3515 ID.Kind = ValID::t_Constant;
3519 case lltok::kw_getelementptr:
3520 case lltok::kw_shufflevector:
3521 case lltok::kw_insertelement:
3522 case lltok::kw_extractelement:
3523 case lltok::kw_select: {
3524 unsigned Opc = Lex.getUIntVal();
3525 SmallVector<Constant*, 16> Elts;
3526 bool InBounds = false;
3530 if (Opc == Instruction::GetElementPtr)
3531 InBounds = EatIfPresent(lltok::kw_inbounds);
3533 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3536 LocTy ExplicitTypeLoc = Lex.getLoc();
3537 if (Opc == Instruction::GetElementPtr) {
3538 if (ParseType(Ty) ||
3539 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3543 Optional<unsigned> InRangeOp;
3544 if (ParseGlobalValueVector(
3545 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3546 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3549 if (Opc == Instruction::GetElementPtr) {
3550 if (Elts.size() == 0 ||
3551 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3552 return Error(ID.Loc, "base of getelementptr must be a pointer");
3554 Type *BaseType = Elts[0]->getType();
3555 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3556 if (Ty != BasePointerType->getElementType())
3559 "explicit pointee type doesn't match operand's pointee type");
3562 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3564 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3565 for (Constant *Val : Indices) {
3566 Type *ValTy = Val->getType();
3567 if (!ValTy->isIntOrIntVectorTy())
3568 return Error(ID.Loc, "getelementptr index must be an integer");
3569 if (ValTy->isVectorTy()) {
3570 unsigned ValNumEl = ValTy->getVectorNumElements();
3571 if (GEPWidth && (ValNumEl != GEPWidth))
3574 "getelementptr vector index has a wrong number of elements");
3575 // GEPWidth may have been unknown because the base is a scalar,
3576 // but it is known now.
3577 GEPWidth = ValNumEl;
3581 SmallPtrSet<Type*, 4> Visited;
3582 if (!Indices.empty() && !Ty->isSized(&Visited))
3583 return Error(ID.Loc, "base element of getelementptr must be sized");
3585 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3586 return Error(ID.Loc, "invalid getelementptr indices");
3589 if (*InRangeOp == 0)
3590 return Error(ID.Loc,
3591 "inrange keyword may not appear on pointer operand");
3595 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3596 InBounds, InRangeOp);
3597 } else if (Opc == Instruction::Select) {
3598 if (Elts.size() != 3)
3599 return Error(ID.Loc, "expected three operands to select");
3600 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3602 return Error(ID.Loc, Reason);
3603 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3604 } else if (Opc == Instruction::ShuffleVector) {
3605 if (Elts.size() != 3)
3606 return Error(ID.Loc, "expected three operands to shufflevector");
3607 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3608 return Error(ID.Loc, "invalid operands to shufflevector");
3610 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3611 } else if (Opc == Instruction::ExtractElement) {
3612 if (Elts.size() != 2)
3613 return Error(ID.Loc, "expected two operands to extractelement");
3614 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3615 return Error(ID.Loc, "invalid extractelement operands");
3616 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3618 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3619 if (Elts.size() != 3)
3620 return Error(ID.Loc, "expected three operands to insertelement");
3621 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3622 return Error(ID.Loc, "invalid insertelement operands");
3624 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3627 ID.Kind = ValID::t_Constant;
3636 /// ParseGlobalValue - Parse a global value with the specified type.
3637 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3641 bool Parsed = ParseValID(ID) ||
3642 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3643 if (V && !(C = dyn_cast<Constant>(V)))
3644 return Error(ID.Loc, "global values must be constants");
3648 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3650 return ParseType(Ty) ||
3651 ParseGlobalValue(Ty, V);
3654 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3657 LocTy KwLoc = Lex.getLoc();
3658 if (!EatIfPresent(lltok::kw_comdat))
3661 if (EatIfPresent(lltok::lparen)) {
3662 if (Lex.getKind() != lltok::ComdatVar)
3663 return TokError("expected comdat variable");
3664 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3666 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3669 if (GlobalName.empty())
3670 return TokError("comdat cannot be unnamed");
3671 C = getComdat(GlobalName, KwLoc);
3677 /// ParseGlobalValueVector
3679 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3680 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3681 Optional<unsigned> *InRangeOp) {
3683 if (Lex.getKind() == lltok::rbrace ||
3684 Lex.getKind() == lltok::rsquare ||
3685 Lex.getKind() == lltok::greater ||
3686 Lex.getKind() == lltok::rparen)
3690 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3691 *InRangeOp = Elts.size();
3694 if (ParseGlobalTypeAndValue(C)) return true;
3696 } while (EatIfPresent(lltok::comma));
3701 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3702 SmallVector<Metadata *, 16> Elts;
3703 if (ParseMDNodeVector(Elts))
3706 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3713 /// ::= !DILocation(...)
3714 bool LLParser::ParseMDNode(MDNode *&N) {
3715 if (Lex.getKind() == lltok::MetadataVar)
3716 return ParseSpecializedMDNode(N);
3718 return ParseToken(lltok::exclaim, "expected '!' here") ||
3722 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3724 if (Lex.getKind() == lltok::lbrace)
3725 return ParseMDTuple(N);
3728 return ParseMDNodeID(N);
3733 /// Structure to represent an optional metadata field.
3734 template <class FieldTy> struct MDFieldImpl {
3735 typedef MDFieldImpl ImplTy;
3739 void assign(FieldTy Val) {
3741 this->Val = std::move(Val);
3744 explicit MDFieldImpl(FieldTy Default)
3745 : Val(std::move(Default)), Seen(false) {}
3748 /// Structure to represent an optional metadata field that
3749 /// can be of either type (A or B) and encapsulates the
3750 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3751 /// to reimplement the specifics for representing each Field.
3752 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3753 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3764 void assign(FieldTypeA A) {
3766 this->A = std::move(A);
3770 void assign(FieldTypeB B) {
3772 this->B = std::move(B);
3776 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3777 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3778 WhatIs(IsInvalid) {}
3781 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3784 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3785 : ImplTy(Default), Max(Max) {}
3788 struct LineField : public MDUnsignedField {
3789 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3792 struct ColumnField : public MDUnsignedField {
3793 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3796 struct DwarfTagField : public MDUnsignedField {
3797 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3798 DwarfTagField(dwarf::Tag DefaultTag)
3799 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3802 struct DwarfMacinfoTypeField : public MDUnsignedField {
3803 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3804 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3805 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3808 struct DwarfAttEncodingField : public MDUnsignedField {
3809 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3812 struct DwarfVirtualityField : public MDUnsignedField {
3813 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3816 struct DwarfLangField : public MDUnsignedField {
3817 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3820 struct DwarfCCField : public MDUnsignedField {
3821 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3824 struct EmissionKindField : public MDUnsignedField {
3825 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3828 struct NameTableKindField : public MDUnsignedField {
3829 NameTableKindField()
3832 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3835 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3836 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3839 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3840 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3843 struct MDSignedField : public MDFieldImpl<int64_t> {
3847 MDSignedField(int64_t Default = 0)
3848 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3849 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3850 : ImplTy(Default), Min(Min), Max(Max) {}
3853 struct MDBoolField : public MDFieldImpl<bool> {
3854 MDBoolField(bool Default = false) : ImplTy(Default) {}
3857 struct MDField : public MDFieldImpl<Metadata *> {
3860 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3863 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3864 MDConstant() : ImplTy(nullptr) {}
3867 struct MDStringField : public MDFieldImpl<MDString *> {
3869 MDStringField(bool AllowEmpty = true)
3870 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3873 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3874 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3877 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3878 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3881 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3882 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3883 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3885 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3886 bool AllowNull = true)
3887 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3889 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3890 bool isMDField() const { return WhatIs == IsTypeB; }
3891 int64_t getMDSignedValue() const {
3892 assert(isMDSignedField() && "Wrong field type");
3895 Metadata *getMDFieldValue() const {
3896 assert(isMDField() && "Wrong field type");
3901 struct MDSignedOrUnsignedField
3902 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3903 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3905 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3906 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3907 int64_t getMDSignedValue() const {
3908 assert(isMDSignedField() && "Wrong field type");
3911 uint64_t getMDUnsignedValue() const {
3912 assert(isMDUnsignedField() && "Wrong field type");
3917 } // end anonymous namespace
3922 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3923 MDUnsignedField &Result) {
3924 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3925 return TokError("expected unsigned integer");
3927 auto &U = Lex.getAPSIntVal();
3928 if (U.ugt(Result.Max))
3929 return TokError("value for '" + Name + "' too large, limit is " +
3931 Result.assign(U.getZExtValue());
3932 assert(Result.Val <= Result.Max && "Expected value in range");
3938 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3939 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3942 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3943 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3947 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3948 if (Lex.getKind() == lltok::APSInt)
3949 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3951 if (Lex.getKind() != lltok::DwarfTag)
3952 return TokError("expected DWARF tag");
3954 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3955 if (Tag == dwarf::DW_TAG_invalid)
3956 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3957 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3965 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3966 DwarfMacinfoTypeField &Result) {
3967 if (Lex.getKind() == lltok::APSInt)
3968 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3970 if (Lex.getKind() != lltok::DwarfMacinfo)
3971 return TokError("expected DWARF macinfo type");
3973 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3974 if (Macinfo == dwarf::DW_MACINFO_invalid)
3976 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3977 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3979 Result.assign(Macinfo);
3985 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3986 DwarfVirtualityField &Result) {
3987 if (Lex.getKind() == lltok::APSInt)
3988 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3990 if (Lex.getKind() != lltok::DwarfVirtuality)
3991 return TokError("expected DWARF virtuality code");
3993 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3994 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3995 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3996 Lex.getStrVal() + "'");
3997 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3998 Result.assign(Virtuality);
4004 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4005 if (Lex.getKind() == lltok::APSInt)
4006 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4008 if (Lex.getKind() != lltok::DwarfLang)
4009 return TokError("expected DWARF language");
4011 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4013 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4015 assert(Lang <= Result.Max && "Expected valid DWARF language");
4016 Result.assign(Lang);
4022 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4023 if (Lex.getKind() == lltok::APSInt)
4024 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4026 if (Lex.getKind() != lltok::DwarfCC)
4027 return TokError("expected DWARF calling convention");
4029 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4031 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
4033 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4040 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
4041 if (Lex.getKind() == lltok::APSInt)
4042 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4044 if (Lex.getKind() != lltok::EmissionKind)
4045 return TokError("expected emission kind");
4047 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4049 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4051 assert(*Kind <= Result.Max && "Expected valid emission kind");
4052 Result.assign(*Kind);
4058 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4059 NameTableKindField &Result) {
4060 if (Lex.getKind() == lltok::APSInt)
4061 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4063 if (Lex.getKind() != lltok::NameTableKind)
4064 return TokError("expected nameTable kind");
4066 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4068 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4070 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4071 Result.assign((unsigned)*Kind);
4077 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4078 DwarfAttEncodingField &Result) {
4079 if (Lex.getKind() == lltok::APSInt)
4080 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4082 if (Lex.getKind() != lltok::DwarfAttEncoding)
4083 return TokError("expected DWARF type attribute encoding");
4085 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4087 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4088 Lex.getStrVal() + "'");
4089 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4090 Result.assign(Encoding);
4097 /// ::= DIFlagVector
4098 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4100 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4102 // Parser for a single flag.
4103 auto parseFlag = [&](DINode::DIFlags &Val) {
4104 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4105 uint32_t TempVal = static_cast<uint32_t>(Val);
4106 bool Res = ParseUInt32(TempVal);
4107 Val = static_cast<DINode::DIFlags>(TempVal);
4111 if (Lex.getKind() != lltok::DIFlag)
4112 return TokError("expected debug info flag");
4114 Val = DINode::getFlag(Lex.getStrVal());
4116 return TokError(Twine("invalid debug info flag flag '") +
4117 Lex.getStrVal() + "'");
4122 // Parse the flags and combine them together.
4123 DINode::DIFlags Combined = DINode::FlagZero;
4125 DINode::DIFlags Val;
4129 } while (EatIfPresent(lltok::bar));
4131 Result.assign(Combined);
4137 /// ::= DISPFlagVector
4138 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4140 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4142 // Parser for a single flag.
4143 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4144 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4145 uint32_t TempVal = static_cast<uint32_t>(Val);
4146 bool Res = ParseUInt32(TempVal);
4147 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4151 if (Lex.getKind() != lltok::DISPFlag)
4152 return TokError("expected debug info flag");
4154 Val = DISubprogram::getFlag(Lex.getStrVal());
4156 return TokError(Twine("invalid subprogram debug info flag '") +
4157 Lex.getStrVal() + "'");
4162 // Parse the flags and combine them together.
4163 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4165 DISubprogram::DISPFlags Val;
4169 } while (EatIfPresent(lltok::bar));
4171 Result.assign(Combined);
4176 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4177 MDSignedField &Result) {
4178 if (Lex.getKind() != lltok::APSInt)
4179 return TokError("expected signed integer");
4181 auto &S = Lex.getAPSIntVal();
4183 return TokError("value for '" + Name + "' too small, limit is " +
4186 return TokError("value for '" + Name + "' too large, limit is " +
4188 Result.assign(S.getExtValue());
4189 assert(Result.Val >= Result.Min && "Expected value in range");
4190 assert(Result.Val <= Result.Max && "Expected value in range");
4196 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4197 switch (Lex.getKind()) {
4199 return TokError("expected 'true' or 'false'");
4200 case lltok::kw_true:
4201 Result.assign(true);
4203 case lltok::kw_false:
4204 Result.assign(false);
4212 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4213 if (Lex.getKind() == lltok::kw_null) {
4214 if (!Result.AllowNull)
4215 return TokError("'" + Name + "' cannot be null");
4217 Result.assign(nullptr);
4222 if (ParseMetadata(MD, nullptr))
4230 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4231 MDSignedOrMDField &Result) {
4232 // Try to parse a signed int.
4233 if (Lex.getKind() == lltok::APSInt) {
4234 MDSignedField Res = Result.A;
4235 if (!ParseMDField(Loc, Name, Res)) {
4242 // Otherwise, try to parse as an MDField.
4243 MDField Res = Result.B;
4244 if (!ParseMDField(Loc, Name, Res)) {
4253 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4254 MDSignedOrUnsignedField &Result) {
4255 if (Lex.getKind() != lltok::APSInt)
4258 if (Lex.getAPSIntVal().isSigned()) {
4259 MDSignedField Res = Result.A;
4260 if (ParseMDField(Loc, Name, Res))
4266 MDUnsignedField Res = Result.B;
4267 if (ParseMDField(Loc, Name, Res))
4274 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4275 LocTy ValueLoc = Lex.getLoc();
4277 if (ParseStringConstant(S))
4280 if (!Result.AllowEmpty && S.empty())
4281 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4283 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4288 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4289 SmallVector<Metadata *, 4> MDs;
4290 if (ParseMDNodeVector(MDs))
4293 Result.assign(std::move(MDs));
4298 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4299 ChecksumKindField &Result) {
4300 Optional<DIFile::ChecksumKind> CSKind =
4301 DIFile::getChecksumKind(Lex.getStrVal());
4303 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4305 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4307 Result.assign(*CSKind);
4312 } // end namespace llvm
4314 template <class ParserTy>
4315 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4317 if (Lex.getKind() != lltok::LabelStr)
4318 return TokError("expected field label here");
4322 } while (EatIfPresent(lltok::comma));
4327 template <class ParserTy>
4328 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4329 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4332 if (ParseToken(lltok::lparen, "expected '(' here"))
4334 if (Lex.getKind() != lltok::rparen)
4335 if (ParseMDFieldsImplBody(parseField))
4338 ClosingLoc = Lex.getLoc();
4339 return ParseToken(lltok::rparen, "expected ')' here");
4342 template <class FieldTy>
4343 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4345 return TokError("field '" + Name + "' cannot be specified more than once");
4347 LocTy Loc = Lex.getLoc();
4349 return ParseMDField(Loc, Name, Result);
4352 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4353 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4355 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4356 if (Lex.getStrVal() == #CLASS) \
4357 return Parse##CLASS(N, IsDistinct);
4358 #include "llvm/IR/Metadata.def"
4360 return TokError("expected metadata type");
4363 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4364 #define NOP_FIELD(NAME, TYPE, INIT)
4365 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4367 return Error(ClosingLoc, "missing required field '" #NAME "'");
4368 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4369 if (Lex.getStrVal() == #NAME) \
4370 return ParseMDField(#NAME, NAME);
4371 #define PARSE_MD_FIELDS() \
4372 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4375 if (ParseMDFieldsImpl([&]() -> bool { \
4376 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4377 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4380 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4382 #define GET_OR_DISTINCT(CLASS, ARGS) \
4383 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4385 /// ParseDILocationFields:
4386 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4387 /// isImplicitCode: true)
4388 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4389 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4390 OPTIONAL(line, LineField, ); \
4391 OPTIONAL(column, ColumnField, ); \
4392 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4393 OPTIONAL(inlinedAt, MDField, ); \
4394 OPTIONAL(isImplicitCode, MDBoolField, (false));
4396 #undef VISIT_MD_FIELDS
4399 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4400 inlinedAt.Val, isImplicitCode.Val));
4404 /// ParseGenericDINode:
4405 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4406 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4407 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4408 REQUIRED(tag, DwarfTagField, ); \
4409 OPTIONAL(header, MDStringField, ); \
4410 OPTIONAL(operands, MDFieldList, );
4412 #undef VISIT_MD_FIELDS
4414 Result = GET_OR_DISTINCT(GenericDINode,
4415 (Context, tag.Val, header.Val, operands.Val));
4419 /// ParseDISubrange:
4420 /// ::= !DISubrange(count: 30, lowerBound: 2)
4421 /// ::= !DISubrange(count: !node, lowerBound: 2)
4422 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4423 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4424 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4425 OPTIONAL(lowerBound, MDSignedField, );
4427 #undef VISIT_MD_FIELDS
4429 if (count.isMDSignedField())
4430 Result = GET_OR_DISTINCT(
4431 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4432 else if (count.isMDField())
4433 Result = GET_OR_DISTINCT(
4434 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4441 /// ParseDIEnumerator:
4442 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4443 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4444 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4445 REQUIRED(name, MDStringField, ); \
4446 REQUIRED(value, MDSignedOrUnsignedField, ); \
4447 OPTIONAL(isUnsigned, MDBoolField, (false));
4449 #undef VISIT_MD_FIELDS
4451 if (isUnsigned.Val && value.isMDSignedField())
4452 return TokError("unsigned enumerator with negative value");
4454 int64_t Value = value.isMDSignedField()
4455 ? value.getMDSignedValue()
4456 : static_cast<int64_t>(value.getMDUnsignedValue());
4458 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4463 /// ParseDIBasicType:
4464 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4465 /// encoding: DW_ATE_encoding, flags: 0)
4466 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4467 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4468 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4469 OPTIONAL(name, MDStringField, ); \
4470 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4471 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4472 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4473 OPTIONAL(flags, DIFlagField, );
4475 #undef VISIT_MD_FIELDS
4477 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4478 align.Val, encoding.Val, flags.Val));
4482 /// ParseDIDerivedType:
4483 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4484 /// line: 7, scope: !1, baseType: !2, size: 32,
4485 /// align: 32, offset: 0, flags: 0, extraData: !3,
4486 /// dwarfAddressSpace: 3)
4487 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4488 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4489 REQUIRED(tag, DwarfTagField, ); \
4490 OPTIONAL(name, MDStringField, ); \
4491 OPTIONAL(file, MDField, ); \
4492 OPTIONAL(line, LineField, ); \
4493 OPTIONAL(scope, MDField, ); \
4494 REQUIRED(baseType, MDField, ); \
4495 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4496 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4497 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4498 OPTIONAL(flags, DIFlagField, ); \
4499 OPTIONAL(extraData, MDField, ); \
4500 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4502 #undef VISIT_MD_FIELDS
4504 Optional<unsigned> DWARFAddressSpace;
4505 if (dwarfAddressSpace.Val != UINT32_MAX)
4506 DWARFAddressSpace = dwarfAddressSpace.Val;
4508 Result = GET_OR_DISTINCT(DIDerivedType,
4509 (Context, tag.Val, name.Val, file.Val, line.Val,
4510 scope.Val, baseType.Val, size.Val, align.Val,
4511 offset.Val, DWARFAddressSpace, flags.Val,
4516 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4517 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4518 REQUIRED(tag, DwarfTagField, ); \
4519 OPTIONAL(name, MDStringField, ); \
4520 OPTIONAL(file, MDField, ); \
4521 OPTIONAL(line, LineField, ); \
4522 OPTIONAL(scope, MDField, ); \
4523 OPTIONAL(baseType, MDField, ); \
4524 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4525 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4526 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4527 OPTIONAL(flags, DIFlagField, ); \
4528 OPTIONAL(elements, MDField, ); \
4529 OPTIONAL(runtimeLang, DwarfLangField, ); \
4530 OPTIONAL(vtableHolder, MDField, ); \
4531 OPTIONAL(templateParams, MDField, ); \
4532 OPTIONAL(identifier, MDStringField, ); \
4533 OPTIONAL(discriminator, MDField, );
4535 #undef VISIT_MD_FIELDS
4537 // If this has an identifier try to build an ODR type.
4539 if (auto *CT = DICompositeType::buildODRType(
4540 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4541 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4542 elements.Val, runtimeLang.Val, vtableHolder.Val,
4543 templateParams.Val, discriminator.Val)) {
4548 // Create a new node, and save it in the context if it belongs in the type
4550 Result = GET_OR_DISTINCT(
4552 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4553 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4554 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4555 discriminator.Val));
4559 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4560 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4561 OPTIONAL(flags, DIFlagField, ); \
4562 OPTIONAL(cc, DwarfCCField, ); \
4563 REQUIRED(types, MDField, );
4565 #undef VISIT_MD_FIELDS
4567 Result = GET_OR_DISTINCT(DISubroutineType,
4568 (Context, flags.Val, cc.Val, types.Val));
4572 /// ParseDIFileType:
4573 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4574 /// checksumkind: CSK_MD5,
4575 /// checksum: "000102030405060708090a0b0c0d0e0f",
4576 /// source: "source file contents")
4577 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4578 // The default constructed value for checksumkind is required, but will never
4579 // be used, as the parser checks if the field was actually Seen before using
4581 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4582 REQUIRED(filename, MDStringField, ); \
4583 REQUIRED(directory, MDStringField, ); \
4584 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4585 OPTIONAL(checksum, MDStringField, ); \
4586 OPTIONAL(source, MDStringField, );
4588 #undef VISIT_MD_FIELDS
4590 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4591 if (checksumkind.Seen && checksum.Seen)
4592 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4593 else if (checksumkind.Seen || checksum.Seen)
4594 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4596 Optional<MDString *> OptSource;
4598 OptSource = source.Val;
4599 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4600 OptChecksum, OptSource));
4604 /// ParseDICompileUnit:
4605 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4606 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4607 /// splitDebugFilename: "abc.debug",
4608 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4609 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4610 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4612 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4614 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4615 REQUIRED(language, DwarfLangField, ); \
4616 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4617 OPTIONAL(producer, MDStringField, ); \
4618 OPTIONAL(isOptimized, MDBoolField, ); \
4619 OPTIONAL(flags, MDStringField, ); \
4620 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4621 OPTIONAL(splitDebugFilename, MDStringField, ); \
4622 OPTIONAL(emissionKind, EmissionKindField, ); \
4623 OPTIONAL(enums, MDField, ); \
4624 OPTIONAL(retainedTypes, MDField, ); \
4625 OPTIONAL(globals, MDField, ); \
4626 OPTIONAL(imports, MDField, ); \
4627 OPTIONAL(macros, MDField, ); \
4628 OPTIONAL(dwoId, MDUnsignedField, ); \
4629 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4630 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4631 OPTIONAL(nameTableKind, NameTableKindField, ); \
4632 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4634 #undef VISIT_MD_FIELDS
4636 Result = DICompileUnit::getDistinct(
4637 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4638 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4639 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4640 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4641 debugBaseAddress.Val);
4645 /// ParseDISubprogram:
4646 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4647 /// file: !1, line: 7, type: !2, isLocal: false,
4648 /// isDefinition: true, scopeLine: 8, containingType: !3,
4649 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4650 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4651 /// spFlags: 10, isOptimized: false, templateParams: !4,
4652 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4653 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4654 auto Loc = Lex.getLoc();
4655 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4656 OPTIONAL(scope, MDField, ); \
4657 OPTIONAL(name, MDStringField, ); \
4658 OPTIONAL(linkageName, MDStringField, ); \
4659 OPTIONAL(file, MDField, ); \
4660 OPTIONAL(line, LineField, ); \
4661 OPTIONAL(type, MDField, ); \
4662 OPTIONAL(isLocal, MDBoolField, ); \
4663 OPTIONAL(isDefinition, MDBoolField, (true)); \
4664 OPTIONAL(scopeLine, LineField, ); \
4665 OPTIONAL(containingType, MDField, ); \
4666 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4667 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4668 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4669 OPTIONAL(flags, DIFlagField, ); \
4670 OPTIONAL(spFlags, DISPFlagField, ); \
4671 OPTIONAL(isOptimized, MDBoolField, ); \
4672 OPTIONAL(unit, MDField, ); \
4673 OPTIONAL(templateParams, MDField, ); \
4674 OPTIONAL(declaration, MDField, ); \
4675 OPTIONAL(retainedNodes, MDField, ); \
4676 OPTIONAL(thrownTypes, MDField, );
4678 #undef VISIT_MD_FIELDS
4680 // An explicit spFlags field takes precedence over individual fields in
4681 // older IR versions.
4682 DISubprogram::DISPFlags SPFlags =
4683 spFlags.Seen ? spFlags.Val
4684 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4685 isOptimized.Val, virtuality.Val);
4686 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4689 "missing 'distinct', required for !DISubprogram that is a Definition");
4690 Result = GET_OR_DISTINCT(
4692 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4693 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4694 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4695 declaration.Val, retainedNodes.Val, thrownTypes.Val));
4699 /// ParseDILexicalBlock:
4700 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4701 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4702 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4703 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4704 OPTIONAL(file, MDField, ); \
4705 OPTIONAL(line, LineField, ); \
4706 OPTIONAL(column, ColumnField, );
4708 #undef VISIT_MD_FIELDS
4710 Result = GET_OR_DISTINCT(
4711 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4715 /// ParseDILexicalBlockFile:
4716 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4717 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4718 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4719 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4720 OPTIONAL(file, MDField, ); \
4721 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4723 #undef VISIT_MD_FIELDS
4725 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4726 (Context, scope.Val, file.Val, discriminator.Val));
4730 /// ParseDICommonBlock:
4731 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4732 bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4733 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4734 REQUIRED(scope, MDField, ); \
4735 OPTIONAL(declaration, MDField, ); \
4736 OPTIONAL(name, MDStringField, ); \
4737 OPTIONAL(file, MDField, ); \
4738 OPTIONAL(line, LineField, );
4740 #undef VISIT_MD_FIELDS
4742 Result = GET_OR_DISTINCT(DICommonBlock,
4743 (Context, scope.Val, declaration.Val, name.Val,
4744 file.Val, line.Val));
4748 /// ParseDINamespace:
4749 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4750 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4751 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4752 REQUIRED(scope, MDField, ); \
4753 OPTIONAL(name, MDStringField, ); \
4754 OPTIONAL(exportSymbols, MDBoolField, );
4756 #undef VISIT_MD_FIELDS
4758 Result = GET_OR_DISTINCT(DINamespace,
4759 (Context, scope.Val, name.Val, exportSymbols.Val));
4764 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4765 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4766 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4767 REQUIRED(type, DwarfMacinfoTypeField, ); \
4768 OPTIONAL(line, LineField, ); \
4769 REQUIRED(name, MDStringField, ); \
4770 OPTIONAL(value, MDStringField, );
4772 #undef VISIT_MD_FIELDS
4774 Result = GET_OR_DISTINCT(DIMacro,
4775 (Context, type.Val, line.Val, name.Val, value.Val));
4779 /// ParseDIMacroFile:
4780 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4781 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4782 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4783 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4784 OPTIONAL(line, LineField, ); \
4785 REQUIRED(file, MDField, ); \
4786 OPTIONAL(nodes, MDField, );
4788 #undef VISIT_MD_FIELDS
4790 Result = GET_OR_DISTINCT(DIMacroFile,
4791 (Context, type.Val, line.Val, file.Val, nodes.Val));
4796 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4797 /// includePath: "/usr/include", isysroot: "/")
4798 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4799 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4800 REQUIRED(scope, MDField, ); \
4801 REQUIRED(name, MDStringField, ); \
4802 OPTIONAL(configMacros, MDStringField, ); \
4803 OPTIONAL(includePath, MDStringField, ); \
4804 OPTIONAL(isysroot, MDStringField, );
4806 #undef VISIT_MD_FIELDS
4808 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4809 configMacros.Val, includePath.Val, isysroot.Val));
4813 /// ParseDITemplateTypeParameter:
4814 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4815 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4816 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4817 OPTIONAL(name, MDStringField, ); \
4818 REQUIRED(type, MDField, );
4820 #undef VISIT_MD_FIELDS
4823 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4827 /// ParseDITemplateValueParameter:
4828 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4829 /// name: "V", type: !1, value: i32 7)
4830 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4831 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4832 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4833 OPTIONAL(name, MDStringField, ); \
4834 OPTIONAL(type, MDField, ); \
4835 REQUIRED(value, MDField, );
4837 #undef VISIT_MD_FIELDS
4839 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4840 (Context, tag.Val, name.Val, type.Val, value.Val));
4844 /// ParseDIGlobalVariable:
4845 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4846 /// file: !1, line: 7, type: !2, isLocal: false,
4847 /// isDefinition: true, templateParams: !3,
4848 /// declaration: !4, align: 8)
4849 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4850 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4851 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4852 OPTIONAL(scope, MDField, ); \
4853 OPTIONAL(linkageName, MDStringField, ); \
4854 OPTIONAL(file, MDField, ); \
4855 OPTIONAL(line, LineField, ); \
4856 OPTIONAL(type, MDField, ); \
4857 OPTIONAL(isLocal, MDBoolField, ); \
4858 OPTIONAL(isDefinition, MDBoolField, (true)); \
4859 OPTIONAL(templateParams, MDField, ); \
4860 OPTIONAL(declaration, MDField, ); \
4861 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4863 #undef VISIT_MD_FIELDS
4866 GET_OR_DISTINCT(DIGlobalVariable,
4867 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4868 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4869 declaration.Val, templateParams.Val, align.Val));
4873 /// ParseDILocalVariable:
4874 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4875 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4877 /// ::= !DILocalVariable(scope: !0, name: "foo",
4878 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4880 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4881 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4882 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4883 OPTIONAL(name, MDStringField, ); \
4884 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4885 OPTIONAL(file, MDField, ); \
4886 OPTIONAL(line, LineField, ); \
4887 OPTIONAL(type, MDField, ); \
4888 OPTIONAL(flags, DIFlagField, ); \
4889 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4891 #undef VISIT_MD_FIELDS
4893 Result = GET_OR_DISTINCT(DILocalVariable,
4894 (Context, scope.Val, name.Val, file.Val, line.Val,
4895 type.Val, arg.Val, flags.Val, align.Val));
4900 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4901 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4902 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4903 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4904 REQUIRED(name, MDStringField, ); \
4905 REQUIRED(file, MDField, ); \
4906 REQUIRED(line, LineField, );
4908 #undef VISIT_MD_FIELDS
4910 Result = GET_OR_DISTINCT(DILabel,
4911 (Context, scope.Val, name.Val, file.Val, line.Val));
4915 /// ParseDIExpression:
4916 /// ::= !DIExpression(0, 7, -1)
4917 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4918 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4921 if (ParseToken(lltok::lparen, "expected '(' here"))
4924 SmallVector<uint64_t, 8> Elements;
4925 if (Lex.getKind() != lltok::rparen)
4927 if (Lex.getKind() == lltok::DwarfOp) {
4928 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4930 Elements.push_back(Op);
4933 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4936 if (Lex.getKind() == lltok::DwarfAttEncoding) {
4937 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
4939 Elements.push_back(Op);
4942 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'");
4945 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4946 return TokError("expected unsigned integer");
4948 auto &U = Lex.getAPSIntVal();
4949 if (U.ugt(UINT64_MAX))
4950 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4951 Elements.push_back(U.getZExtValue());
4953 } while (EatIfPresent(lltok::comma));
4955 if (ParseToken(lltok::rparen, "expected ')' here"))
4958 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4962 /// ParseDIGlobalVariableExpression:
4963 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4964 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4966 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4967 REQUIRED(var, MDField, ); \
4968 REQUIRED(expr, MDField, );
4970 #undef VISIT_MD_FIELDS
4973 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4977 /// ParseDIObjCProperty:
4978 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4979 /// getter: "getFoo", attributes: 7, type: !2)
4980 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4981 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4982 OPTIONAL(name, MDStringField, ); \
4983 OPTIONAL(file, MDField, ); \
4984 OPTIONAL(line, LineField, ); \
4985 OPTIONAL(setter, MDStringField, ); \
4986 OPTIONAL(getter, MDStringField, ); \
4987 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4988 OPTIONAL(type, MDField, );
4990 #undef VISIT_MD_FIELDS
4992 Result = GET_OR_DISTINCT(DIObjCProperty,
4993 (Context, name.Val, file.Val, line.Val, setter.Val,
4994 getter.Val, attributes.Val, type.Val));
4998 /// ParseDIImportedEntity:
4999 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5000 /// line: 7, name: "foo")
5001 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5002 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5003 REQUIRED(tag, DwarfTagField, ); \
5004 REQUIRED(scope, MDField, ); \
5005 OPTIONAL(entity, MDField, ); \
5006 OPTIONAL(file, MDField, ); \
5007 OPTIONAL(line, LineField, ); \
5008 OPTIONAL(name, MDStringField, );
5010 #undef VISIT_MD_FIELDS
5012 Result = GET_OR_DISTINCT(
5014 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
5018 #undef PARSE_MD_FIELD
5020 #undef REQUIRE_FIELD
5021 #undef DECLARE_FIELD
5023 /// ParseMetadataAsValue
5024 /// ::= metadata i32 %local
5025 /// ::= metadata i32 @global
5026 /// ::= metadata i32 7
5028 /// ::= metadata !{...}
5029 /// ::= metadata !"string"
5030 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5031 // Note: the type 'metadata' has already been parsed.
5033 if (ParseMetadata(MD, &PFS))
5036 V = MetadataAsValue::get(Context, MD);
5040 /// ParseValueAsMetadata
5044 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5045 PerFunctionState *PFS) {
5048 if (ParseType(Ty, TypeMsg, Loc))
5050 if (Ty->isMetadataTy())
5051 return Error(Loc, "invalid metadata-value-metadata roundtrip");
5054 if (ParseValue(Ty, V, PFS))
5057 MD = ValueAsMetadata::get(V);
5068 /// ::= !DILocation(...)
5069 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5070 if (Lex.getKind() == lltok::MetadataVar) {
5072 if (ParseSpecializedMDNode(N))
5080 if (Lex.getKind() != lltok::exclaim)
5081 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
5084 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5088 // ::= '!' STRINGCONSTANT
5089 if (Lex.getKind() == lltok::StringConstant) {
5091 if (ParseMDString(S))
5101 if (ParseMDNodeTail(N))
5107 //===----------------------------------------------------------------------===//
5108 // Function Parsing.
5109 //===----------------------------------------------------------------------===//
5111 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5112 PerFunctionState *PFS, bool IsCall) {
5113 if (Ty->isFunctionTy())
5114 return Error(ID.Loc, "functions are not values, refer to them as pointers");
5117 case ValID::t_LocalID:
5118 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5119 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5120 return V == nullptr;
5121 case ValID::t_LocalName:
5122 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5123 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5124 return V == nullptr;
5125 case ValID::t_InlineAsm: {
5126 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5127 return Error(ID.Loc, "invalid type for inline asm constraint string");
5128 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5129 (ID.UIntVal >> 1) & 1,
5130 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5133 case ValID::t_GlobalName:
5134 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5135 return V == nullptr;
5136 case ValID::t_GlobalID:
5137 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5138 return V == nullptr;
5139 case ValID::t_APSInt:
5140 if (!Ty->isIntegerTy())
5141 return Error(ID.Loc, "integer constant must have integer type");
5142 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5143 V = ConstantInt::get(Context, ID.APSIntVal);
5145 case ValID::t_APFloat:
5146 if (!Ty->isFloatingPointTy() ||
5147 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5148 return Error(ID.Loc, "floating point constant invalid for type");
5150 // The lexer has no type info, so builds all half, float, and double FP
5151 // constants as double. Fix this here. Long double does not need this.
5152 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5155 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5157 else if (Ty->isFloatTy())
5158 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5161 V = ConstantFP::get(Context, ID.APFloatVal);
5163 if (V->getType() != Ty)
5164 return Error(ID.Loc, "floating point constant does not have type '" +
5165 getTypeString(Ty) + "'");
5169 if (!Ty->isPointerTy())
5170 return Error(ID.Loc, "null must be a pointer type");
5171 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5173 case ValID::t_Undef:
5174 // FIXME: LabelTy should not be a first-class type.
5175 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5176 return Error(ID.Loc, "invalid type for undef constant");
5177 V = UndefValue::get(Ty);
5179 case ValID::t_EmptyArray:
5180 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5181 return Error(ID.Loc, "invalid empty array initializer");
5182 V = UndefValue::get(Ty);
5185 // FIXME: LabelTy should not be a first-class type.
5186 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5187 return Error(ID.Loc, "invalid type for null constant");
5188 V = Constant::getNullValue(Ty);
5191 if (!Ty->isTokenTy())
5192 return Error(ID.Loc, "invalid type for none constant");
5193 V = Constant::getNullValue(Ty);
5195 case ValID::t_Constant:
5196 if (ID.ConstantVal->getType() != Ty)
5197 return Error(ID.Loc, "constant expression type mismatch");
5201 case ValID::t_ConstantStruct:
5202 case ValID::t_PackedConstantStruct:
5203 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5204 if (ST->getNumElements() != ID.UIntVal)
5205 return Error(ID.Loc,
5206 "initializer with struct type has wrong # elements");
5207 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5208 return Error(ID.Loc, "packed'ness of initializer and type don't match");
5210 // Verify that the elements are compatible with the structtype.
5211 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5212 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5213 return Error(ID.Loc, "element " + Twine(i) +
5214 " of struct initializer doesn't match struct element type");
5216 V = ConstantStruct::get(
5217 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5219 return Error(ID.Loc, "constant expression type mismatch");
5222 llvm_unreachable("Invalid ValID");
5225 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5228 auto Loc = Lex.getLoc();
5229 if (ParseValID(ID, /*PFS=*/nullptr))
5232 case ValID::t_APSInt:
5233 case ValID::t_APFloat:
5234 case ValID::t_Undef:
5235 case ValID::t_Constant:
5236 case ValID::t_ConstantStruct:
5237 case ValID::t_PackedConstantStruct: {
5239 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5241 assert(isa<Constant>(V) && "Expected a constant value");
5242 C = cast<Constant>(V);
5246 C = Constant::getNullValue(Ty);
5249 return Error(Loc, "expected a constant value");
5253 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5256 return ParseValID(ID, PFS) ||
5257 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5260 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5262 return ParseType(Ty) ||
5263 ParseValue(Ty, V, PFS);
5266 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5267 PerFunctionState &PFS) {
5270 if (ParseTypeAndValue(V, PFS)) return true;
5271 if (!isa<BasicBlock>(V))
5272 return Error(Loc, "expected a basic block");
5273 BB = cast<BasicBlock>(V);
5278 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5279 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5280 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5281 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5282 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5283 // Parse the linkage.
5284 LocTy LinkageLoc = Lex.getLoc();
5286 unsigned Visibility;
5287 unsigned DLLStorageClass;
5289 AttrBuilder RetAttrs;
5292 Type *RetType = nullptr;
5293 LocTy RetTypeLoc = Lex.getLoc();
5294 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5296 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5297 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5300 // Verify that the linkage is ok.
5301 switch ((GlobalValue::LinkageTypes)Linkage) {
5302 case GlobalValue::ExternalLinkage:
5303 break; // always ok.
5304 case GlobalValue::ExternalWeakLinkage:
5306 return Error(LinkageLoc, "invalid linkage for function definition");
5308 case GlobalValue::PrivateLinkage:
5309 case GlobalValue::InternalLinkage:
5310 case GlobalValue::AvailableExternallyLinkage:
5311 case GlobalValue::LinkOnceAnyLinkage:
5312 case GlobalValue::LinkOnceODRLinkage:
5313 case GlobalValue::WeakAnyLinkage:
5314 case GlobalValue::WeakODRLinkage:
5316 return Error(LinkageLoc, "invalid linkage for function declaration");
5318 case GlobalValue::AppendingLinkage:
5319 case GlobalValue::CommonLinkage:
5320 return Error(LinkageLoc, "invalid function linkage type");
5323 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5324 return Error(LinkageLoc,
5325 "symbol with local linkage must have default visibility");
5327 if (!FunctionType::isValidReturnType(RetType))
5328 return Error(RetTypeLoc, "invalid function return type");
5330 LocTy NameLoc = Lex.getLoc();
5332 std::string FunctionName;
5333 if (Lex.getKind() == lltok::GlobalVar) {
5334 FunctionName = Lex.getStrVal();
5335 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5336 unsigned NameID = Lex.getUIntVal();
5338 if (NameID != NumberedVals.size())
5339 return TokError("function expected to be numbered '%" +
5340 Twine(NumberedVals.size()) + "'");
5342 return TokError("expected function name");
5347 if (Lex.getKind() != lltok::lparen)
5348 return TokError("expected '(' in function argument list");
5350 SmallVector<ArgInfo, 8> ArgList;
5352 AttrBuilder FuncAttrs;
5353 std::vector<unsigned> FwdRefAttrGrps;
5355 std::string Section;
5356 std::string Partition;
5359 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5360 unsigned AddrSpace = 0;
5361 Constant *Prefix = nullptr;
5362 Constant *Prologue = nullptr;
5363 Constant *PersonalityFn = nullptr;
5366 if (ParseArgumentList(ArgList, isVarArg) ||
5367 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5368 ParseOptionalProgramAddrSpace(AddrSpace) ||
5369 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5371 (EatIfPresent(lltok::kw_section) &&
5372 ParseStringConstant(Section)) ||
5373 (EatIfPresent(lltok::kw_partition) &&
5374 ParseStringConstant(Partition)) ||
5375 parseOptionalComdat(FunctionName, C) ||
5376 ParseOptionalAlignment(Alignment) ||
5377 (EatIfPresent(lltok::kw_gc) &&
5378 ParseStringConstant(GC)) ||
5379 (EatIfPresent(lltok::kw_prefix) &&
5380 ParseGlobalTypeAndValue(Prefix)) ||
5381 (EatIfPresent(lltok::kw_prologue) &&
5382 ParseGlobalTypeAndValue(Prologue)) ||
5383 (EatIfPresent(lltok::kw_personality) &&
5384 ParseGlobalTypeAndValue(PersonalityFn)))
5387 if (FuncAttrs.contains(Attribute::Builtin))
5388 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5390 // If the alignment was parsed as an attribute, move to the alignment field.
5391 if (FuncAttrs.hasAlignmentAttr()) {
5392 Alignment = FuncAttrs.getAlignment();
5393 FuncAttrs.removeAttribute(Attribute::Alignment);
5396 // Okay, if we got here, the function is syntactically valid. Convert types
5397 // and do semantic checks.
5398 std::vector<Type*> ParamTypeList;
5399 SmallVector<AttributeSet, 8> Attrs;
5401 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5402 ParamTypeList.push_back(ArgList[i].Ty);
5403 Attrs.push_back(ArgList[i].Attrs);
5407 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5408 AttributeSet::get(Context, RetAttrs), Attrs);
5410 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5411 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5414 FunctionType::get(RetType, ParamTypeList, isVarArg);
5415 PointerType *PFT = PointerType::get(FT, AddrSpace);
5418 if (!FunctionName.empty()) {
5419 // If this was a definition of a forward reference, remove the definition
5420 // from the forward reference table and fill in the forward ref.
5421 auto FRVI = ForwardRefVals.find(FunctionName);
5422 if (FRVI != ForwardRefVals.end()) {
5423 Fn = M->getFunction(FunctionName);
5425 return Error(FRVI->second.second, "invalid forward reference to "
5426 "function as global value!");
5427 if (Fn->getType() != PFT)
5428 return Error(FRVI->second.second, "invalid forward reference to "
5429 "function '" + FunctionName + "' with wrong type: "
5430 "expected '" + getTypeString(PFT) + "' but was '" +
5431 getTypeString(Fn->getType()) + "'");
5432 ForwardRefVals.erase(FRVI);
5433 } else if ((Fn = M->getFunction(FunctionName))) {
5434 // Reject redefinitions.
5435 return Error(NameLoc, "invalid redefinition of function '" +
5436 FunctionName + "'");
5437 } else if (M->getNamedValue(FunctionName)) {
5438 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5442 // If this is a definition of a forward referenced function, make sure the
5444 auto I = ForwardRefValIDs.find(NumberedVals.size());
5445 if (I != ForwardRefValIDs.end()) {
5446 Fn = cast<Function>(I->second.first);
5447 if (Fn->getType() != PFT)
5448 return Error(NameLoc, "type of definition and forward reference of '@" +
5449 Twine(NumberedVals.size()) + "' disagree: "
5450 "expected '" + getTypeString(PFT) + "' but was '" +
5451 getTypeString(Fn->getType()) + "'");
5452 ForwardRefValIDs.erase(I);
5457 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5459 else // Move the forward-reference to the correct spot in the module.
5460 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5462 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5464 if (FunctionName.empty())
5465 NumberedVals.push_back(Fn);
5467 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5468 maybeSetDSOLocal(DSOLocal, *Fn);
5469 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5470 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5471 Fn->setCallingConv(CC);
5472 Fn->setAttributes(PAL);
5473 Fn->setUnnamedAddr(UnnamedAddr);
5474 Fn->setAlignment(Alignment);
5475 Fn->setSection(Section);
5476 Fn->setPartition(Partition);
5478 Fn->setPersonalityFn(PersonalityFn);
5479 if (!GC.empty()) Fn->setGC(GC);
5480 Fn->setPrefixData(Prefix);
5481 Fn->setPrologueData(Prologue);
5482 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5484 // Add all of the arguments we parsed to the function.
5485 Function::arg_iterator ArgIt = Fn->arg_begin();
5486 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5487 // If the argument has a name, insert it into the argument symbol table.
5488 if (ArgList[i].Name.empty()) continue;
5490 // Set the name, if it conflicted, it will be auto-renamed.
5491 ArgIt->setName(ArgList[i].Name);
5493 if (ArgIt->getName() != ArgList[i].Name)
5494 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5495 ArgList[i].Name + "'");
5501 // Check the declaration has no block address forward references.
5503 if (FunctionName.empty()) {
5504 ID.Kind = ValID::t_GlobalID;
5505 ID.UIntVal = NumberedVals.size() - 1;
5507 ID.Kind = ValID::t_GlobalName;
5508 ID.StrVal = FunctionName;
5510 auto Blocks = ForwardRefBlockAddresses.find(ID);
5511 if (Blocks != ForwardRefBlockAddresses.end())
5512 return Error(Blocks->first.Loc,
5513 "cannot take blockaddress inside a declaration");
5517 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5519 if (FunctionNumber == -1) {
5520 ID.Kind = ValID::t_GlobalName;
5521 ID.StrVal = F.getName();
5523 ID.Kind = ValID::t_GlobalID;
5524 ID.UIntVal = FunctionNumber;
5527 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5528 if (Blocks == P.ForwardRefBlockAddresses.end())
5531 for (const auto &I : Blocks->second) {
5532 const ValID &BBID = I.first;
5533 GlobalValue *GV = I.second;
5535 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5536 "Expected local id or name");
5538 if (BBID.Kind == ValID::t_LocalName)
5539 BB = GetBB(BBID.StrVal, BBID.Loc);
5541 BB = GetBB(BBID.UIntVal, BBID.Loc);
5543 return P.Error(BBID.Loc, "referenced value is not a basic block");
5545 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5546 GV->eraseFromParent();
5549 P.ForwardRefBlockAddresses.erase(Blocks);
5553 /// ParseFunctionBody
5554 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5555 bool LLParser::ParseFunctionBody(Function &Fn) {
5556 if (Lex.getKind() != lltok::lbrace)
5557 return TokError("expected '{' in function body");
5558 Lex.Lex(); // eat the {.
5560 int FunctionNumber = -1;
5561 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5563 PerFunctionState PFS(*this, Fn, FunctionNumber);
5565 // Resolve block addresses and allow basic blocks to be forward-declared
5566 // within this function.
5567 if (PFS.resolveForwardRefBlockAddresses())
5569 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5571 // We need at least one basic block.
5572 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5573 return TokError("function body requires at least one basic block");
5575 while (Lex.getKind() != lltok::rbrace &&
5576 Lex.getKind() != lltok::kw_uselistorder)
5577 if (ParseBasicBlock(PFS)) return true;
5579 while (Lex.getKind() != lltok::rbrace)
5580 if (ParseUseListOrder(&PFS))
5586 // Verify function is ok.
5587 return PFS.FinishFunction();
5591 /// ::= (LabelStr|LabelID)? Instruction*
5592 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5593 // If this basic block starts out with a name, remember it.
5596 LocTy NameLoc = Lex.getLoc();
5597 if (Lex.getKind() == lltok::LabelStr) {
5598 Name = Lex.getStrVal();
5600 } else if (Lex.getKind() == lltok::LabelID) {
5601 NameID = Lex.getUIntVal();
5605 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc);
5609 std::string NameStr;
5611 // Parse the instructions in this block until we get a terminator.
5614 // This instruction may have three possibilities for a name: a) none
5615 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5616 LocTy NameLoc = Lex.getLoc();
5620 if (Lex.getKind() == lltok::LocalVarID) {
5621 NameID = Lex.getUIntVal();
5623 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5625 } else if (Lex.getKind() == lltok::LocalVar) {
5626 NameStr = Lex.getStrVal();
5628 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5632 switch (ParseInstruction(Inst, BB, PFS)) {
5633 default: llvm_unreachable("Unknown ParseInstruction result!");
5634 case InstError: return true;
5636 BB->getInstList().push_back(Inst);
5638 // With a normal result, we check to see if the instruction is followed by
5639 // a comma and metadata.
5640 if (EatIfPresent(lltok::comma))
5641 if (ParseInstructionMetadata(*Inst))
5644 case InstExtraComma:
5645 BB->getInstList().push_back(Inst);
5647 // If the instruction parser ate an extra comma at the end of it, it
5648 // *must* be followed by metadata.
5649 if (ParseInstructionMetadata(*Inst))
5654 // Set the name on the instruction.
5655 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5656 } while (!Inst->isTerminator());
5661 //===----------------------------------------------------------------------===//
5662 // Instruction Parsing.
5663 //===----------------------------------------------------------------------===//
5665 /// ParseInstruction - Parse one of the many different instructions.
5667 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5668 PerFunctionState &PFS) {
5669 lltok::Kind Token = Lex.getKind();
5670 if (Token == lltok::Eof)
5671 return TokError("found end of file when expecting more instructions");
5672 LocTy Loc = Lex.getLoc();
5673 unsigned KeywordVal = Lex.getUIntVal();
5674 Lex.Lex(); // Eat the keyword.
5677 default: return Error(Loc, "expected instruction opcode");
5678 // Terminator Instructions.
5679 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5680 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5681 case lltok::kw_br: return ParseBr(Inst, PFS);
5682 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5683 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5684 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5685 case lltok::kw_resume: return ParseResume(Inst, PFS);
5686 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5687 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5688 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5689 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5690 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5691 case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
5693 case lltok::kw_fneg: {
5694 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5695 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true);
5699 Inst->setFastMathFlags(FMF);
5702 // Binary Operators.
5706 case lltok::kw_shl: {
5707 bool NUW = EatIfPresent(lltok::kw_nuw);
5708 bool NSW = EatIfPresent(lltok::kw_nsw);
5709 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5711 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5713 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5714 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5717 case lltok::kw_fadd:
5718 case lltok::kw_fsub:
5719 case lltok::kw_fmul:
5720 case lltok::kw_fdiv:
5721 case lltok::kw_frem: {
5722 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5723 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true);
5727 Inst->setFastMathFlags(FMF);
5731 case lltok::kw_sdiv:
5732 case lltok::kw_udiv:
5733 case lltok::kw_lshr:
5734 case lltok::kw_ashr: {
5735 bool Exact = EatIfPresent(lltok::kw_exact);
5737 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5738 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5742 case lltok::kw_urem:
5743 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal,
5747 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5748 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5749 case lltok::kw_fcmp: {
5750 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5751 int Res = ParseCompare(Inst, PFS, KeywordVal);
5755 Inst->setFastMathFlags(FMF);
5760 case lltok::kw_trunc:
5761 case lltok::kw_zext:
5762 case lltok::kw_sext:
5763 case lltok::kw_fptrunc:
5764 case lltok::kw_fpext:
5765 case lltok::kw_bitcast:
5766 case lltok::kw_addrspacecast:
5767 case lltok::kw_uitofp:
5768 case lltok::kw_sitofp:
5769 case lltok::kw_fptoui:
5770 case lltok::kw_fptosi:
5771 case lltok::kw_inttoptr:
5772 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5774 case lltok::kw_select: {
5775 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5776 int Res = ParseSelect(Inst, PFS);
5780 if (!Inst->getType()->isFPOrFPVectorTy())
5781 return Error(Loc, "fast-math-flags specified for select without "
5782 "floating-point scalar or vector return type");
5783 Inst->setFastMathFlags(FMF);
5787 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5788 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5789 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5790 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5791 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5792 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5794 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5795 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5796 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5797 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5799 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5800 case lltok::kw_load: return ParseLoad(Inst, PFS);
5801 case lltok::kw_store: return ParseStore(Inst, PFS);
5802 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5803 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5804 case lltok::kw_fence: return ParseFence(Inst, PFS);
5805 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5806 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5807 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5811 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5812 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5813 if (Opc == Instruction::FCmp) {
5814 switch (Lex.getKind()) {
5815 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5816 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5817 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5818 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5819 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5820 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5821 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5822 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5823 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5824 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5825 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5826 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5827 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5828 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5829 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5830 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5831 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5834 switch (Lex.getKind()) {
5835 default: return TokError("expected icmp predicate (e.g. 'eq')");
5836 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5837 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5838 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5839 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5840 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5841 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5842 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5843 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5844 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5845 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5852 //===----------------------------------------------------------------------===//
5853 // Terminator Instructions.
5854 //===----------------------------------------------------------------------===//
5856 /// ParseRet - Parse a return instruction.
5857 /// ::= 'ret' void (',' !dbg, !1)*
5858 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5859 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5860 PerFunctionState &PFS) {
5861 SMLoc TypeLoc = Lex.getLoc();
5863 if (ParseType(Ty, true /*void allowed*/)) return true;
5865 Type *ResType = PFS.getFunction().getReturnType();
5867 if (Ty->isVoidTy()) {
5868 if (!ResType->isVoidTy())
5869 return Error(TypeLoc, "value doesn't match function result type '" +
5870 getTypeString(ResType) + "'");
5872 Inst = ReturnInst::Create(Context);
5877 if (ParseValue(Ty, RV, PFS)) return true;
5879 if (ResType != RV->getType())
5880 return Error(TypeLoc, "value doesn't match function result type '" +
5881 getTypeString(ResType) + "'");
5883 Inst = ReturnInst::Create(Context, RV);
5888 /// ::= 'br' TypeAndValue
5889 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5890 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5893 BasicBlock *Op1, *Op2;
5894 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5896 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5897 Inst = BranchInst::Create(BB);
5901 if (Op0->getType() != Type::getInt1Ty(Context))
5902 return Error(Loc, "branch condition must have 'i1' type");
5904 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5905 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5906 ParseToken(lltok::comma, "expected ',' after true destination") ||
5907 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5910 Inst = BranchInst::Create(Op1, Op2, Op0);
5916 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5918 /// ::= (TypeAndValue ',' TypeAndValue)*
5919 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5920 LocTy CondLoc, BBLoc;
5922 BasicBlock *DefaultBB;
5923 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5924 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5925 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5926 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5929 if (!Cond->getType()->isIntegerTy())
5930 return Error(CondLoc, "switch condition must have integer type");
5932 // Parse the jump table pairs.
5933 SmallPtrSet<Value*, 32> SeenCases;
5934 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5935 while (Lex.getKind() != lltok::rsquare) {
5939 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5940 ParseToken(lltok::comma, "expected ',' after case value") ||
5941 ParseTypeAndBasicBlock(DestBB, PFS))
5944 if (!SeenCases.insert(Constant).second)
5945 return Error(CondLoc, "duplicate case value in switch");
5946 if (!isa<ConstantInt>(Constant))
5947 return Error(CondLoc, "case value is not a constant integer");
5949 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5952 Lex.Lex(); // Eat the ']'.
5954 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5955 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5956 SI->addCase(Table[i].first, Table[i].second);
5963 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5964 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5967 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5968 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5969 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5972 if (!Address->getType()->isPointerTy())
5973 return Error(AddrLoc, "indirectbr address must have pointer type");
5975 // Parse the destination list.
5976 SmallVector<BasicBlock*, 16> DestList;
5978 if (Lex.getKind() != lltok::rsquare) {
5980 if (ParseTypeAndBasicBlock(DestBB, PFS))
5982 DestList.push_back(DestBB);
5984 while (EatIfPresent(lltok::comma)) {
5985 if (ParseTypeAndBasicBlock(DestBB, PFS))
5987 DestList.push_back(DestBB);
5991 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5994 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5995 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5996 IBI->addDestination(DestList[i]);
6002 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6003 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6004 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6005 LocTy CallLoc = Lex.getLoc();
6006 AttrBuilder RetAttrs, FnAttrs;
6007 std::vector<unsigned> FwdRefAttrGrps;
6010 unsigned InvokeAddrSpace;
6011 Type *RetType = nullptr;
6014 SmallVector<ParamInfo, 16> ArgList;
6015 SmallVector<OperandBundleDef, 2> BundleList;
6017 BasicBlock *NormalBB, *UnwindBB;
6018 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6019 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6020 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6021 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6022 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6024 ParseOptionalOperandBundles(BundleList, PFS) ||
6025 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
6026 ParseTypeAndBasicBlock(NormalBB, PFS) ||
6027 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6028 ParseTypeAndBasicBlock(UnwindBB, PFS))
6031 // If RetType is a non-function pointer type, then this is the short syntax
6032 // for the call, which means that RetType is just the return type. Infer the
6033 // rest of the function argument types from the arguments that are present.
6034 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6036 // Pull out the types of all of the arguments...
6037 std::vector<Type*> ParamTypes;
6038 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6039 ParamTypes.push_back(ArgList[i].V->getType());
6041 if (!FunctionType::isValidReturnType(RetType))
6042 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6044 Ty = FunctionType::get(RetType, ParamTypes, false);
6049 // Look up the callee.
6051 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6052 Callee, &PFS, /*IsCall=*/true))
6055 // Set up the Attribute for the function.
6056 SmallVector<Value *, 8> Args;
6057 SmallVector<AttributeSet, 8> ArgAttrs;
6059 // Loop through FunctionType's arguments and ensure they are specified
6060 // correctly. Also, gather any parameter attributes.
6061 FunctionType::param_iterator I = Ty->param_begin();
6062 FunctionType::param_iterator E = Ty->param_end();
6063 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6064 Type *ExpectedTy = nullptr;
6067 } else if (!Ty->isVarArg()) {
6068 return Error(ArgList[i].Loc, "too many arguments specified");
6071 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6072 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6073 getTypeString(ExpectedTy) + "'");
6074 Args.push_back(ArgList[i].V);
6075 ArgAttrs.push_back(ArgList[i].Attrs);
6079 return Error(CallLoc, "not enough parameters specified for call");
6081 if (FnAttrs.hasAlignmentAttr())
6082 return Error(CallLoc, "invoke instructions may not have an alignment");
6084 // Finish off the Attribute and check them
6086 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6087 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6090 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6091 II->setCallingConv(CC);
6092 II->setAttributes(PAL);
6093 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6099 /// ::= 'resume' TypeAndValue
6100 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
6101 Value *Exn; LocTy ExnLoc;
6102 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
6105 ResumeInst *RI = ResumeInst::Create(Exn);
6110 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
6111 PerFunctionState &PFS) {
6112 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6115 while (Lex.getKind() != lltok::rsquare) {
6116 // If this isn't the first argument, we need a comma.
6117 if (!Args.empty() &&
6118 ParseToken(lltok::comma, "expected ',' in argument list"))
6121 // Parse the argument.
6123 Type *ArgTy = nullptr;
6124 if (ParseType(ArgTy, ArgLoc))
6128 if (ArgTy->isMetadataTy()) {
6129 if (ParseMetadataAsValue(V, PFS))
6132 if (ParseValue(ArgTy, V, PFS))
6138 Lex.Lex(); // Lex the ']'.
6143 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6144 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6145 Value *CleanupPad = nullptr;
6147 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6150 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6153 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6156 BasicBlock *UnwindBB = nullptr;
6157 if (Lex.getKind() == lltok::kw_to) {
6159 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6162 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6167 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6172 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6173 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6174 Value *CatchPad = nullptr;
6176 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6179 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
6183 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6184 ParseTypeAndBasicBlock(BB, PFS))
6187 Inst = CatchReturnInst::Create(CatchPad, BB);
6191 /// ParseCatchSwitch
6192 /// ::= 'catchswitch' within Parent
6193 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6196 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6199 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6200 Lex.getKind() != lltok::LocalVarID)
6201 return TokError("expected scope value for catchswitch");
6203 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6206 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6209 SmallVector<BasicBlock *, 32> Table;
6212 if (ParseTypeAndBasicBlock(DestBB, PFS))
6214 Table.push_back(DestBB);
6215 } while (EatIfPresent(lltok::comma));
6217 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6220 if (ParseToken(lltok::kw_unwind,
6221 "expected 'unwind' after catchswitch scope"))
6224 BasicBlock *UnwindBB = nullptr;
6225 if (EatIfPresent(lltok::kw_to)) {
6226 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6229 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6234 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6235 for (BasicBlock *DestBB : Table)
6236 CatchSwitch->addHandler(DestBB);
6242 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6243 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6244 Value *CatchSwitch = nullptr;
6246 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6249 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6250 return TokError("expected scope value for catchpad");
6252 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6255 SmallVector<Value *, 8> Args;
6256 if (ParseExceptionArgs(Args, PFS))
6259 Inst = CatchPadInst::Create(CatchSwitch, Args);
6264 /// ::= 'cleanuppad' within Parent ParamList
6265 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6266 Value *ParentPad = nullptr;
6268 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6271 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6272 Lex.getKind() != lltok::LocalVarID)
6273 return TokError("expected scope value for cleanuppad");
6275 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6278 SmallVector<Value *, 8> Args;
6279 if (ParseExceptionArgs(Args, PFS))
6282 Inst = CleanupPadInst::Create(ParentPad, Args);
6286 //===----------------------------------------------------------------------===//
6288 //===----------------------------------------------------------------------===//
6291 /// ::= UnaryOp TypeAndValue ',' Value
6293 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6294 /// operand is allowed.
6295 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6296 unsigned Opc, bool IsFP) {
6297 LocTy Loc; Value *LHS;
6298 if (ParseTypeAndValue(LHS, Loc, PFS))
6301 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6302 : LHS->getType()->isIntOrIntVectorTy();
6305 return Error(Loc, "invalid operand type for instruction");
6307 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6312 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6313 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6314 /// '[' LabelList ']'
6315 bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6316 LocTy CallLoc = Lex.getLoc();
6317 AttrBuilder RetAttrs, FnAttrs;
6318 std::vector<unsigned> FwdRefAttrGrps;
6321 Type *RetType = nullptr;
6324 SmallVector<ParamInfo, 16> ArgList;
6325 SmallVector<OperandBundleDef, 2> BundleList;
6327 BasicBlock *DefaultDest;
6328 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6329 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6330 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6331 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6333 ParseOptionalOperandBundles(BundleList, PFS) ||
6334 ParseToken(lltok::kw_to, "expected 'to' in callbr") ||
6335 ParseTypeAndBasicBlock(DefaultDest, PFS) ||
6336 ParseToken(lltok::lsquare, "expected '[' in callbr"))
6339 // Parse the destination list.
6340 SmallVector<BasicBlock *, 16> IndirectDests;
6342 if (Lex.getKind() != lltok::rsquare) {
6344 if (ParseTypeAndBasicBlock(DestBB, PFS))
6346 IndirectDests.push_back(DestBB);
6348 while (EatIfPresent(lltok::comma)) {
6349 if (ParseTypeAndBasicBlock(DestBB, PFS))
6351 IndirectDests.push_back(DestBB);
6355 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6358 // If RetType is a non-function pointer type, then this is the short syntax
6359 // for the call, which means that RetType is just the return type. Infer the
6360 // rest of the function argument types from the arguments that are present.
6361 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6363 // Pull out the types of all of the arguments...
6364 std::vector<Type *> ParamTypes;
6365 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6366 ParamTypes.push_back(ArgList[i].V->getType());
6368 if (!FunctionType::isValidReturnType(RetType))
6369 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6371 Ty = FunctionType::get(RetType, ParamTypes, false);
6376 // Look up the callee.
6378 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6382 if (isa<InlineAsm>(Callee) && !Ty->getReturnType()->isVoidTy())
6383 return Error(RetTypeLoc, "asm-goto outputs not supported");
6385 // Set up the Attribute for the function.
6386 SmallVector<Value *, 8> Args;
6387 SmallVector<AttributeSet, 8> ArgAttrs;
6389 // Loop through FunctionType's arguments and ensure they are specified
6390 // correctly. Also, gather any parameter attributes.
6391 FunctionType::param_iterator I = Ty->param_begin();
6392 FunctionType::param_iterator E = Ty->param_end();
6393 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6394 Type *ExpectedTy = nullptr;
6397 } else if (!Ty->isVarArg()) {
6398 return Error(ArgList[i].Loc, "too many arguments specified");
6401 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6402 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6403 getTypeString(ExpectedTy) + "'");
6404 Args.push_back(ArgList[i].V);
6405 ArgAttrs.push_back(ArgList[i].Attrs);
6409 return Error(CallLoc, "not enough parameters specified for call");
6411 if (FnAttrs.hasAlignmentAttr())
6412 return Error(CallLoc, "callbr instructions may not have an alignment");
6414 // Finish off the Attribute and check them
6416 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6417 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6420 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6422 CBI->setCallingConv(CC);
6423 CBI->setAttributes(PAL);
6424 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6429 //===----------------------------------------------------------------------===//
6430 // Binary Operators.
6431 //===----------------------------------------------------------------------===//
6434 /// ::= ArithmeticOps TypeAndValue ',' Value
6436 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6437 /// operand is allowed.
6438 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6439 unsigned Opc, bool IsFP) {
6440 LocTy Loc; Value *LHS, *RHS;
6441 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6442 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6443 ParseValue(LHS->getType(), RHS, PFS))
6446 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6447 : LHS->getType()->isIntOrIntVectorTy();
6450 return Error(Loc, "invalid operand type for instruction");
6452 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6457 /// ::= ArithmeticOps TypeAndValue ',' Value {
6458 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6460 LocTy Loc; Value *LHS, *RHS;
6461 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6462 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6463 ParseValue(LHS->getType(), RHS, PFS))
6466 if (!LHS->getType()->isIntOrIntVectorTy())
6467 return Error(Loc,"instruction requires integer or integer vector operands");
6469 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6474 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6475 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6476 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6478 // Parse the integer/fp comparison predicate.
6482 if (ParseCmpPredicate(Pred, Opc) ||
6483 ParseTypeAndValue(LHS, Loc, PFS) ||
6484 ParseToken(lltok::comma, "expected ',' after compare value") ||
6485 ParseValue(LHS->getType(), RHS, PFS))
6488 if (Opc == Instruction::FCmp) {
6489 if (!LHS->getType()->isFPOrFPVectorTy())
6490 return Error(Loc, "fcmp requires floating point operands");
6491 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6493 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6494 if (!LHS->getType()->isIntOrIntVectorTy() &&
6495 !LHS->getType()->isPtrOrPtrVectorTy())
6496 return Error(Loc, "icmp requires integer operands");
6497 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6502 //===----------------------------------------------------------------------===//
6503 // Other Instructions.
6504 //===----------------------------------------------------------------------===//
6508 /// ::= CastOpc TypeAndValue 'to' Type
6509 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6513 Type *DestTy = nullptr;
6514 if (ParseTypeAndValue(Op, Loc, PFS) ||
6515 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6519 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6520 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6521 return Error(Loc, "invalid cast opcode for cast from '" +
6522 getTypeString(Op->getType()) + "' to '" +
6523 getTypeString(DestTy) + "'");
6525 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6530 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6531 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6533 Value *Op0, *Op1, *Op2;
6534 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6535 ParseToken(lltok::comma, "expected ',' after select condition") ||
6536 ParseTypeAndValue(Op1, PFS) ||
6537 ParseToken(lltok::comma, "expected ',' after select value") ||
6538 ParseTypeAndValue(Op2, PFS))
6541 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6542 return Error(Loc, Reason);
6544 Inst = SelectInst::Create(Op0, Op1, Op2);
6549 /// ::= 'va_arg' TypeAndValue ',' Type
6550 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
6552 Type *EltTy = nullptr;
6554 if (ParseTypeAndValue(Op, PFS) ||
6555 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
6556 ParseType(EltTy, TypeLoc))
6559 if (!EltTy->isFirstClassType())
6560 return Error(TypeLoc, "va_arg requires operand with first class type");
6562 Inst = new VAArgInst(Op, EltTy);
6566 /// ParseExtractElement
6567 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6568 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6571 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6572 ParseToken(lltok::comma, "expected ',' after extract value") ||
6573 ParseTypeAndValue(Op1, PFS))
6576 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6577 return Error(Loc, "invalid extractelement operands");
6579 Inst = ExtractElementInst::Create(Op0, Op1);
6583 /// ParseInsertElement
6584 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6585 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6587 Value *Op0, *Op1, *Op2;
6588 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6589 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6590 ParseTypeAndValue(Op1, PFS) ||
6591 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6592 ParseTypeAndValue(Op2, PFS))
6595 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6596 return Error(Loc, "invalid insertelement operands");
6598 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6602 /// ParseShuffleVector
6603 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6604 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6606 Value *Op0, *Op1, *Op2;
6607 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6608 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6609 ParseTypeAndValue(Op1, PFS) ||
6610 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6611 ParseTypeAndValue(Op2, PFS))
6614 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6615 return Error(Loc, "invalid shufflevector operands");
6617 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6622 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6623 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6624 Type *Ty = nullptr; LocTy TypeLoc;
6627 if (ParseType(Ty, TypeLoc) ||
6628 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6629 ParseValue(Ty, Op0, PFS) ||
6630 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6631 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6632 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6635 bool AteExtraComma = false;
6636 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6639 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6641 if (!EatIfPresent(lltok::comma))
6644 if (Lex.getKind() == lltok::MetadataVar) {
6645 AteExtraComma = true;
6649 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6650 ParseValue(Ty, Op0, PFS) ||
6651 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6652 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6653 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6657 if (!Ty->isFirstClassType())
6658 return Error(TypeLoc, "phi node must have first class type");
6660 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6661 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6662 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6664 return AteExtraComma ? InstExtraComma : InstNormal;
6668 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6670 /// ::= 'catch' TypeAndValue
6672 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6673 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6674 Type *Ty = nullptr; LocTy TyLoc;
6676 if (ParseType(Ty, TyLoc))
6679 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6680 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6682 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6683 LandingPadInst::ClauseType CT;
6684 if (EatIfPresent(lltok::kw_catch))
6685 CT = LandingPadInst::Catch;
6686 else if (EatIfPresent(lltok::kw_filter))
6687 CT = LandingPadInst::Filter;
6689 return TokError("expected 'catch' or 'filter' clause type");
6693 if (ParseTypeAndValue(V, VLoc, PFS))
6696 // A 'catch' type expects a non-array constant. A filter clause expects an
6698 if (CT == LandingPadInst::Catch) {
6699 if (isa<ArrayType>(V->getType()))
6700 Error(VLoc, "'catch' clause has an invalid type");
6702 if (!isa<ArrayType>(V->getType()))
6703 Error(VLoc, "'filter' clause has an invalid type");
6706 Constant *CV = dyn_cast<Constant>(V);
6708 return Error(VLoc, "clause argument must be a constant");
6712 Inst = LP.release();
6717 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6718 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6719 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6720 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6721 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6722 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6723 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6724 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6725 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6726 CallInst::TailCallKind TCK) {
6727 AttrBuilder RetAttrs, FnAttrs;
6728 std::vector<unsigned> FwdRefAttrGrps;
6730 unsigned CallAddrSpace;
6732 Type *RetType = nullptr;
6735 SmallVector<ParamInfo, 16> ArgList;
6736 SmallVector<OperandBundleDef, 2> BundleList;
6737 LocTy CallLoc = Lex.getLoc();
6739 if (TCK != CallInst::TCK_None &&
6740 ParseToken(lltok::kw_call,
6741 "expected 'tail call', 'musttail call', or 'notail call'"))
6744 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6746 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6747 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
6748 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6749 ParseValID(CalleeID) ||
6750 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6751 PFS.getFunction().isVarArg()) ||
6752 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6753 ParseOptionalOperandBundles(BundleList, PFS))
6756 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6757 return Error(CallLoc, "fast-math-flags specified for call without "
6758 "floating-point scalar or vector return type");
6760 // If RetType is a non-function pointer type, then this is the short syntax
6761 // for the call, which means that RetType is just the return type. Infer the
6762 // rest of the function argument types from the arguments that are present.
6763 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6765 // Pull out the types of all of the arguments...
6766 std::vector<Type*> ParamTypes;
6767 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6768 ParamTypes.push_back(ArgList[i].V->getType());
6770 if (!FunctionType::isValidReturnType(RetType))
6771 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6773 Ty = FunctionType::get(RetType, ParamTypes, false);
6778 // Look up the callee.
6780 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6781 &PFS, /*IsCall=*/true))
6784 // Set up the Attribute for the function.
6785 SmallVector<AttributeSet, 8> Attrs;
6787 SmallVector<Value*, 8> Args;
6789 // Loop through FunctionType's arguments and ensure they are specified
6790 // correctly. Also, gather any parameter attributes.
6791 FunctionType::param_iterator I = Ty->param_begin();
6792 FunctionType::param_iterator E = Ty->param_end();
6793 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6794 Type *ExpectedTy = nullptr;
6797 } else if (!Ty->isVarArg()) {
6798 return Error(ArgList[i].Loc, "too many arguments specified");
6801 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6802 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6803 getTypeString(ExpectedTy) + "'");
6804 Args.push_back(ArgList[i].V);
6805 Attrs.push_back(ArgList[i].Attrs);
6809 return Error(CallLoc, "not enough parameters specified for call");
6811 if (FnAttrs.hasAlignmentAttr())
6812 return Error(CallLoc, "call instructions may not have an alignment");
6814 // Finish off the Attribute and check them
6816 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6817 AttributeSet::get(Context, RetAttrs), Attrs);
6819 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6820 CI->setTailCallKind(TCK);
6821 CI->setCallingConv(CC);
6823 CI->setFastMathFlags(FMF);
6824 CI->setAttributes(PAL);
6825 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6830 //===----------------------------------------------------------------------===//
6831 // Memory Instructions.
6832 //===----------------------------------------------------------------------===//
6835 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6836 /// (',' 'align' i32)? (',', 'addrspace(n))?
6837 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6838 Value *Size = nullptr;
6839 LocTy SizeLoc, TyLoc, ASLoc;
6840 unsigned Alignment = 0;
6841 unsigned AddrSpace = 0;
6844 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6845 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6847 if (ParseType(Ty, TyLoc)) return true;
6849 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6850 return Error(TyLoc, "invalid type for alloca");
6852 bool AteExtraComma = false;
6853 if (EatIfPresent(lltok::comma)) {
6854 if (Lex.getKind() == lltok::kw_align) {
6855 if (ParseOptionalAlignment(Alignment))
6857 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6859 } else if (Lex.getKind() == lltok::kw_addrspace) {
6860 ASLoc = Lex.getLoc();
6861 if (ParseOptionalAddrSpace(AddrSpace))
6863 } else if (Lex.getKind() == lltok::MetadataVar) {
6864 AteExtraComma = true;
6866 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6868 if (EatIfPresent(lltok::comma)) {
6869 if (Lex.getKind() == lltok::kw_align) {
6870 if (ParseOptionalAlignment(Alignment))
6872 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6874 } else if (Lex.getKind() == lltok::kw_addrspace) {
6875 ASLoc = Lex.getLoc();
6876 if (ParseOptionalAddrSpace(AddrSpace))
6878 } else if (Lex.getKind() == lltok::MetadataVar) {
6879 AteExtraComma = true;
6885 if (Size && !Size->getType()->isIntegerTy())
6886 return Error(SizeLoc, "element count must have integer type");
6888 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
6889 AI->setUsedWithInAlloca(IsInAlloca);
6890 AI->setSwiftError(IsSwiftError);
6892 return AteExtraComma ? InstExtraComma : InstNormal;
6896 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6897 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6898 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6899 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6900 Value *Val; LocTy Loc;
6901 unsigned Alignment = 0;
6902 bool AteExtraComma = false;
6903 bool isAtomic = false;
6904 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6905 SyncScope::ID SSID = SyncScope::System;
6907 if (Lex.getKind() == lltok::kw_atomic) {
6912 bool isVolatile = false;
6913 if (Lex.getKind() == lltok::kw_volatile) {
6919 LocTy ExplicitTypeLoc = Lex.getLoc();
6920 if (ParseType(Ty) ||
6921 ParseToken(lltok::comma, "expected comma after load's type") ||
6922 ParseTypeAndValue(Val, Loc, PFS) ||
6923 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6924 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6927 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6928 return Error(Loc, "load operand must be a pointer to a first class type");
6929 if (isAtomic && !Alignment)
6930 return Error(Loc, "atomic load must have explicit non-zero alignment");
6931 if (Ordering == AtomicOrdering::Release ||
6932 Ordering == AtomicOrdering::AcquireRelease)
6933 return Error(Loc, "atomic load cannot use Release ordering");
6935 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6936 return Error(ExplicitTypeLoc,
6937 "explicit pointee type doesn't match operand's pointee type");
6939 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6940 return AteExtraComma ? InstExtraComma : InstNormal;
6945 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6946 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6947 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6948 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6949 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6950 unsigned Alignment = 0;
6951 bool AteExtraComma = false;
6952 bool isAtomic = false;
6953 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6954 SyncScope::ID SSID = SyncScope::System;
6956 if (Lex.getKind() == lltok::kw_atomic) {
6961 bool isVolatile = false;
6962 if (Lex.getKind() == lltok::kw_volatile) {
6967 if (ParseTypeAndValue(Val, Loc, PFS) ||
6968 ParseToken(lltok::comma, "expected ',' after store operand") ||
6969 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6970 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6971 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6974 if (!Ptr->getType()->isPointerTy())
6975 return Error(PtrLoc, "store operand must be a pointer");
6976 if (!Val->getType()->isFirstClassType())
6977 return Error(Loc, "store operand must be a first class value");
6978 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6979 return Error(Loc, "stored value and pointer type do not match");
6980 if (isAtomic && !Alignment)
6981 return Error(Loc, "atomic store must have explicit non-zero alignment");
6982 if (Ordering == AtomicOrdering::Acquire ||
6983 Ordering == AtomicOrdering::AcquireRelease)
6984 return Error(Loc, "atomic store cannot use Acquire ordering");
6986 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6987 return AteExtraComma ? InstExtraComma : InstNormal;
6991 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6992 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6993 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6994 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6995 bool AteExtraComma = false;
6996 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6997 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6998 SyncScope::ID SSID = SyncScope::System;
6999 bool isVolatile = false;
7000 bool isWeak = false;
7002 if (EatIfPresent(lltok::kw_weak))
7005 if (EatIfPresent(lltok::kw_volatile))
7008 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7009 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7010 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
7011 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7012 ParseTypeAndValue(New, NewLoc, PFS) ||
7013 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7014 ParseOrdering(FailureOrdering))
7017 if (SuccessOrdering == AtomicOrdering::Unordered ||
7018 FailureOrdering == AtomicOrdering::Unordered)
7019 return TokError("cmpxchg cannot be unordered");
7020 if (isStrongerThan(FailureOrdering, SuccessOrdering))
7021 return TokError("cmpxchg failure argument shall be no stronger than the "
7022 "success argument");
7023 if (FailureOrdering == AtomicOrdering::Release ||
7024 FailureOrdering == AtomicOrdering::AcquireRelease)
7026 "cmpxchg failure ordering cannot include release semantics");
7027 if (!Ptr->getType()->isPointerTy())
7028 return Error(PtrLoc, "cmpxchg operand must be a pointer");
7029 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
7030 return Error(CmpLoc, "compare value and pointer type do not match");
7031 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
7032 return Error(NewLoc, "new value and pointer type do not match");
7033 if (!New->getType()->isFirstClassType())
7034 return Error(NewLoc, "cmpxchg operand must be a first class value");
7035 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7036 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
7037 CXI->setVolatile(isVolatile);
7038 CXI->setWeak(isWeak);
7040 return AteExtraComma ? InstExtraComma : InstNormal;
7044 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7045 /// 'singlethread'? AtomicOrdering
7046 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7047 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7048 bool AteExtraComma = false;
7049 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7050 SyncScope::ID SSID = SyncScope::System;
7051 bool isVolatile = false;
7053 AtomicRMWInst::BinOp Operation;
7055 if (EatIfPresent(lltok::kw_volatile))
7058 switch (Lex.getKind()) {
7059 default: return TokError("expected binary operation in atomicrmw");
7060 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7061 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7062 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7063 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7064 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7065 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7066 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7067 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7068 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7069 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7070 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7071 case lltok::kw_fadd:
7072 Operation = AtomicRMWInst::FAdd;
7075 case lltok::kw_fsub:
7076 Operation = AtomicRMWInst::FSub;
7080 Lex.Lex(); // Eat the operation.
7082 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7083 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7084 ParseTypeAndValue(Val, ValLoc, PFS) ||
7085 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7088 if (Ordering == AtomicOrdering::Unordered)
7089 return TokError("atomicrmw cannot be unordered");
7090 if (!Ptr->getType()->isPointerTy())
7091 return Error(PtrLoc, "atomicrmw operand must be a pointer");
7092 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7093 return Error(ValLoc, "atomicrmw value and pointer type do not match");
7095 if (Operation == AtomicRMWInst::Xchg) {
7096 if (!Val->getType()->isIntegerTy() &&
7097 !Val->getType()->isFloatingPointTy()) {
7098 return Error(ValLoc, "atomicrmw " +
7099 AtomicRMWInst::getOperationName(Operation) +
7100 " operand must be an integer or floating point type");
7103 if (!Val->getType()->isFloatingPointTy()) {
7104 return Error(ValLoc, "atomicrmw " +
7105 AtomicRMWInst::getOperationName(Operation) +
7106 " operand must be a floating point type");
7109 if (!Val->getType()->isIntegerTy()) {
7110 return Error(ValLoc, "atomicrmw " +
7111 AtomicRMWInst::getOperationName(Operation) +
7112 " operand must be an integer");
7116 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7117 if (Size < 8 || (Size & (Size - 1)))
7118 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7121 AtomicRMWInst *RMWI =
7122 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
7123 RMWI->setVolatile(isVolatile);
7125 return AteExtraComma ? InstExtraComma : InstNormal;
7129 /// ::= 'fence' 'singlethread'? AtomicOrdering
7130 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
7131 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7132 SyncScope::ID SSID = SyncScope::System;
7133 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7136 if (Ordering == AtomicOrdering::Unordered)
7137 return TokError("fence cannot be unordered");
7138 if (Ordering == AtomicOrdering::Monotonic)
7139 return TokError("fence cannot be monotonic");
7141 Inst = new FenceInst(Context, Ordering, SSID);
7145 /// ParseGetElementPtr
7146 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7147 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7148 Value *Ptr = nullptr;
7149 Value *Val = nullptr;
7152 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7155 LocTy ExplicitTypeLoc = Lex.getLoc();
7156 if (ParseType(Ty) ||
7157 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
7158 ParseTypeAndValue(Ptr, Loc, PFS))
7161 Type *BaseType = Ptr->getType();
7162 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7163 if (!BasePointerType)
7164 return Error(Loc, "base of getelementptr must be a pointer");
7166 if (Ty != BasePointerType->getElementType())
7167 return Error(ExplicitTypeLoc,
7168 "explicit pointee type doesn't match operand's pointee type");
7170 SmallVector<Value*, 16> Indices;
7171 bool AteExtraComma = false;
7172 // GEP returns a vector of pointers if at least one of parameters is a vector.
7173 // All vector parameters should have the same vector width.
7174 unsigned GEPWidth = BaseType->isVectorTy() ?
7175 BaseType->getVectorNumElements() : 0;
7177 while (EatIfPresent(lltok::comma)) {
7178 if (Lex.getKind() == lltok::MetadataVar) {
7179 AteExtraComma = true;
7182 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
7183 if (!Val->getType()->isIntOrIntVectorTy())
7184 return Error(EltLoc, "getelementptr index must be an integer");
7186 if (Val->getType()->isVectorTy()) {
7187 unsigned ValNumEl = Val->getType()->getVectorNumElements();
7188 if (GEPWidth && GEPWidth != ValNumEl)
7189 return Error(EltLoc,
7190 "getelementptr vector index has a wrong number of elements");
7191 GEPWidth = ValNumEl;
7193 Indices.push_back(Val);
7196 SmallPtrSet<Type*, 4> Visited;
7197 if (!Indices.empty() && !Ty->isSized(&Visited))
7198 return Error(Loc, "base element of getelementptr must be sized");
7200 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7201 return Error(Loc, "invalid getelementptr indices");
7202 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7204 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7205 return AteExtraComma ? InstExtraComma : InstNormal;
7208 /// ParseExtractValue
7209 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7210 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7211 Value *Val; LocTy Loc;
7212 SmallVector<unsigned, 4> Indices;
7214 if (ParseTypeAndValue(Val, Loc, PFS) ||
7215 ParseIndexList(Indices, AteExtraComma))
7218 if (!Val->getType()->isAggregateType())
7219 return Error(Loc, "extractvalue operand must be aggregate type");
7221 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7222 return Error(Loc, "invalid indices for extractvalue");
7223 Inst = ExtractValueInst::Create(Val, Indices);
7224 return AteExtraComma ? InstExtraComma : InstNormal;
7227 /// ParseInsertValue
7228 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7229 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7230 Value *Val0, *Val1; LocTy Loc0, Loc1;
7231 SmallVector<unsigned, 4> Indices;
7233 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
7234 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
7235 ParseTypeAndValue(Val1, Loc1, PFS) ||
7236 ParseIndexList(Indices, AteExtraComma))
7239 if (!Val0->getType()->isAggregateType())
7240 return Error(Loc0, "insertvalue operand must be aggregate type");
7242 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7244 return Error(Loc0, "invalid indices for insertvalue");
7245 if (IndexedType != Val1->getType())
7246 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
7247 getTypeString(Val1->getType()) + "' instead of '" +
7248 getTypeString(IndexedType) + "'");
7249 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7250 return AteExtraComma ? InstExtraComma : InstNormal;
7253 //===----------------------------------------------------------------------===//
7254 // Embedded metadata.
7255 //===----------------------------------------------------------------------===//
7257 /// ParseMDNodeVector
7258 /// ::= { Element (',' Element)* }
7260 /// ::= 'null' | TypeAndValue
7261 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7262 if (ParseToken(lltok::lbrace, "expected '{' here"))
7265 // Check for an empty list.
7266 if (EatIfPresent(lltok::rbrace))
7270 // Null is a special case since it is typeless.
7271 if (EatIfPresent(lltok::kw_null)) {
7272 Elts.push_back(nullptr);
7277 if (ParseMetadata(MD, nullptr))
7280 } while (EatIfPresent(lltok::comma));
7282 return ParseToken(lltok::rbrace, "expected end of metadata node");
7285 //===----------------------------------------------------------------------===//
7286 // Use-list order directives.
7287 //===----------------------------------------------------------------------===//
7288 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7291 return Error(Loc, "value has no uses");
7293 unsigned NumUses = 0;
7294 SmallDenseMap<const Use *, unsigned, 16> Order;
7295 for (const Use &U : V->uses()) {
7296 if (++NumUses > Indexes.size())
7298 Order[&U] = Indexes[NumUses - 1];
7301 return Error(Loc, "value only has one use");
7302 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7304 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7306 V->sortUseList([&](const Use &L, const Use &R) {
7307 return Order.lookup(&L) < Order.lookup(&R);
7312 /// ParseUseListOrderIndexes
7313 /// ::= '{' uint32 (',' uint32)+ '}'
7314 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7315 SMLoc Loc = Lex.getLoc();
7316 if (ParseToken(lltok::lbrace, "expected '{' here"))
7318 if (Lex.getKind() == lltok::rbrace)
7319 return Lex.Error("expected non-empty list of uselistorder indexes");
7321 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7322 // indexes should be distinct numbers in the range [0, size-1], and should
7324 unsigned Offset = 0;
7326 bool IsOrdered = true;
7327 assert(Indexes.empty() && "Expected empty order vector");
7330 if (ParseUInt32(Index))
7333 // Update consistency checks.
7334 Offset += Index - Indexes.size();
7335 Max = std::max(Max, Index);
7336 IsOrdered &= Index == Indexes.size();
7338 Indexes.push_back(Index);
7339 } while (EatIfPresent(lltok::comma));
7341 if (ParseToken(lltok::rbrace, "expected '}' here"))
7344 if (Indexes.size() < 2)
7345 return Error(Loc, "expected >= 2 uselistorder indexes");
7346 if (Offset != 0 || Max >= Indexes.size())
7347 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7349 return Error(Loc, "expected uselistorder indexes to change the order");
7354 /// ParseUseListOrder
7355 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7356 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7357 SMLoc Loc = Lex.getLoc();
7358 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7362 SmallVector<unsigned, 16> Indexes;
7363 if (ParseTypeAndValue(V, PFS) ||
7364 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7365 ParseUseListOrderIndexes(Indexes))
7368 return sortUseListOrder(V, Indexes, Loc);
7371 /// ParseUseListOrderBB
7372 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7373 bool LLParser::ParseUseListOrderBB() {
7374 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7375 SMLoc Loc = Lex.getLoc();
7379 SmallVector<unsigned, 16> Indexes;
7380 if (ParseValID(Fn) ||
7381 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7382 ParseValID(Label) ||
7383 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7384 ParseUseListOrderIndexes(Indexes))
7387 // Check the function.
7389 if (Fn.Kind == ValID::t_GlobalName)
7390 GV = M->getNamedValue(Fn.StrVal);
7391 else if (Fn.Kind == ValID::t_GlobalID)
7392 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7394 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7396 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7397 auto *F = dyn_cast<Function>(GV);
7399 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7400 if (F->isDeclaration())
7401 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7403 // Check the basic block.
7404 if (Label.Kind == ValID::t_LocalID)
7405 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7406 if (Label.Kind != ValID::t_LocalName)
7407 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
7408 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7410 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7411 if (!isa<BasicBlock>(V))
7412 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7414 return sortUseListOrder(V, Indexes, Loc);
7418 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7419 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7420 bool LLParser::ParseModuleEntry(unsigned ID) {
7421 assert(Lex.getKind() == lltok::kw_module);
7425 if (ParseToken(lltok::colon, "expected ':' here") ||
7426 ParseToken(lltok::lparen, "expected '(' here") ||
7427 ParseToken(lltok::kw_path, "expected 'path' here") ||
7428 ParseToken(lltok::colon, "expected ':' here") ||
7429 ParseStringConstant(Path) ||
7430 ParseToken(lltok::comma, "expected ',' here") ||
7431 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7432 ParseToken(lltok::colon, "expected ':' here") ||
7433 ParseToken(lltok::lparen, "expected '(' here"))
7437 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7438 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7439 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7440 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7441 ParseUInt32(Hash[4]))
7444 if (ParseToken(lltok::rparen, "expected ')' here") ||
7445 ParseToken(lltok::rparen, "expected ')' here"))
7448 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7449 ModuleIdMap[ID] = ModuleEntry->first();
7455 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7456 bool LLParser::ParseTypeIdEntry(unsigned ID) {
7457 assert(Lex.getKind() == lltok::kw_typeid);
7461 if (ParseToken(lltok::colon, "expected ':' here") ||
7462 ParseToken(lltok::lparen, "expected '(' here") ||
7463 ParseToken(lltok::kw_name, "expected 'name' here") ||
7464 ParseToken(lltok::colon, "expected ':' here") ||
7465 ParseStringConstant(Name))
7468 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7469 if (ParseToken(lltok::comma, "expected ',' here") ||
7470 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7473 // Check if this ID was forward referenced, and if so, update the
7474 // corresponding GUIDs.
7475 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7476 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7477 for (auto TIDRef : FwdRefTIDs->second) {
7478 assert(!*TIDRef.first &&
7479 "Forward referenced type id GUID expected to be 0");
7480 *TIDRef.first = GlobalValue::getGUID(Name);
7482 ForwardRefTypeIds.erase(FwdRefTIDs);
7489 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7490 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7491 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7492 ParseToken(lltok::colon, "expected ':' here") ||
7493 ParseToken(lltok::lparen, "expected '(' here") ||
7494 ParseTypeTestResolution(TIS.TTRes))
7497 if (EatIfPresent(lltok::comma)) {
7498 // Expect optional wpdResolutions field
7499 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7503 if (ParseToken(lltok::rparen, "expected ')' here"))
7509 static ValueInfo EmptyVI =
7510 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7512 /// TypeIdCompatibleVtableEntry
7513 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7514 /// TypeIdCompatibleVtableInfo
7516 bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID) {
7517 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7521 if (ParseToken(lltok::colon, "expected ':' here") ||
7522 ParseToken(lltok::lparen, "expected '(' here") ||
7523 ParseToken(lltok::kw_name, "expected 'name' here") ||
7524 ParseToken(lltok::colon, "expected ':' here") ||
7525 ParseStringConstant(Name))
7528 TypeIdCompatibleVtableInfo &TI =
7529 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7530 if (ParseToken(lltok::comma, "expected ',' here") ||
7531 ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7532 ParseToken(lltok::colon, "expected ':' here") ||
7533 ParseToken(lltok::lparen, "expected '(' here"))
7536 IdToIndexMapType IdToIndexMap;
7537 // Parse each call edge
7540 if (ParseToken(lltok::lparen, "expected '(' here") ||
7541 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7542 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7543 ParseToken(lltok::comma, "expected ',' here"))
7546 LocTy Loc = Lex.getLoc();
7549 if (ParseGVReference(VI, GVId))
7552 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7553 // forward reference. We will save the location of the ValueInfo needing an
7554 // update, but can only do so once the std::vector is finalized.
7556 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7557 TI.push_back({Offset, VI});
7559 if (ParseToken(lltok::rparen, "expected ')' in call"))
7561 } while (EatIfPresent(lltok::comma));
7563 // Now that the TI vector is finalized, it is safe to save the locations
7564 // of any forward GV references that need updating later.
7565 for (auto I : IdToIndexMap) {
7566 for (auto P : I.second) {
7567 assert(TI[P.first].VTableVI == EmptyVI &&
7568 "Forward referenced ValueInfo expected to be empty");
7569 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7570 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7571 FwdRef.first->second.push_back(
7572 std::make_pair(&TI[P.first].VTableVI, P.second));
7576 if (ParseToken(lltok::rparen, "expected ')' here") ||
7577 ParseToken(lltok::rparen, "expected ')' here"))
7580 // Check if this ID was forward referenced, and if so, update the
7581 // corresponding GUIDs.
7582 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7583 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7584 for (auto TIDRef : FwdRefTIDs->second) {
7585 assert(!*TIDRef.first &&
7586 "Forward referenced type id GUID expected to be 0");
7587 *TIDRef.first = GlobalValue::getGUID(Name);
7589 ForwardRefTypeIds.erase(FwdRefTIDs);
7595 /// TypeTestResolution
7596 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7597 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7598 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7599 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7600 /// [',' 'inlinesBits' ':' UInt64]? ')'
7601 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7602 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7603 ParseToken(lltok::colon, "expected ':' here") ||
7604 ParseToken(lltok::lparen, "expected '(' here") ||
7605 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7606 ParseToken(lltok::colon, "expected ':' here"))
7609 switch (Lex.getKind()) {
7610 case lltok::kw_unsat:
7611 TTRes.TheKind = TypeTestResolution::Unsat;
7613 case lltok::kw_byteArray:
7614 TTRes.TheKind = TypeTestResolution::ByteArray;
7616 case lltok::kw_inline:
7617 TTRes.TheKind = TypeTestResolution::Inline;
7619 case lltok::kw_single:
7620 TTRes.TheKind = TypeTestResolution::Single;
7622 case lltok::kw_allOnes:
7623 TTRes.TheKind = TypeTestResolution::AllOnes;
7626 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7630 if (ParseToken(lltok::comma, "expected ',' here") ||
7631 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7632 ParseToken(lltok::colon, "expected ':' here") ||
7633 ParseUInt32(TTRes.SizeM1BitWidth))
7636 // Parse optional fields
7637 while (EatIfPresent(lltok::comma)) {
7638 switch (Lex.getKind()) {
7639 case lltok::kw_alignLog2:
7641 if (ParseToken(lltok::colon, "expected ':'") ||
7642 ParseUInt64(TTRes.AlignLog2))
7645 case lltok::kw_sizeM1:
7647 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7650 case lltok::kw_bitMask: {
7653 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7655 assert(Val <= 0xff);
7656 TTRes.BitMask = (uint8_t)Val;
7659 case lltok::kw_inlineBits:
7661 if (ParseToken(lltok::colon, "expected ':'") ||
7662 ParseUInt64(TTRes.InlineBits))
7666 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7670 if (ParseToken(lltok::rparen, "expected ')' here"))
7676 /// OptionalWpdResolutions
7677 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7678 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7679 bool LLParser::ParseOptionalWpdResolutions(
7680 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7681 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7682 ParseToken(lltok::colon, "expected ':' here") ||
7683 ParseToken(lltok::lparen, "expected '(' here"))
7688 WholeProgramDevirtResolution WPDRes;
7689 if (ParseToken(lltok::lparen, "expected '(' here") ||
7690 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7691 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7692 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7693 ParseToken(lltok::rparen, "expected ')' here"))
7695 WPDResMap[Offset] = WPDRes;
7696 } while (EatIfPresent(lltok::comma));
7698 if (ParseToken(lltok::rparen, "expected ')' here"))
7705 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7706 /// [',' OptionalResByArg]? ')'
7707 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7708 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7709 /// [',' OptionalResByArg]? ')'
7710 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7711 /// [',' OptionalResByArg]? ')'
7712 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7713 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7714 ParseToken(lltok::colon, "expected ':' here") ||
7715 ParseToken(lltok::lparen, "expected '(' here") ||
7716 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7717 ParseToken(lltok::colon, "expected ':' here"))
7720 switch (Lex.getKind()) {
7721 case lltok::kw_indir:
7722 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7724 case lltok::kw_singleImpl:
7725 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7727 case lltok::kw_branchFunnel:
7728 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7731 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7735 // Parse optional fields
7736 while (EatIfPresent(lltok::comma)) {
7737 switch (Lex.getKind()) {
7738 case lltok::kw_singleImplName:
7740 if (ParseToken(lltok::colon, "expected ':' here") ||
7741 ParseStringConstant(WPDRes.SingleImplName))
7744 case lltok::kw_resByArg:
7745 if (ParseOptionalResByArg(WPDRes.ResByArg))
7749 return Error(Lex.getLoc(),
7750 "expected optional WholeProgramDevirtResolution field");
7754 if (ParseToken(lltok::rparen, "expected ')' here"))
7760 /// OptionalResByArg
7761 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7762 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7763 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7764 /// 'virtualConstProp' )
7765 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7766 /// [',' 'bit' ':' UInt32]? ')'
7767 bool LLParser::ParseOptionalResByArg(
7768 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7770 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7771 ParseToken(lltok::colon, "expected ':' here") ||
7772 ParseToken(lltok::lparen, "expected '(' here"))
7776 std::vector<uint64_t> Args;
7777 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7778 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7779 ParseToken(lltok::colon, "expected ':' here") ||
7780 ParseToken(lltok::lparen, "expected '(' here") ||
7781 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7782 ParseToken(lltok::colon, "expected ':' here"))
7785 WholeProgramDevirtResolution::ByArg ByArg;
7786 switch (Lex.getKind()) {
7787 case lltok::kw_indir:
7788 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7790 case lltok::kw_uniformRetVal:
7791 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7793 case lltok::kw_uniqueRetVal:
7794 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7796 case lltok::kw_virtualConstProp:
7797 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7800 return Error(Lex.getLoc(),
7801 "unexpected WholeProgramDevirtResolution::ByArg kind");
7805 // Parse optional fields
7806 while (EatIfPresent(lltok::comma)) {
7807 switch (Lex.getKind()) {
7808 case lltok::kw_info:
7810 if (ParseToken(lltok::colon, "expected ':' here") ||
7811 ParseUInt64(ByArg.Info))
7814 case lltok::kw_byte:
7816 if (ParseToken(lltok::colon, "expected ':' here") ||
7817 ParseUInt32(ByArg.Byte))
7822 if (ParseToken(lltok::colon, "expected ':' here") ||
7823 ParseUInt32(ByArg.Bit))
7827 return Error(Lex.getLoc(),
7828 "expected optional whole program devirt field");
7832 if (ParseToken(lltok::rparen, "expected ')' here"))
7835 ResByArg[Args] = ByArg;
7836 } while (EatIfPresent(lltok::comma));
7838 if (ParseToken(lltok::rparen, "expected ')' here"))
7844 /// OptionalResByArg
7845 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7846 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7847 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7848 ParseToken(lltok::colon, "expected ':' here") ||
7849 ParseToken(lltok::lparen, "expected '(' here"))
7854 if (ParseUInt64(Val))
7856 Args.push_back(Val);
7857 } while (EatIfPresent(lltok::comma));
7859 if (ParseToken(lltok::rparen, "expected ')' here"))
7865 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
7867 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7868 bool ReadOnly = Fwd->isReadOnly();
7869 bool WriteOnly = Fwd->isWriteOnly();
7870 assert(!(ReadOnly && WriteOnly));
7875 Fwd->setWriteOnly();
7878 /// Stores the given Name/GUID and associated summary into the Index.
7879 /// Also updates any forward references to the associated entry ID.
7880 void LLParser::AddGlobalValueToIndex(
7881 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7882 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7883 // First create the ValueInfo utilizing the Name or GUID.
7886 assert(Name.empty());
7887 VI = Index->getOrInsertValueInfo(GUID);
7889 assert(!Name.empty());
7891 auto *GV = M->getNamedValue(Name);
7893 VI = Index->getOrInsertValueInfo(GV);
7896 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7897 "Need a source_filename to compute GUID for local");
7898 GUID = GlobalValue::getGUID(
7899 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7900 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7904 // Resolve forward references from calls/refs
7905 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7906 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7907 for (auto VIRef : FwdRefVIs->second) {
7908 assert(VIRef.first->getRef() == FwdVIRef &&
7909 "Forward referenced ValueInfo expected to be empty");
7910 resolveFwdRef(VIRef.first, VI);
7912 ForwardRefValueInfos.erase(FwdRefVIs);
7915 // Resolve forward references from aliases
7916 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7917 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7918 for (auto AliaseeRef : FwdRefAliasees->second) {
7919 assert(!AliaseeRef.first->hasAliasee() &&
7920 "Forward referencing alias already has aliasee");
7921 assert(Summary && "Aliasee must be a definition");
7922 AliaseeRef.first->setAliasee(VI, Summary.get());
7924 ForwardRefAliasees.erase(FwdRefAliasees);
7927 // Add the summary if one was provided.
7929 Index->addGlobalValueSummary(VI, std::move(Summary));
7931 // Save the associated ValueInfo for use in later references by ID.
7932 if (ID == NumberedValueInfos.size())
7933 NumberedValueInfos.push_back(VI);
7935 // Handle non-continuous numbers (to make test simplification easier).
7936 if (ID > NumberedValueInfos.size())
7937 NumberedValueInfos.resize(ID + 1);
7938 NumberedValueInfos[ID] = VI;
7943 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7944 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7945 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7946 bool LLParser::ParseGVEntry(unsigned ID) {
7947 assert(Lex.getKind() == lltok::kw_gv);
7950 if (ParseToken(lltok::colon, "expected ':' here") ||
7951 ParseToken(lltok::lparen, "expected '(' here"))
7955 GlobalValue::GUID GUID = 0;
7956 switch (Lex.getKind()) {
7957 case lltok::kw_name:
7959 if (ParseToken(lltok::colon, "expected ':' here") ||
7960 ParseStringConstant(Name))
7962 // Can't create GUID/ValueInfo until we have the linkage.
7964 case lltok::kw_guid:
7966 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7970 return Error(Lex.getLoc(), "expected name or guid tag");
7973 if (!EatIfPresent(lltok::comma)) {
7974 // No summaries. Wrap up.
7975 if (ParseToken(lltok::rparen, "expected ')' here"))
7977 // This was created for a call to an external or indirect target.
7978 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7979 // created for indirect calls with VP. A Name with no GUID came from
7980 // an external definition. We pass ExternalLinkage since that is only
7981 // used when the GUID must be computed from Name, and in that case
7982 // the symbol must have external linkage.
7983 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7988 // Have a list of summaries
7989 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7990 ParseToken(lltok::colon, "expected ':' here"))
7994 if (ParseToken(lltok::lparen, "expected '(' here"))
7996 switch (Lex.getKind()) {
7997 case lltok::kw_function:
7998 if (ParseFunctionSummary(Name, GUID, ID))
8001 case lltok::kw_variable:
8002 if (ParseVariableSummary(Name, GUID, ID))
8005 case lltok::kw_alias:
8006 if (ParseAliasSummary(Name, GUID, ID))
8010 return Error(Lex.getLoc(), "expected summary type");
8012 if (ParseToken(lltok::rparen, "expected ')' here"))
8014 } while (EatIfPresent(lltok::comma));
8016 if (ParseToken(lltok::rparen, "expected ')' here"))
8023 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8024 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8025 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
8026 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8028 assert(Lex.getKind() == lltok::kw_function);
8031 StringRef ModulePath;
8032 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8033 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8034 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8036 std::vector<FunctionSummary::EdgeTy> Calls;
8037 FunctionSummary::TypeIdInfo TypeIdInfo;
8038 std::vector<ValueInfo> Refs;
8039 // Default is all-zeros (conservative values).
8040 FunctionSummary::FFlags FFlags = {};
8041 if (ParseToken(lltok::colon, "expected ':' here") ||
8042 ParseToken(lltok::lparen, "expected '(' here") ||
8043 ParseModuleReference(ModulePath) ||
8044 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8045 ParseToken(lltok::comma, "expected ',' here") ||
8046 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
8047 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
8050 // Parse optional fields
8051 while (EatIfPresent(lltok::comma)) {
8052 switch (Lex.getKind()) {
8053 case lltok::kw_funcFlags:
8054 if (ParseOptionalFFlags(FFlags))
8057 case lltok::kw_calls:
8058 if (ParseOptionalCalls(Calls))
8061 case lltok::kw_typeIdInfo:
8062 if (ParseOptionalTypeIdInfo(TypeIdInfo))
8065 case lltok::kw_refs:
8066 if (ParseOptionalRefs(Refs))
8070 return Error(Lex.getLoc(), "expected optional function summary field");
8074 if (ParseToken(lltok::rparen, "expected ')' here"))
8077 auto FS = llvm::make_unique<FunctionSummary>(
8078 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8079 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8080 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8081 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8082 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8083 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
8085 FS->setModulePath(ModulePath);
8087 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8094 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8095 /// [',' OptionalRefs]? ')'
8096 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8098 assert(Lex.getKind() == lltok::kw_variable);
8101 StringRef ModulePath;
8102 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8103 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8104 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8105 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8106 /* WriteOnly */ false);
8107 std::vector<ValueInfo> Refs;
8108 VTableFuncList VTableFuncs;
8109 if (ParseToken(lltok::colon, "expected ':' here") ||
8110 ParseToken(lltok::lparen, "expected '(' here") ||
8111 ParseModuleReference(ModulePath) ||
8112 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8113 ParseToken(lltok::comma, "expected ',' here") ||
8114 ParseGVarFlags(GVarFlags))
8117 // Parse optional fields
8118 while (EatIfPresent(lltok::comma)) {
8119 switch (Lex.getKind()) {
8120 case lltok::kw_vTableFuncs:
8121 if (ParseOptionalVTableFuncs(VTableFuncs))
8124 case lltok::kw_refs:
8125 if (ParseOptionalRefs(Refs))
8129 return Error(Lex.getLoc(), "expected optional variable summary field");
8133 if (ParseToken(lltok::rparen, "expected ')' here"))
8137 llvm::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8139 GS->setModulePath(ModulePath);
8140 GS->setVTableFuncs(std::move(VTableFuncs));
8142 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8149 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8150 /// 'aliasee' ':' GVReference ')'
8151 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8153 assert(Lex.getKind() == lltok::kw_alias);
8154 LocTy Loc = Lex.getLoc();
8157 StringRef ModulePath;
8158 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8159 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8160 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8161 if (ParseToken(lltok::colon, "expected ':' here") ||
8162 ParseToken(lltok::lparen, "expected '(' here") ||
8163 ParseModuleReference(ModulePath) ||
8164 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8165 ParseToken(lltok::comma, "expected ',' here") ||
8166 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8167 ParseToken(lltok::colon, "expected ':' here"))
8170 ValueInfo AliaseeVI;
8172 if (ParseGVReference(AliaseeVI, GVId))
8175 if (ParseToken(lltok::rparen, "expected ')' here"))
8178 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
8180 AS->setModulePath(ModulePath);
8182 // Record forward reference if the aliasee is not parsed yet.
8183 if (AliaseeVI.getRef() == FwdVIRef) {
8184 auto FwdRef = ForwardRefAliasees.insert(
8185 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
8186 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
8188 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8189 assert(Summary && "Aliasee must be a definition");
8190 AS->setAliasee(AliaseeVI, Summary);
8193 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8201 bool LLParser::ParseFlag(unsigned &Val) {
8202 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8203 return TokError("expected integer");
8204 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8210 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8211 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8212 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8213 /// [',' 'noInline' ':' Flag]? ')'
8214 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8215 assert(Lex.getKind() == lltok::kw_funcFlags);
8218 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
8219 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
8224 switch (Lex.getKind()) {
8225 case lltok::kw_readNone:
8227 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8229 FFlags.ReadNone = Val;
8231 case lltok::kw_readOnly:
8233 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8235 FFlags.ReadOnly = Val;
8237 case lltok::kw_noRecurse:
8239 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8241 FFlags.NoRecurse = Val;
8243 case lltok::kw_returnDoesNotAlias:
8245 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8247 FFlags.ReturnDoesNotAlias = Val;
8249 case lltok::kw_noInline:
8251 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8253 FFlags.NoInline = Val;
8256 return Error(Lex.getLoc(), "expected function flag type");
8258 } while (EatIfPresent(lltok::comma));
8260 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
8267 /// := 'calls' ':' '(' Call [',' Call]* ')'
8268 /// Call ::= '(' 'callee' ':' GVReference
8269 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8270 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8271 assert(Lex.getKind() == lltok::kw_calls);
8274 if (ParseToken(lltok::colon, "expected ':' in calls") |
8275 ParseToken(lltok::lparen, "expected '(' in calls"))
8278 IdToIndexMapType IdToIndexMap;
8279 // Parse each call edge
8282 if (ParseToken(lltok::lparen, "expected '(' in call") ||
8283 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
8284 ParseToken(lltok::colon, "expected ':'"))
8287 LocTy Loc = Lex.getLoc();
8289 if (ParseGVReference(VI, GVId))
8292 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8294 if (EatIfPresent(lltok::comma)) {
8295 // Expect either hotness or relbf
8296 if (EatIfPresent(lltok::kw_hotness)) {
8297 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
8300 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
8301 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
8305 // Keep track of the Call array index needing a forward reference.
8306 // We will save the location of the ValueInfo needing an update, but
8307 // can only do so once the std::vector is finalized.
8308 if (VI.getRef() == FwdVIRef)
8309 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8310 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8312 if (ParseToken(lltok::rparen, "expected ')' in call"))
8314 } while (EatIfPresent(lltok::comma));
8316 // Now that the Calls vector is finalized, it is safe to save the locations
8317 // of any forward GV references that need updating later.
8318 for (auto I : IdToIndexMap) {
8319 for (auto P : I.second) {
8320 assert(Calls[P.first].first.getRef() == FwdVIRef &&
8321 "Forward referenced ValueInfo expected to be empty");
8322 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8323 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8324 FwdRef.first->second.push_back(
8325 std::make_pair(&Calls[P.first].first, P.second));
8329 if (ParseToken(lltok::rparen, "expected ')' in calls"))
8336 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8337 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
8338 switch (Lex.getKind()) {
8339 case lltok::kw_unknown:
8340 Hotness = CalleeInfo::HotnessType::Unknown;
8342 case lltok::kw_cold:
8343 Hotness = CalleeInfo::HotnessType::Cold;
8345 case lltok::kw_none:
8346 Hotness = CalleeInfo::HotnessType::None;
8349 Hotness = CalleeInfo::HotnessType::Hot;
8351 case lltok::kw_critical:
8352 Hotness = CalleeInfo::HotnessType::Critical;
8355 return Error(Lex.getLoc(), "invalid call edge hotness");
8361 /// OptionalVTableFuncs
8362 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8363 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8364 bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8365 assert(Lex.getKind() == lltok::kw_vTableFuncs);
8368 if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") |
8369 ParseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8372 IdToIndexMapType IdToIndexMap;
8373 // Parse each virtual function pair
8376 if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8377 ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8378 ParseToken(lltok::colon, "expected ':'"))
8381 LocTy Loc = Lex.getLoc();
8383 if (ParseGVReference(VI, GVId))
8387 if (ParseToken(lltok::comma, "expected comma") ||
8388 ParseToken(lltok::kw_offset, "expected offset") ||
8389 ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset))
8392 // Keep track of the VTableFuncs array index needing a forward reference.
8393 // We will save the location of the ValueInfo needing an update, but
8394 // can only do so once the std::vector is finalized.
8396 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8397 VTableFuncs.push_back({VI, Offset});
8399 if (ParseToken(lltok::rparen, "expected ')' in vTableFunc"))
8401 } while (EatIfPresent(lltok::comma));
8403 // Now that the VTableFuncs vector is finalized, it is safe to save the
8404 // locations of any forward GV references that need updating later.
8405 for (auto I : IdToIndexMap) {
8406 for (auto P : I.second) {
8407 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8408 "Forward referenced ValueInfo expected to be empty");
8409 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8410 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8411 FwdRef.first->second.push_back(
8412 std::make_pair(&VTableFuncs[P.first].FuncVI, P.second));
8416 if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8423 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8424 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8425 assert(Lex.getKind() == lltok::kw_refs);
8428 if (ParseToken(lltok::colon, "expected ':' in refs") |
8429 ParseToken(lltok::lparen, "expected '(' in refs"))
8432 struct ValueContext {
8437 std::vector<ValueContext> VContexts;
8438 // Parse each ref edge
8441 VC.Loc = Lex.getLoc();
8442 if (ParseGVReference(VC.VI, VC.GVId))
8444 VContexts.push_back(VC);
8445 } while (EatIfPresent(lltok::comma));
8447 // Sort value contexts so that ones with writeonly
8448 // and readonly ValueInfo are at the end of VContexts vector.
8449 // See FunctionSummary::specialRefCounts()
8450 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8451 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
8454 IdToIndexMapType IdToIndexMap;
8455 for (auto &VC : VContexts) {
8456 // Keep track of the Refs array index needing a forward reference.
8457 // We will save the location of the ValueInfo needing an update, but
8458 // can only do so once the std::vector is finalized.
8459 if (VC.VI.getRef() == FwdVIRef)
8460 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8461 Refs.push_back(VC.VI);
8464 // Now that the Refs vector is finalized, it is safe to save the locations
8465 // of any forward GV references that need updating later.
8466 for (auto I : IdToIndexMap) {
8467 for (auto P : I.second) {
8468 assert(Refs[P.first].getRef() == FwdVIRef &&
8469 "Forward referenced ValueInfo expected to be empty");
8470 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8471 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8472 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8476 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8482 /// OptionalTypeIdInfo
8483 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8484 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8485 /// [',' TypeCheckedLoadConstVCalls]? ')'
8486 bool LLParser::ParseOptionalTypeIdInfo(
8487 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8488 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8491 if (ParseToken(lltok::colon, "expected ':' here") ||
8492 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8496 switch (Lex.getKind()) {
8497 case lltok::kw_typeTests:
8498 if (ParseTypeTests(TypeIdInfo.TypeTests))
8501 case lltok::kw_typeTestAssumeVCalls:
8502 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8503 TypeIdInfo.TypeTestAssumeVCalls))
8506 case lltok::kw_typeCheckedLoadVCalls:
8507 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8508 TypeIdInfo.TypeCheckedLoadVCalls))
8511 case lltok::kw_typeTestAssumeConstVCalls:
8512 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8513 TypeIdInfo.TypeTestAssumeConstVCalls))
8516 case lltok::kw_typeCheckedLoadConstVCalls:
8517 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8518 TypeIdInfo.TypeCheckedLoadConstVCalls))
8522 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8524 } while (EatIfPresent(lltok::comma));
8526 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8533 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8534 /// [',' (SummaryID | UInt64)]* ')'
8535 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8536 assert(Lex.getKind() == lltok::kw_typeTests);
8539 if (ParseToken(lltok::colon, "expected ':' here") ||
8540 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8543 IdToIndexMapType IdToIndexMap;
8545 GlobalValue::GUID GUID = 0;
8546 if (Lex.getKind() == lltok::SummaryID) {
8547 unsigned ID = Lex.getUIntVal();
8548 LocTy Loc = Lex.getLoc();
8549 // Keep track of the TypeTests array index needing a forward reference.
8550 // We will save the location of the GUID needing an update, but
8551 // can only do so once the std::vector is finalized.
8552 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8554 } else if (ParseUInt64(GUID))
8556 TypeTests.push_back(GUID);
8557 } while (EatIfPresent(lltok::comma));
8559 // Now that the TypeTests vector is finalized, it is safe to save the
8560 // locations of any forward GV references that need updating later.
8561 for (auto I : IdToIndexMap) {
8562 for (auto P : I.second) {
8563 assert(TypeTests[P.first] == 0 &&
8564 "Forward referenced type id GUID expected to be 0");
8565 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8566 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8567 FwdRef.first->second.push_back(
8568 std::make_pair(&TypeTests[P.first], P.second));
8572 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8579 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8580 bool LLParser::ParseVFuncIdList(
8581 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8582 assert(Lex.getKind() == Kind);
8585 if (ParseToken(lltok::colon, "expected ':' here") ||
8586 ParseToken(lltok::lparen, "expected '(' here"))
8589 IdToIndexMapType IdToIndexMap;
8591 FunctionSummary::VFuncId VFuncId;
8592 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8594 VFuncIdList.push_back(VFuncId);
8595 } while (EatIfPresent(lltok::comma));
8597 if (ParseToken(lltok::rparen, "expected ')' here"))
8600 // Now that the VFuncIdList vector is finalized, it is safe to save the
8601 // locations of any forward GV references that need updating later.
8602 for (auto I : IdToIndexMap) {
8603 for (auto P : I.second) {
8604 assert(VFuncIdList[P.first].GUID == 0 &&
8605 "Forward referenced type id GUID expected to be 0");
8606 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8607 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8608 FwdRef.first->second.push_back(
8609 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8617 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8618 bool LLParser::ParseConstVCallList(
8620 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8621 assert(Lex.getKind() == Kind);
8624 if (ParseToken(lltok::colon, "expected ':' here") ||
8625 ParseToken(lltok::lparen, "expected '(' here"))
8628 IdToIndexMapType IdToIndexMap;
8630 FunctionSummary::ConstVCall ConstVCall;
8631 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8633 ConstVCallList.push_back(ConstVCall);
8634 } while (EatIfPresent(lltok::comma));
8636 if (ParseToken(lltok::rparen, "expected ')' here"))
8639 // Now that the ConstVCallList vector is finalized, it is safe to save the
8640 // locations of any forward GV references that need updating later.
8641 for (auto I : IdToIndexMap) {
8642 for (auto P : I.second) {
8643 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8644 "Forward referenced type id GUID expected to be 0");
8645 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8646 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8647 FwdRef.first->second.push_back(
8648 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8656 /// ::= '(' VFuncId ',' Args ')'
8657 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8658 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8659 if (ParseToken(lltok::lparen, "expected '(' here") ||
8660 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8663 if (EatIfPresent(lltok::comma))
8664 if (ParseArgs(ConstVCall.Args))
8667 if (ParseToken(lltok::rparen, "expected ')' here"))
8674 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8675 /// 'offset' ':' UInt64 ')'
8676 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8677 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8678 assert(Lex.getKind() == lltok::kw_vFuncId);
8681 if (ParseToken(lltok::colon, "expected ':' here") ||
8682 ParseToken(lltok::lparen, "expected '(' here"))
8685 if (Lex.getKind() == lltok::SummaryID) {
8687 unsigned ID = Lex.getUIntVal();
8688 LocTy Loc = Lex.getLoc();
8689 // Keep track of the array index needing a forward reference.
8690 // We will save the location of the GUID needing an update, but
8691 // can only do so once the caller's std::vector is finalized.
8692 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8694 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8695 ParseToken(lltok::colon, "expected ':' here") ||
8696 ParseUInt64(VFuncId.GUID))
8699 if (ParseToken(lltok::comma, "expected ',' here") ||
8700 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8701 ParseToken(lltok::colon, "expected ':' here") ||
8702 ParseUInt64(VFuncId.Offset) ||
8703 ParseToken(lltok::rparen, "expected ')' here"))
8710 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8711 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8712 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')'
8713 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8714 assert(Lex.getKind() == lltok::kw_flags);
8717 if (ParseToken(lltok::colon, "expected ':' here") ||
8718 ParseToken(lltok::lparen, "expected '(' here"))
8723 switch (Lex.getKind()) {
8724 case lltok::kw_linkage:
8726 if (ParseToken(lltok::colon, "expected ':'"))
8729 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8730 assert(HasLinkage && "Linkage not optional in summary entry");
8733 case lltok::kw_notEligibleToImport:
8735 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8737 GVFlags.NotEligibleToImport = Flag;
8739 case lltok::kw_live:
8741 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8743 GVFlags.Live = Flag;
8745 case lltok::kw_dsoLocal:
8747 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8749 GVFlags.DSOLocal = Flag;
8751 case lltok::kw_canAutoHide:
8753 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8755 GVFlags.CanAutoHide = Flag;
8758 return Error(Lex.getLoc(), "expected gv flag type");
8760 } while (EatIfPresent(lltok::comma));
8762 if (ParseToken(lltok::rparen, "expected ')' here"))
8769 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
8770 /// ',' 'writeonly' ':' Flag ')'
8771 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8772 assert(Lex.getKind() == lltok::kw_varFlags);
8775 if (ParseToken(lltok::colon, "expected ':' here") ||
8776 ParseToken(lltok::lparen, "expected '(' here"))
8779 auto ParseRest = [this](unsigned int &Val) {
8781 if (ParseToken(lltok::colon, "expected ':'"))
8783 return ParseFlag(Val);
8788 switch (Lex.getKind()) {
8789 case lltok::kw_readonly:
8790 if (ParseRest(Flag))
8792 GVarFlags.MaybeReadOnly = Flag;
8794 case lltok::kw_writeonly:
8795 if (ParseRest(Flag))
8797 GVarFlags.MaybeWriteOnly = Flag;
8800 return Error(Lex.getLoc(), "expected gvar flag type");
8802 } while (EatIfPresent(lltok::comma));
8803 return ParseToken(lltok::rparen, "expected ')' here");
8807 /// ::= 'module' ':' UInt
8808 bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8810 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8811 ParseToken(lltok::colon, "expected ':' here") ||
8812 ParseToken(lltok::SummaryID, "expected module ID"))
8815 unsigned ModuleID = Lex.getUIntVal();
8816 auto I = ModuleIdMap.find(ModuleID);
8817 // We should have already parsed all module IDs
8818 assert(I != ModuleIdMap.end());
8819 ModulePath = I->second;
8825 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8826 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
8828 WriteOnly = EatIfPresent(lltok::kw_writeonly);
8829 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8832 GVId = Lex.getUIntVal();
8833 // Check if we already have a VI for this GV
8834 if (GVId < NumberedValueInfos.size()) {
8835 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
8836 VI = NumberedValueInfos[GVId];
8838 // We will create a forward reference to the stored location.
8839 VI = ValueInfo(false, FwdVIRef);