LLVM 22.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
50#include "llvm/Support/ModRef.h"
53#include <algorithm>
54#include <cassert>
55#include <cstring>
56#include <optional>
57#include <vector>
58
59using namespace llvm;
60
62 "allow-incomplete-ir", cl::init(false), cl::Hidden,
64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
66
67static std::string getTypeString(Type *T) {
68 std::string Result;
69 raw_string_ostream Tmp(Result);
70 Tmp << *T;
71 return Tmp.str();
72}
73
74/// Run: module ::= toplevelentity*
75bool LLParser::Run(bool UpgradeDebugInfo,
76 DataLayoutCallbackTy DataLayoutCallback) {
77 // Prime the lexer.
78 Lex.Lex();
79
80 if (Context.shouldDiscardValueNames())
81 return error(
82 Lex.getLoc(),
83 "Can't read textual IR with a Context that discards named Values");
84
85 if (M) {
86 if (parseTargetDefinitions(DataLayoutCallback))
87 return true;
88 }
89
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
91 validateEndOfIndex();
92}
93
95 const SlotMapping *Slots) {
96 restoreParsingState(Slots);
97 Lex.Lex();
98
99 Type *Ty = nullptr;
100 if (parseType(Ty) || parseConstantValue(Ty, C))
101 return true;
102 if (Lex.getKind() != lltok::Eof)
103 return error(Lex.getLoc(), "expected end of string");
104 return false;
105}
106
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
111
112 Read = 0;
113 SMLoc Start = Lex.getLoc();
114 Ty = nullptr;
115 if (parseType(Ty))
116 return true;
117 SMLoc End = Lex.getLoc();
118 Read = End.getPointer() - Start.getPointer();
119
120 return false;
121}
122
124 const SlotMapping *Slots) {
125 restoreParsingState(Slots);
126 Lex.Lex();
127
128 Read = 0;
129 SMLoc Start = Lex.getLoc();
130 Result = nullptr;
131 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
132 SMLoc End = Lex.getLoc();
133 Read = End.getPointer() - Start.getPointer();
134
135 return Status;
136}
137
138void LLParser::restoreParsingState(const SlotMapping *Slots) {
139 if (!Slots)
140 return;
141 NumberedVals = Slots->GlobalValues;
142 NumberedMetadata = Slots->MetadataNodes;
143 for (const auto &I : Slots->NamedTypes)
144 NamedTypes.insert(
145 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
146 for (const auto &I : Slots->Types)
147 NumberedTypes.insert(
148 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149}
150
152 // White-list intrinsics that are safe to drop.
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
155 return;
156
158 for (Value *V : II->args())
159 if (auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
162 MVs.push_back(MV);
163
164 if (!MVs.empty()) {
165 assert(II->use_empty() && "Cannot have uses");
166 II->eraseFromParent();
167
168 // Also remove no longer used MetadataAsValue wrappers.
169 for (MetadataAsValue *MV : MVs)
170 if (MV->use_empty())
171 delete MV;
172 }
173}
174
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
177 for (Function &F : *M) {
178 F.eraseMetadataIf(Pred);
179 for (Instruction &I : make_early_inc_range(instructions(F))) {
180 I.eraseMetadataIf(Pred);
181
182 if (auto *II = dyn_cast<IntrinsicInst>(&I))
184 }
185 }
186
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
189
190 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
191 // Check whether there is only a single use left, which would be in our
192 // own NumberedMetadata.
193 if (Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(ID);
195 ForwardRefMDNodes.erase(ID);
196 }
197 }
198}
199
200/// validateEndOfModule - Do final validity and basic correctness checks at the
201/// end of the module.
202bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
203 if (!M)
204 return false;
205
206 // We should have already returned an error if we observed both intrinsics and
207 // records in this IR.
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
210
211 // Handle any function attribute group forward references.
212 for (const auto &RAG : ForwardRefAttrGroups) {
213 Value *V = RAG.first;
214 const std::vector<unsigned> &Attrs = RAG.second;
215 AttrBuilder B(Context);
216
217 for (const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
220 B.merge(R->second);
221 }
222
223 if (Function *Fn = dyn_cast<Function>(V)) {
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
227
228 FnAttrs.merge(B);
229
230 // If the alignment was parsed as an attribute, move to the alignment
231 // field.
232 if (MaybeAlign A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
235 }
236
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
239 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
243 FnAttrs.merge(B);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
246 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
247 AttributeList AS = II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
250 FnAttrs.merge(B);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
253 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
257 FnAttrs.merge(B);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
260 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
261 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
262 Attrs.merge(B);
263 GV->setAttributes(AttributeSet::get(Context,Attrs));
264 } else {
265 llvm_unreachable("invalid object with forward attribute group reference");
266 }
267 }
268
269 // If there are entries in ForwardRefBlockAddresses at this point, the
270 // function was never defined.
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
274
275 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV = nullptr;
278 if (GVRef.Kind == ValID::t_GlobalName) {
279 GV = M->getNamedValue(GVRef.StrVal);
280 } else {
281 GV = NumberedVals.get(GVRef.UIntVal);
282 }
283
284 if (!GV)
285 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
286 "' referenced by dso_local_equivalent");
287
288 if (!GV->getValueType()->isFunctionTy())
289 return error(GVRef.Loc,
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
292
293 auto *Equiv = DSOLocalEquivalent::get(GV);
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
296 return false;
297 };
298
299 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
300 // point, they are references after the function was defined. Resolve those
301 // now.
302 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 return true;
305 }
306 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
308 return true;
309 }
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
312
313 for (const auto &NT : NumberedTypes)
314 if (NT.second.second.isValid())
315 return error(NT.second.second,
316 "use of undefined type '%" + Twine(NT.first) + "'");
317
318 for (const auto &[Name, TypeInfo] : NamedTypes)
319 if (TypeInfo.second.isValid())
320 return error(TypeInfo.second,
321 "use of undefined type named '" + Name + "'");
322
323 if (!ForwardRefComdats.empty())
324 return error(ForwardRefComdats.begin()->second,
325 "use of undefined comdat '$" +
326 ForwardRefComdats.begin()->first + "'");
327
328 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
329 if (StringRef(Name).starts_with("llvm.")) {
331 // Automatically create declarations for intrinsics. Intrinsics can only
332 // be called directly, so the call function type directly determines the
333 // declaration function type.
334 //
335 // Additionally, automatically add the required mangling suffix to the
336 // intrinsic name. This means that we may replace a single forward
337 // declaration with multiple functions here.
338 for (Use &U : make_early_inc_range(Info.first->uses())) {
339 auto *CB = dyn_cast<CallBase>(U.getUser());
340 if (!CB || !CB->isCallee(&U))
341 return error(Info.second, "intrinsic can only be used as callee");
342
343 SmallVector<Type *> OverloadTys;
344 if (IID != Intrinsic::not_intrinsic &&
345 Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
346 OverloadTys)) {
347 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
348 } else {
349 // Try to upgrade the intrinsic.
350 Function *TmpF = Function::Create(CB->getFunctionType(),
352 Function *NewF = nullptr;
353 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
354 if (IID == Intrinsic::not_intrinsic)
355 return error(Info.second, "unknown intrinsic '" + Name + "'");
356 return error(Info.second, "invalid intrinsic signature");
357 }
358
359 U.set(TmpF);
360 UpgradeIntrinsicCall(CB, NewF);
361 if (TmpF->use_empty())
362 TmpF->eraseFromParent();
363 }
364 }
365
366 Info.first->eraseFromParent();
367 ForwardRefVals.erase(Name);
368 continue;
369 }
370
371 // If incomplete IR is allowed, also add declarations for
372 // non-intrinsics.
374 continue;
375
376 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
377 FunctionType *FTy = nullptr;
378 for (Use &U : V->uses()) {
379 auto *CB = dyn_cast<CallBase>(U.getUser());
380 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
381 return nullptr;
382 FTy = CB->getFunctionType();
383 }
384 return FTy;
385 };
386
387 // First check whether this global is only used in calls with the same
388 // type, in which case we'll insert a function. Otherwise, fall back to
389 // using a dummy i8 type.
390 Type *Ty = GetCommonFunctionType(Info.first);
391 if (!Ty)
392 Ty = Type::getInt8Ty(Context);
393
394 GlobalValue *GV;
395 if (auto *FTy = dyn_cast<FunctionType>(Ty))
397 else
398 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
400 /*Initializer*/ nullptr, Name);
401 Info.first->replaceAllUsesWith(GV);
402 Info.first->eraseFromParent();
403 ForwardRefVals.erase(Name);
404 }
405
406 if (!ForwardRefVals.empty())
407 return error(ForwardRefVals.begin()->second.second,
408 "use of undefined value '@" + ForwardRefVals.begin()->first +
409 "'");
410
411 if (!ForwardRefValIDs.empty())
412 return error(ForwardRefValIDs.begin()->second.second,
413 "use of undefined value '@" +
414 Twine(ForwardRefValIDs.begin()->first) + "'");
415
416 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
417 dropUnknownMetadataReferences();
418
419 if (!ForwardRefMDNodes.empty())
420 return error(ForwardRefMDNodes.begin()->second.second,
421 "use of undefined metadata '!" +
422 Twine(ForwardRefMDNodes.begin()->first) + "'");
423
424 // Resolve metadata cycles.
425 for (auto &N : NumberedMetadata) {
426 if (N.second && !N.second->isResolved())
427 N.second->resolveCycles();
428 }
429
430 for (auto *Inst : InstsWithTBAATag) {
431 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
432 // With incomplete IR, the tbaa metadata may have been dropped.
434 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
435 if (MD) {
436 auto *UpgradedMD = UpgradeTBAANode(*MD);
437 if (MD != UpgradedMD)
438 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
439 }
440 }
441
442 // Look for intrinsic functions and CallInst that need to be upgraded. We use
443 // make_early_inc_range here because we may remove some functions.
444 for (Function &F : llvm::make_early_inc_range(*M))
446
447 if (UpgradeDebugInfo)
449
454
455 if (!Slots)
456 return false;
457 // Initialize the slot mapping.
458 // Because by this point we've parsed and validated everything, we can "steal"
459 // the mapping from LLParser as it doesn't need it anymore.
460 Slots->GlobalValues = std::move(NumberedVals);
461 Slots->MetadataNodes = std::move(NumberedMetadata);
462 for (const auto &I : NamedTypes)
463 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
464 for (const auto &I : NumberedTypes)
465 Slots->Types.insert(std::make_pair(I.first, I.second.first));
466
467 return false;
468}
469
470/// Do final validity and basic correctness checks at the end of the index.
471bool LLParser::validateEndOfIndex() {
472 if (!Index)
473 return false;
474
475 if (!ForwardRefValueInfos.empty())
476 return error(ForwardRefValueInfos.begin()->second.front().second,
477 "use of undefined summary '^" +
478 Twine(ForwardRefValueInfos.begin()->first) + "'");
479
480 if (!ForwardRefAliasees.empty())
481 return error(ForwardRefAliasees.begin()->second.front().second,
482 "use of undefined summary '^" +
483 Twine(ForwardRefAliasees.begin()->first) + "'");
484
485 if (!ForwardRefTypeIds.empty())
486 return error(ForwardRefTypeIds.begin()->second.front().second,
487 "use of undefined type id summary '^" +
488 Twine(ForwardRefTypeIds.begin()->first) + "'");
489
490 return false;
491}
492
493//===----------------------------------------------------------------------===//
494// Top-Level Entities
495//===----------------------------------------------------------------------===//
496
497bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
498 // Delay parsing of the data layout string until the target triple is known.
499 // Then, pass both the the target triple and the tentative data layout string
500 // to DataLayoutCallback, allowing to override the DL string.
501 // This enables importing modules with invalid DL strings.
502 std::string TentativeDLStr = M->getDataLayoutStr();
503 LocTy DLStrLoc;
504
505 bool Done = false;
506 while (!Done) {
507 switch (Lex.getKind()) {
508 case lltok::kw_target:
509 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
510 return true;
511 break;
513 if (parseSourceFileName())
514 return true;
515 break;
516 default:
517 Done = true;
518 }
519 }
520 // Run the override callback to potentially change the data layout string, and
521 // parse the data layout string.
522 if (auto LayoutOverride =
523 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
524 TentativeDLStr = *LayoutOverride;
525 DLStrLoc = {};
526 }
527 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
528 if (!MaybeDL)
529 return error(DLStrLoc, toString(MaybeDL.takeError()));
530 M->setDataLayout(MaybeDL.get());
531 return false;
532}
533
534bool LLParser::parseTopLevelEntities() {
535 // If there is no Module, then parse just the summary index entries.
536 if (!M) {
537 while (true) {
538 switch (Lex.getKind()) {
539 case lltok::Eof:
540 return false;
541 case lltok::SummaryID:
542 if (parseSummaryEntry())
543 return true;
544 break;
546 if (parseSourceFileName())
547 return true;
548 break;
549 default:
550 // Skip everything else
551 Lex.Lex();
552 }
553 }
554 }
555 while (true) {
556 switch (Lex.getKind()) {
557 default:
558 return tokError("expected top-level entity");
559 case lltok::Eof: return false;
561 if (parseDeclare())
562 return true;
563 break;
564 case lltok::kw_define:
565 if (parseDefine())
566 return true;
567 break;
568 case lltok::kw_module:
569 if (parseModuleAsm())
570 return true;
571 break;
573 if (parseUnnamedType())
574 return true;
575 break;
576 case lltok::LocalVar:
577 if (parseNamedType())
578 return true;
579 break;
580 case lltok::GlobalID:
581 if (parseUnnamedGlobal())
582 return true;
583 break;
584 case lltok::GlobalVar:
585 if (parseNamedGlobal())
586 return true;
587 break;
588 case lltok::ComdatVar: if (parseComdat()) return true; break;
589 case lltok::exclaim:
590 if (parseStandaloneMetadata())
591 return true;
592 break;
593 case lltok::SummaryID:
594 if (parseSummaryEntry())
595 return true;
596 break;
598 if (parseNamedMetadata())
599 return true;
600 break;
602 if (parseUnnamedAttrGrp())
603 return true;
604 break;
606 if (parseUseListOrder())
607 return true;
608 break;
610 if (parseUseListOrderBB())
611 return true;
612 break;
613 }
614 }
615}
616
617/// toplevelentity
618/// ::= 'module' 'asm' STRINGCONSTANT
619bool LLParser::parseModuleAsm() {
620 assert(Lex.getKind() == lltok::kw_module);
621 Lex.Lex();
622
623 std::string AsmStr;
624 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
625 parseStringConstant(AsmStr))
626 return true;
627
628 M->appendModuleInlineAsm(AsmStr);
629 return false;
630}
631
632/// toplevelentity
633/// ::= 'target' 'triple' '=' STRINGCONSTANT
634/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
635bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
636 LocTy &DLStrLoc) {
637 assert(Lex.getKind() == lltok::kw_target);
638 std::string Str;
639 switch (Lex.Lex()) {
640 default:
641 return tokError("unknown target property");
642 case lltok::kw_triple:
643 Lex.Lex();
644 if (parseToken(lltok::equal, "expected '=' after target triple") ||
645 parseStringConstant(Str))
646 return true;
647 M->setTargetTriple(Triple(std::move(Str)));
648 return false;
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
652 return true;
653 DLStrLoc = Lex.getLoc();
654 if (parseStringConstant(TentativeDLStr))
655 return true;
656 return false;
657 }
658}
659
660/// toplevelentity
661/// ::= 'source_filename' '=' STRINGCONSTANT
662bool LLParser::parseSourceFileName() {
663 assert(Lex.getKind() == lltok::kw_source_filename);
664 Lex.Lex();
665 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
666 parseStringConstant(SourceFileName))
667 return true;
668 if (M)
669 M->setSourceFileName(SourceFileName);
670 return false;
671}
672
673/// parseUnnamedType:
674/// ::= LocalVarID '=' 'type' type
675bool LLParser::parseUnnamedType() {
676 LocTy TypeLoc = Lex.getLoc();
677 unsigned TypeID = Lex.getUIntVal();
678 Lex.Lex(); // eat LocalVarID;
679
680 if (parseToken(lltok::equal, "expected '=' after name") ||
681 parseToken(lltok::kw_type, "expected 'type' after '='"))
682 return true;
683
684 Type *Result = nullptr;
685 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
686 return true;
687
688 if (!isa<StructType>(Result)) {
689 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
690 if (Entry.first)
691 return error(TypeLoc, "non-struct types may not be recursive");
692 Entry.first = Result;
693 Entry.second = SMLoc();
694 }
695
696 return false;
697}
698
699/// toplevelentity
700/// ::= LocalVar '=' 'type' type
701bool LLParser::parseNamedType() {
702 std::string Name = Lex.getStrVal();
703 LocTy NameLoc = Lex.getLoc();
704 Lex.Lex(); // eat LocalVar.
705
706 if (parseToken(lltok::equal, "expected '=' after name") ||
707 parseToken(lltok::kw_type, "expected 'type' after name"))
708 return true;
709
710 Type *Result = nullptr;
711 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
712 return true;
713
714 if (!isa<StructType>(Result)) {
715 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
716 if (Entry.first)
717 return error(NameLoc, "non-struct types may not be recursive");
718 Entry.first = Result;
719 Entry.second = SMLoc();
720 }
721
722 return false;
723}
724
725/// toplevelentity
726/// ::= 'declare' FunctionHeader
727bool LLParser::parseDeclare() {
728 assert(Lex.getKind() == lltok::kw_declare);
729 Lex.Lex();
730
731 std::vector<std::pair<unsigned, MDNode *>> MDs;
732 while (Lex.getKind() == lltok::MetadataVar) {
733 unsigned MDK;
734 MDNode *N;
735 if (parseMetadataAttachment(MDK, N))
736 return true;
737 MDs.push_back({MDK, N});
738 }
739
740 Function *F;
741 unsigned FunctionNumber = -1;
742 SmallVector<unsigned> UnnamedArgNums;
743 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
744 return true;
745 for (auto &MD : MDs)
746 F->addMetadata(MD.first, *MD.second);
747 return false;
748}
749
750/// toplevelentity
751/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
752bool LLParser::parseDefine() {
753 assert(Lex.getKind() == lltok::kw_define);
754 FileLoc FunctionStart(Lex.getTokLineColumnPos());
755 Lex.Lex();
756
757 Function *F;
758 unsigned FunctionNumber = -1;
759 SmallVector<unsigned> UnnamedArgNums;
760 bool RetValue =
761 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
762 parseOptionalFunctionMetadata(*F) ||
763 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
764 if (ParserContext)
765 ParserContext->addFunctionLocation(
766 F, FileLocRange(FunctionStart, Lex.getPrevTokEndLineColumnPos()));
767
768 return RetValue;
769}
770
771/// parseGlobalType
772/// ::= 'constant'
773/// ::= 'global'
774bool LLParser::parseGlobalType(bool &IsConstant) {
775 if (Lex.getKind() == lltok::kw_constant)
776 IsConstant = true;
777 else if (Lex.getKind() == lltok::kw_global)
778 IsConstant = false;
779 else {
780 IsConstant = false;
781 return tokError("expected 'global' or 'constant'");
782 }
783 Lex.Lex();
784 return false;
785}
786
787bool LLParser::parseOptionalUnnamedAddr(
788 GlobalVariable::UnnamedAddr &UnnamedAddr) {
789 if (EatIfPresent(lltok::kw_unnamed_addr))
791 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
793 else
794 UnnamedAddr = GlobalValue::UnnamedAddr::None;
795 return false;
796}
797
798/// parseUnnamedGlobal:
799/// OptionalVisibility (ALIAS | IFUNC) ...
800/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
801/// OptionalDLLStorageClass
802/// ... -> global variable
803/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
804/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
805/// OptionalVisibility
806/// OptionalDLLStorageClass
807/// ... -> global variable
808bool LLParser::parseUnnamedGlobal() {
809 unsigned VarID;
810 std::string Name;
811 LocTy NameLoc = Lex.getLoc();
812
813 // Handle the GlobalID form.
814 if (Lex.getKind() == lltok::GlobalID) {
815 VarID = Lex.getUIntVal();
816 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
817 return true;
818
819 Lex.Lex(); // eat GlobalID;
820 if (parseToken(lltok::equal, "expected '=' after name"))
821 return true;
822 } else {
823 VarID = NumberedVals.getNext();
824 }
825
826 bool HasLinkage;
827 unsigned Linkage, Visibility, DLLStorageClass;
828 bool DSOLocal;
830 GlobalVariable::UnnamedAddr UnnamedAddr;
831 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
832 DSOLocal) ||
833 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
834 return true;
835
836 switch (Lex.getKind()) {
837 default:
838 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
839 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
840 case lltok::kw_alias:
841 case lltok::kw_ifunc:
842 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
843 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
844 }
845}
846
847/// parseNamedGlobal:
848/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
849/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
850/// OptionalVisibility OptionalDLLStorageClass
851/// ... -> global variable
852bool LLParser::parseNamedGlobal() {
853 assert(Lex.getKind() == lltok::GlobalVar);
854 LocTy NameLoc = Lex.getLoc();
855 std::string Name = Lex.getStrVal();
856 Lex.Lex();
857
858 bool HasLinkage;
859 unsigned Linkage, Visibility, DLLStorageClass;
860 bool DSOLocal;
862 GlobalVariable::UnnamedAddr UnnamedAddr;
863 if (parseToken(lltok::equal, "expected '=' in global variable") ||
864 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
865 DSOLocal) ||
866 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
867 return true;
868
869 switch (Lex.getKind()) {
870 default:
871 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
872 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
873 case lltok::kw_alias:
874 case lltok::kw_ifunc:
875 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
876 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
877 }
878}
879
880bool LLParser::parseComdat() {
881 assert(Lex.getKind() == lltok::ComdatVar);
882 std::string Name = Lex.getStrVal();
883 LocTy NameLoc = Lex.getLoc();
884 Lex.Lex();
885
886 if (parseToken(lltok::equal, "expected '=' here"))
887 return true;
888
889 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
890 return tokError("expected comdat type");
891
893 switch (Lex.getKind()) {
894 default:
895 return tokError("unknown selection kind");
896 case lltok::kw_any:
897 SK = Comdat::Any;
898 break;
901 break;
903 SK = Comdat::Largest;
904 break;
907 break;
909 SK = Comdat::SameSize;
910 break;
911 }
912 Lex.Lex();
913
914 // See if the comdat was forward referenced, if so, use the comdat.
915 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
916 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
917 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
918 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
919
920 Comdat *C;
921 if (I != ComdatSymTab.end())
922 C = &I->second;
923 else
924 C = M->getOrInsertComdat(Name);
925 C->setSelectionKind(SK);
926
927 return false;
928}
929
930// MDString:
931// ::= '!' STRINGCONSTANT
932bool LLParser::parseMDString(MDString *&Result) {
933 std::string Str;
934 if (parseStringConstant(Str))
935 return true;
936 Result = MDString::get(Context, Str);
937 return false;
938}
939
940// MDNode:
941// ::= '!' MDNodeNumber
942bool LLParser::parseMDNodeID(MDNode *&Result) {
943 // !{ ..., !42, ... }
944 LocTy IDLoc = Lex.getLoc();
945 unsigned MID = 0;
946 if (parseUInt32(MID))
947 return true;
948
949 // If not a forward reference, just return it now.
950 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
951 if (!Inserted) {
952 Result = It->second;
953 return false;
954 }
955
956 // Otherwise, create MDNode forward reference.
957 auto &FwdRef = ForwardRefMDNodes[MID];
958 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
959
960 Result = FwdRef.first.get();
961 It->second.reset(Result);
962 return false;
963}
964
965/// parseNamedMetadata:
966/// !foo = !{ !1, !2 }
967bool LLParser::parseNamedMetadata() {
968 assert(Lex.getKind() == lltok::MetadataVar);
969 std::string Name = Lex.getStrVal();
970 Lex.Lex();
971
972 if (parseToken(lltok::equal, "expected '=' here") ||
973 parseToken(lltok::exclaim, "Expected '!' here") ||
974 parseToken(lltok::lbrace, "Expected '{' here"))
975 return true;
976
977 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
978 if (Lex.getKind() != lltok::rbrace)
979 do {
980 MDNode *N = nullptr;
981 // parse DIExpressions inline as a special case. They are still MDNodes,
982 // so they can still appear in named metadata. Remove this logic if they
983 // become plain Metadata.
984 if (Lex.getKind() == lltok::MetadataVar &&
985 Lex.getStrVal() == "DIExpression") {
986 if (parseDIExpression(N, /*IsDistinct=*/false))
987 return true;
988 // DIArgLists should only appear inline in a function, as they may
989 // contain LocalAsMetadata arguments which require a function context.
990 } else if (Lex.getKind() == lltok::MetadataVar &&
991 Lex.getStrVal() == "DIArgList") {
992 return tokError("found DIArgList outside of function");
993 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
994 parseMDNodeID(N)) {
995 return true;
996 }
997 NMD->addOperand(N);
998 } while (EatIfPresent(lltok::comma));
999
1000 return parseToken(lltok::rbrace, "expected end of metadata node");
1001}
1002
1003/// parseStandaloneMetadata:
1004/// !42 = !{...}
1005bool LLParser::parseStandaloneMetadata() {
1006 assert(Lex.getKind() == lltok::exclaim);
1007 Lex.Lex();
1008 unsigned MetadataID = 0;
1009
1010 MDNode *Init;
1011 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1012 return true;
1013
1014 // Detect common error, from old metadata syntax.
1015 if (Lex.getKind() == lltok::Type)
1016 return tokError("unexpected type in metadata definition");
1017
1018 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1019 if (Lex.getKind() == lltok::MetadataVar) {
1020 if (parseSpecializedMDNode(Init, IsDistinct))
1021 return true;
1022 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1023 parseMDTuple(Init, IsDistinct))
1024 return true;
1025
1026 // See if this was forward referenced, if so, handle it.
1027 auto FI = ForwardRefMDNodes.find(MetadataID);
1028 if (FI != ForwardRefMDNodes.end()) {
1029 auto *ToReplace = FI->second.first.get();
1030 // DIAssignID has its own special forward-reference "replacement" for
1031 // attachments (the temporary attachments are never actually attached).
1032 if (isa<DIAssignID>(Init)) {
1033 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1034 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1035 "Inst unexpectedly already has DIAssignID attachment");
1036 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1037 }
1038 }
1039
1040 ToReplace->replaceAllUsesWith(Init);
1041 ForwardRefMDNodes.erase(FI);
1042
1043 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1044 } else {
1045 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1046 if (!Inserted)
1047 return tokError("Metadata id is already used");
1048 It->second.reset(Init);
1049 }
1050
1051 return false;
1052}
1053
1054// Skips a single module summary entry.
1055bool LLParser::skipModuleSummaryEntry() {
1056 // Each module summary entry consists of a tag for the entry
1057 // type, followed by a colon, then the fields which may be surrounded by
1058 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1059 // support is in place we will look for the tokens corresponding to the
1060 // expected tags.
1061 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1062 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1063 Lex.getKind() != lltok::kw_blockcount)
1064 return tokError(
1065 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1066 "start of summary entry");
1067 if (Lex.getKind() == lltok::kw_flags)
1068 return parseSummaryIndexFlags();
1069 if (Lex.getKind() == lltok::kw_blockcount)
1070 return parseBlockCount();
1071 Lex.Lex();
1072 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1073 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1074 return true;
1075 // Now walk through the parenthesized entry, until the number of open
1076 // parentheses goes back down to 0 (the first '(' was parsed above).
1077 unsigned NumOpenParen = 1;
1078 do {
1079 switch (Lex.getKind()) {
1080 case lltok::lparen:
1081 NumOpenParen++;
1082 break;
1083 case lltok::rparen:
1084 NumOpenParen--;
1085 break;
1086 case lltok::Eof:
1087 return tokError("found end of file while parsing summary entry");
1088 default:
1089 // Skip everything in between parentheses.
1090 break;
1091 }
1092 Lex.Lex();
1093 } while (NumOpenParen > 0);
1094 return false;
1095}
1096
1097/// SummaryEntry
1098/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1099bool LLParser::parseSummaryEntry() {
1100 assert(Lex.getKind() == lltok::SummaryID);
1101 unsigned SummaryID = Lex.getUIntVal();
1102
1103 // For summary entries, colons should be treated as distinct tokens,
1104 // not an indication of the end of a label token.
1105 Lex.setIgnoreColonInIdentifiers(true);
1106
1107 Lex.Lex();
1108 if (parseToken(lltok::equal, "expected '=' here"))
1109 return true;
1110
1111 // If we don't have an index object, skip the summary entry.
1112 if (!Index)
1113 return skipModuleSummaryEntry();
1114
1115 bool result = false;
1116 switch (Lex.getKind()) {
1117 case lltok::kw_gv:
1118 result = parseGVEntry(SummaryID);
1119 break;
1120 case lltok::kw_module:
1121 result = parseModuleEntry(SummaryID);
1122 break;
1123 case lltok::kw_typeid:
1124 result = parseTypeIdEntry(SummaryID);
1125 break;
1127 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1128 break;
1129 case lltok::kw_flags:
1130 result = parseSummaryIndexFlags();
1131 break;
1133 result = parseBlockCount();
1134 break;
1135 default:
1136 result = error(Lex.getLoc(), "unexpected summary kind");
1137 break;
1138 }
1139 Lex.setIgnoreColonInIdentifiers(false);
1140 return result;
1141}
1142
1151
1152// If there was an explicit dso_local, update GV. In the absence of an explicit
1153// dso_local we keep the default value.
1154static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1155 if (DSOLocal)
1156 GV.setDSOLocal(true);
1157}
1158
1159/// parseAliasOrIFunc:
1160/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1161/// OptionalVisibility OptionalDLLStorageClass
1162/// OptionalThreadLocal OptionalUnnamedAddr
1163/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1164///
1165/// AliaseeOrResolver
1166/// ::= TypeAndValue
1167///
1168/// SymbolAttrs
1169/// ::= ',' 'partition' StringConstant
1170///
1171/// Everything through OptionalUnnamedAddr has already been parsed.
1172///
1173bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1174 LocTy NameLoc, unsigned L, unsigned Visibility,
1175 unsigned DLLStorageClass, bool DSOLocal,
1177 GlobalVariable::UnnamedAddr UnnamedAddr) {
1178 bool IsAlias;
1179 if (Lex.getKind() == lltok::kw_alias)
1180 IsAlias = true;
1181 else if (Lex.getKind() == lltok::kw_ifunc)
1182 IsAlias = false;
1183 else
1184 llvm_unreachable("Not an alias or ifunc!");
1185 Lex.Lex();
1186
1188
1189 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1190 return error(NameLoc, "invalid linkage type for alias");
1191
1192 if (!isValidVisibilityForLinkage(Visibility, L))
1193 return error(NameLoc,
1194 "symbol with local linkage must have default visibility");
1195
1196 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1197 return error(NameLoc,
1198 "symbol with local linkage cannot have a DLL storage class");
1199
1200 Type *Ty;
1201 LocTy ExplicitTypeLoc = Lex.getLoc();
1202 if (parseType(Ty) ||
1203 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1204 return true;
1205
1206 Constant *Aliasee;
1207 LocTy AliaseeLoc = Lex.getLoc();
1208 if (Lex.getKind() != lltok::kw_bitcast &&
1209 Lex.getKind() != lltok::kw_getelementptr &&
1210 Lex.getKind() != lltok::kw_addrspacecast &&
1211 Lex.getKind() != lltok::kw_inttoptr) {
1212 if (parseGlobalTypeAndValue(Aliasee))
1213 return true;
1214 } else {
1215 // The bitcast dest type is not present, it is implied by the dest type.
1216 ValID ID;
1217 if (parseValID(ID, /*PFS=*/nullptr))
1218 return true;
1219 if (ID.Kind != ValID::t_Constant)
1220 return error(AliaseeLoc, "invalid aliasee");
1221 Aliasee = ID.ConstantVal;
1222 }
1223
1224 Type *AliaseeType = Aliasee->getType();
1225 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1226 if (!PTy)
1227 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1228 unsigned AddrSpace = PTy->getAddressSpace();
1229
1230 GlobalValue *GVal = nullptr;
1231
1232 // See if the alias was forward referenced, if so, prepare to replace the
1233 // forward reference.
1234 if (!Name.empty()) {
1235 auto I = ForwardRefVals.find(Name);
1236 if (I != ForwardRefVals.end()) {
1237 GVal = I->second.first;
1238 ForwardRefVals.erase(Name);
1239 } else if (M->getNamedValue(Name)) {
1240 return error(NameLoc, "redefinition of global '@" + Name + "'");
1241 }
1242 } else {
1243 auto I = ForwardRefValIDs.find(NameID);
1244 if (I != ForwardRefValIDs.end()) {
1245 GVal = I->second.first;
1246 ForwardRefValIDs.erase(I);
1247 }
1248 }
1249
1250 // Okay, create the alias/ifunc but do not insert it into the module yet.
1251 std::unique_ptr<GlobalAlias> GA;
1252 std::unique_ptr<GlobalIFunc> GI;
1253 GlobalValue *GV;
1254 if (IsAlias) {
1255 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1256 /*Parent=*/nullptr));
1257 GV = GA.get();
1258 } else {
1259 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1260 /*Parent=*/nullptr));
1261 GV = GI.get();
1262 }
1263 GV->setThreadLocalMode(TLM);
1266 GV->setUnnamedAddr(UnnamedAddr);
1267 maybeSetDSOLocal(DSOLocal, *GV);
1268
1269 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1270 // Now parse them if there are any.
1271 while (Lex.getKind() == lltok::comma) {
1272 Lex.Lex();
1273
1274 if (Lex.getKind() == lltok::kw_partition) {
1275 Lex.Lex();
1276 GV->setPartition(Lex.getStrVal());
1277 if (parseToken(lltok::StringConstant, "expected partition string"))
1278 return true;
1279 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1280 if (parseGlobalObjectMetadataAttachment(*GI))
1281 return true;
1282 } else {
1283 return tokError("unknown alias or ifunc property!");
1284 }
1285 }
1286
1287 if (Name.empty())
1288 NumberedVals.add(NameID, GV);
1289
1290 if (GVal) {
1291 // Verify that types agree.
1292 if (GVal->getType() != GV->getType())
1293 return error(
1294 ExplicitTypeLoc,
1295 "forward reference and definition of alias have different types");
1296
1297 // If they agree, just RAUW the old value with the alias and remove the
1298 // forward ref info.
1299 GVal->replaceAllUsesWith(GV);
1300 GVal->eraseFromParent();
1301 }
1302
1303 // Insert into the module, we know its name won't collide now.
1304 if (IsAlias)
1305 M->insertAlias(GA.release());
1306 else
1307 M->insertIFunc(GI.release());
1308 assert(GV->getName() == Name && "Should not be a name conflict!");
1309
1310 return false;
1311}
1312
1313static bool isSanitizer(lltok::Kind Kind) {
1314 switch (Kind) {
1317 case lltok::kw_sanitize_memtag:
1319 return true;
1320 default:
1321 return false;
1322 }
1323}
1324
1325bool LLParser::parseSanitizer(GlobalVariable *GV) {
1326 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1328 if (GV->hasSanitizerMetadata())
1329 Meta = GV->getSanitizerMetadata();
1330
1331 switch (Lex.getKind()) {
1333 Meta.NoAddress = true;
1334 break;
1336 Meta.NoHWAddress = true;
1337 break;
1338 case lltok::kw_sanitize_memtag:
1339 Meta.Memtag = true;
1340 break;
1342 Meta.IsDynInit = true;
1343 break;
1344 default:
1345 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1346 }
1347 GV->setSanitizerMetadata(Meta);
1348 Lex.Lex();
1349 return false;
1350}
1351
1352/// parseGlobal
1353/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1354/// OptionalVisibility OptionalDLLStorageClass
1355/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1356/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1357/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1358/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1359/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1360/// Const OptionalAttrs
1361///
1362/// Everything up to and including OptionalUnnamedAddr has been parsed
1363/// already.
1364///
1365bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1366 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1367 unsigned Visibility, unsigned DLLStorageClass,
1368 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1369 GlobalVariable::UnnamedAddr UnnamedAddr) {
1370 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1371 return error(NameLoc,
1372 "symbol with local linkage must have default visibility");
1373
1374 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1375 return error(NameLoc,
1376 "symbol with local linkage cannot have a DLL storage class");
1377
1378 unsigned AddrSpace;
1379 bool IsConstant, IsExternallyInitialized;
1380 LocTy IsExternallyInitializedLoc;
1381 LocTy TyLoc;
1382
1383 Type *Ty = nullptr;
1384 if (parseOptionalAddrSpace(AddrSpace) ||
1385 parseOptionalToken(lltok::kw_externally_initialized,
1386 IsExternallyInitialized,
1387 &IsExternallyInitializedLoc) ||
1388 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1389 return true;
1390
1391 // If the linkage is specified and is external, then no initializer is
1392 // present.
1393 Constant *Init = nullptr;
1394 if (!HasLinkage ||
1397 if (parseGlobalValue(Ty, Init))
1398 return true;
1399 }
1400
1402 return error(TyLoc, "invalid type for global variable");
1403
1404 GlobalValue *GVal = nullptr;
1405
1406 // See if the global was forward referenced, if so, use the global.
1407 if (!Name.empty()) {
1408 auto I = ForwardRefVals.find(Name);
1409 if (I != ForwardRefVals.end()) {
1410 GVal = I->second.first;
1411 ForwardRefVals.erase(I);
1412 } else if (M->getNamedValue(Name)) {
1413 return error(NameLoc, "redefinition of global '@" + Name + "'");
1414 }
1415 } else {
1416 // Handle @"", where a name is syntactically specified, but semantically
1417 // missing.
1418 if (NameID == (unsigned)-1)
1419 NameID = NumberedVals.getNext();
1420
1421 auto I = ForwardRefValIDs.find(NameID);
1422 if (I != ForwardRefValIDs.end()) {
1423 GVal = I->second.first;
1424 ForwardRefValIDs.erase(I);
1425 }
1426 }
1427
1428 GlobalVariable *GV = new GlobalVariable(
1429 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1431
1432 if (Name.empty())
1433 NumberedVals.add(NameID, GV);
1434
1435 // Set the parsed properties on the global.
1436 if (Init)
1437 GV->setInitializer(Init);
1438 GV->setConstant(IsConstant);
1440 maybeSetDSOLocal(DSOLocal, *GV);
1443 GV->setExternallyInitialized(IsExternallyInitialized);
1444 GV->setThreadLocalMode(TLM);
1445 GV->setUnnamedAddr(UnnamedAddr);
1446
1447 if (GVal) {
1448 if (GVal->getAddressSpace() != AddrSpace)
1449 return error(
1450 TyLoc,
1451 "forward reference and definition of global have different types");
1452
1453 GVal->replaceAllUsesWith(GV);
1454 GVal->eraseFromParent();
1455 }
1456
1457 // parse attributes on the global.
1458 while (Lex.getKind() == lltok::comma) {
1459 Lex.Lex();
1460
1461 if (Lex.getKind() == lltok::kw_section) {
1462 Lex.Lex();
1463 GV->setSection(Lex.getStrVal());
1464 if (parseToken(lltok::StringConstant, "expected global section string"))
1465 return true;
1466 } else if (Lex.getKind() == lltok::kw_partition) {
1467 Lex.Lex();
1468 GV->setPartition(Lex.getStrVal());
1469 if (parseToken(lltok::StringConstant, "expected partition string"))
1470 return true;
1471 } else if (Lex.getKind() == lltok::kw_align) {
1472 MaybeAlign Alignment;
1473 if (parseOptionalAlignment(Alignment))
1474 return true;
1475 if (Alignment)
1476 GV->setAlignment(*Alignment);
1477 } else if (Lex.getKind() == lltok::kw_code_model) {
1479 if (parseOptionalCodeModel(CodeModel))
1480 return true;
1481 GV->setCodeModel(CodeModel);
1482 } else if (Lex.getKind() == lltok::MetadataVar) {
1483 if (parseGlobalObjectMetadataAttachment(*GV))
1484 return true;
1485 } else if (isSanitizer(Lex.getKind())) {
1486 if (parseSanitizer(GV))
1487 return true;
1488 } else {
1489 Comdat *C;
1490 if (parseOptionalComdat(Name, C))
1491 return true;
1492 if (C)
1493 GV->setComdat(C);
1494 else
1495 return tokError("unknown global variable property!");
1496 }
1497 }
1498
1499 AttrBuilder Attrs(M->getContext());
1500 LocTy BuiltinLoc;
1501 std::vector<unsigned> FwdRefAttrGrps;
1502 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1503 return true;
1504 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1505 GV->setAttributes(AttributeSet::get(Context, Attrs));
1506 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1507 }
1508
1509 return false;
1510}
1511
1512/// parseUnnamedAttrGrp
1513/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1514bool LLParser::parseUnnamedAttrGrp() {
1515 assert(Lex.getKind() == lltok::kw_attributes);
1516 LocTy AttrGrpLoc = Lex.getLoc();
1517 Lex.Lex();
1518
1519 if (Lex.getKind() != lltok::AttrGrpID)
1520 return tokError("expected attribute group id");
1521
1522 unsigned VarID = Lex.getUIntVal();
1523 std::vector<unsigned> unused;
1524 LocTy BuiltinLoc;
1525 Lex.Lex();
1526
1527 if (parseToken(lltok::equal, "expected '=' here") ||
1528 parseToken(lltok::lbrace, "expected '{' here"))
1529 return true;
1530
1531 auto R = NumberedAttrBuilders.find(VarID);
1532 if (R == NumberedAttrBuilders.end())
1533 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1534
1535 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1536 parseToken(lltok::rbrace, "expected end of attribute group"))
1537 return true;
1538
1539 if (!R->second.hasAttributes())
1540 return error(AttrGrpLoc, "attribute group has no attributes");
1541
1542 return false;
1543}
1544
1546 switch (Kind) {
1547#define GET_ATTR_NAMES
1548#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1549 case lltok::kw_##DISPLAY_NAME: \
1550 return Attribute::ENUM_NAME;
1551#include "llvm/IR/Attributes.inc"
1552 default:
1553 return Attribute::None;
1554 }
1555}
1556
1557bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1558 bool InAttrGroup) {
1559 if (Attribute::isTypeAttrKind(Attr))
1560 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1561
1562 switch (Attr) {
1563 case Attribute::Alignment: {
1564 MaybeAlign Alignment;
1565 if (InAttrGroup) {
1566 uint32_t Value = 0;
1567 Lex.Lex();
1568 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1569 return true;
1570 Alignment = Align(Value);
1571 } else {
1572 if (parseOptionalAlignment(Alignment, true))
1573 return true;
1574 }
1575 B.addAlignmentAttr(Alignment);
1576 return false;
1577 }
1578 case Attribute::StackAlignment: {
1579 unsigned Alignment;
1580 if (InAttrGroup) {
1581 Lex.Lex();
1582 if (parseToken(lltok::equal, "expected '=' here") ||
1583 parseUInt32(Alignment))
1584 return true;
1585 } else {
1586 if (parseOptionalStackAlignment(Alignment))
1587 return true;
1588 }
1589 B.addStackAlignmentAttr(Alignment);
1590 return false;
1591 }
1592 case Attribute::AllocSize: {
1593 unsigned ElemSizeArg;
1594 std::optional<unsigned> NumElemsArg;
1595 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1596 return true;
1597 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1598 return false;
1599 }
1600 case Attribute::VScaleRange: {
1601 unsigned MinValue, MaxValue;
1602 if (parseVScaleRangeArguments(MinValue, MaxValue))
1603 return true;
1604 B.addVScaleRangeAttr(MinValue,
1605 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1606 return false;
1607 }
1608 case Attribute::Dereferenceable: {
1609 uint64_t Bytes;
1610 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1611 return true;
1612 B.addDereferenceableAttr(Bytes);
1613 return false;
1614 }
1615 case Attribute::DereferenceableOrNull: {
1616 uint64_t Bytes;
1617 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1618 return true;
1619 B.addDereferenceableOrNullAttr(Bytes);
1620 return false;
1621 }
1622 case Attribute::UWTable: {
1624 if (parseOptionalUWTableKind(Kind))
1625 return true;
1626 B.addUWTableAttr(Kind);
1627 return false;
1628 }
1629 case Attribute::AllocKind: {
1631 if (parseAllocKind(Kind))
1632 return true;
1633 B.addAllocKindAttr(Kind);
1634 return false;
1635 }
1636 case Attribute::Memory: {
1637 std::optional<MemoryEffects> ME = parseMemoryAttr();
1638 if (!ME)
1639 return true;
1640 B.addMemoryAttr(*ME);
1641 return false;
1642 }
1643 case Attribute::NoFPClass: {
1644 if (FPClassTest NoFPClass =
1645 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1646 B.addNoFPClassAttr(NoFPClass);
1647 return false;
1648 }
1649
1650 return true;
1651 }
1652 case Attribute::Range:
1653 return parseRangeAttr(B);
1654 case Attribute::Initializes:
1655 return parseInitializesAttr(B);
1656 case Attribute::Captures:
1657 return parseCapturesAttr(B);
1658 default:
1659 B.addAttribute(Attr);
1660 Lex.Lex();
1661 return false;
1662 }
1663}
1664
1666 switch (Kind) {
1667 case lltok::kw_readnone:
1668 ME &= MemoryEffects::none();
1669 return true;
1670 case lltok::kw_readonly:
1672 return true;
1673 case lltok::kw_writeonly:
1675 return true;
1678 return true;
1681 return true;
1684 return true;
1685 default:
1686 return false;
1687 }
1688}
1689
1690/// parseFnAttributeValuePairs
1691/// ::= <attr> | <attr> '=' <value>
1692bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1693 std::vector<unsigned> &FwdRefAttrGrps,
1694 bool InAttrGrp, LocTy &BuiltinLoc) {
1695 bool HaveError = false;
1696
1697 B.clear();
1698
1700 while (true) {
1701 lltok::Kind Token = Lex.getKind();
1702 if (Token == lltok::rbrace)
1703 break; // Finished.
1704
1705 if (Token == lltok::StringConstant) {
1706 if (parseStringAttribute(B))
1707 return true;
1708 continue;
1709 }
1710
1711 if (Token == lltok::AttrGrpID) {
1712 // Allow a function to reference an attribute group:
1713 //
1714 // define void @foo() #1 { ... }
1715 if (InAttrGrp) {
1716 HaveError |= error(
1717 Lex.getLoc(),
1718 "cannot have an attribute group reference in an attribute group");
1719 } else {
1720 // Save the reference to the attribute group. We'll fill it in later.
1721 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1722 }
1723 Lex.Lex();
1724 continue;
1725 }
1726
1727 SMLoc Loc = Lex.getLoc();
1728 if (Token == lltok::kw_builtin)
1729 BuiltinLoc = Loc;
1730
1731 if (upgradeMemoryAttr(ME, Token)) {
1732 Lex.Lex();
1733 continue;
1734 }
1735
1737 if (Attr == Attribute::None) {
1738 if (!InAttrGrp)
1739 break;
1740 return error(Lex.getLoc(), "unterminated attribute group");
1741 }
1742
1743 if (parseEnumAttribute(Attr, B, InAttrGrp))
1744 return true;
1745
1746 // As a hack, we allow function alignment to be initially parsed as an
1747 // attribute on a function declaration/definition or added to an attribute
1748 // group and later moved to the alignment field.
1749 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1750 HaveError |= error(Loc, "this attribute does not apply to functions");
1751 }
1752
1753 if (ME != MemoryEffects::unknown())
1754 B.addMemoryAttr(ME);
1755 return HaveError;
1756}
1757
1758//===----------------------------------------------------------------------===//
1759// GlobalValue Reference/Resolution Routines.
1760//===----------------------------------------------------------------------===//
1761
1763 // The used global type does not matter. We will later RAUW it with a
1764 // global/function of the correct type.
1765 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1768 PTy->getAddressSpace());
1769}
1770
1771Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1772 Value *Val) {
1773 Type *ValTy = Val->getType();
1774 if (ValTy == Ty)
1775 return Val;
1776 if (Ty->isLabelTy())
1777 error(Loc, "'" + Name + "' is not a basic block");
1778 else
1779 error(Loc, "'" + Name + "' defined with type '" +
1780 getTypeString(Val->getType()) + "' but expected '" +
1781 getTypeString(Ty) + "'");
1782 return nullptr;
1783}
1784
1785/// getGlobalVal - Get a value with the specified name or ID, creating a
1786/// forward reference record if needed. This can return null if the value
1787/// exists but does not have the right type.
1788GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1789 LocTy Loc) {
1791 if (!PTy) {
1792 error(Loc, "global variable reference must have pointer type");
1793 return nullptr;
1794 }
1795
1796 // Look this name up in the normal function symbol table.
1797 GlobalValue *Val =
1798 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1799
1800 // If this is a forward reference for the value, see if we already created a
1801 // forward ref record.
1802 if (!Val) {
1803 auto I = ForwardRefVals.find(Name);
1804 if (I != ForwardRefVals.end())
1805 Val = I->second.first;
1806 }
1807
1808 // If we have the value in the symbol table or fwd-ref table, return it.
1809 if (Val)
1811 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1812
1813 // Otherwise, create a new forward reference for this value and remember it.
1814 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1815 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1816 return FwdVal;
1817}
1818
1819GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1821 if (!PTy) {
1822 error(Loc, "global variable reference must have pointer type");
1823 return nullptr;
1824 }
1825
1826 GlobalValue *Val = NumberedVals.get(ID);
1827
1828 // If this is a forward reference for the value, see if we already created a
1829 // forward ref record.
1830 if (!Val) {
1831 auto I = ForwardRefValIDs.find(ID);
1832 if (I != ForwardRefValIDs.end())
1833 Val = I->second.first;
1834 }
1835
1836 // If we have the value in the symbol table or fwd-ref table, return it.
1837 if (Val)
1839 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1840
1841 // Otherwise, create a new forward reference for this value and remember it.
1842 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1843 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1844 return FwdVal;
1845}
1846
1847//===----------------------------------------------------------------------===//
1848// Comdat Reference/Resolution Routines.
1849//===----------------------------------------------------------------------===//
1850
1851Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1852 // Look this name up in the comdat symbol table.
1853 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1854 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1855 if (I != ComdatSymTab.end())
1856 return &I->second;
1857
1858 // Otherwise, create a new forward reference for this value and remember it.
1859 Comdat *C = M->getOrInsertComdat(Name);
1860 ForwardRefComdats[Name] = Loc;
1861 return C;
1862}
1863
1864//===----------------------------------------------------------------------===//
1865// Helper Routines.
1866//===----------------------------------------------------------------------===//
1867
1868/// parseToken - If the current token has the specified kind, eat it and return
1869/// success. Otherwise, emit the specified error and return failure.
1870bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1871 if (Lex.getKind() != T)
1872 return tokError(ErrMsg);
1873 Lex.Lex();
1874 return false;
1875}
1876
1877/// parseStringConstant
1878/// ::= StringConstant
1879bool LLParser::parseStringConstant(std::string &Result) {
1880 if (Lex.getKind() != lltok::StringConstant)
1881 return tokError("expected string constant");
1882 Result = Lex.getStrVal();
1883 Lex.Lex();
1884 return false;
1885}
1886
1887/// parseUInt32
1888/// ::= uint32
1889bool LLParser::parseUInt32(uint32_t &Val) {
1890 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1891 return tokError("expected integer");
1892 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1893 if (Val64 != unsigned(Val64))
1894 return tokError("expected 32-bit integer (too large)");
1895 Val = Val64;
1896 Lex.Lex();
1897 return false;
1898}
1899
1900/// parseUInt64
1901/// ::= uint64
1902bool LLParser::parseUInt64(uint64_t &Val) {
1903 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1904 return tokError("expected integer");
1905 Val = Lex.getAPSIntVal().getLimitedValue();
1906 Lex.Lex();
1907 return false;
1908}
1909
1910/// parseTLSModel
1911/// := 'localdynamic'
1912/// := 'initialexec'
1913/// := 'localexec'
1914bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1915 switch (Lex.getKind()) {
1916 default:
1917 return tokError("expected localdynamic, initialexec or localexec");
1920 break;
1923 break;
1926 break;
1927 }
1928
1929 Lex.Lex();
1930 return false;
1931}
1932
1933/// parseOptionalThreadLocal
1934/// := /*empty*/
1935/// := 'thread_local'
1936/// := 'thread_local' '(' tlsmodel ')'
1937bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1939 if (!EatIfPresent(lltok::kw_thread_local))
1940 return false;
1941
1943 if (Lex.getKind() == lltok::lparen) {
1944 Lex.Lex();
1945 return parseTLSModel(TLM) ||
1946 parseToken(lltok::rparen, "expected ')' after thread local model");
1947 }
1948 return false;
1949}
1950
1951/// parseOptionalAddrSpace
1952/// := /*empty*/
1953/// := 'addrspace' '(' uint32 ')'
1954bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1955 AddrSpace = DefaultAS;
1956 if (!EatIfPresent(lltok::kw_addrspace))
1957 return false;
1958
1959 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1960 if (Lex.getKind() == lltok::StringConstant) {
1961 const std::string &AddrSpaceStr = Lex.getStrVal();
1962 if (AddrSpaceStr == "A") {
1963 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1964 } else if (AddrSpaceStr == "G") {
1965 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1966 } else if (AddrSpaceStr == "P") {
1967 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1968 } else if (std::optional<unsigned> AS =
1969 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
1970 AddrSpace = *AS;
1971 } else {
1972 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1973 }
1974 Lex.Lex();
1975 return false;
1976 }
1977 if (Lex.getKind() != lltok::APSInt)
1978 return tokError("expected integer or string constant");
1979 SMLoc Loc = Lex.getLoc();
1980 if (parseUInt32(AddrSpace))
1981 return true;
1982 if (!isUInt<24>(AddrSpace))
1983 return error(Loc, "invalid address space, must be a 24-bit integer");
1984 return false;
1985 };
1986
1987 return parseToken(lltok::lparen, "expected '(' in address space") ||
1988 ParseAddrspaceValue(AddrSpace) ||
1989 parseToken(lltok::rparen, "expected ')' in address space");
1990}
1991
1992/// parseStringAttribute
1993/// := StringConstant
1994/// := StringConstant '=' StringConstant
1995bool LLParser::parseStringAttribute(AttrBuilder &B) {
1996 std::string Attr = Lex.getStrVal();
1997 Lex.Lex();
1998 std::string Val;
1999 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2000 return true;
2001 B.addAttribute(Attr, Val);
2002 return false;
2003}
2004
2005/// Parse a potentially empty list of parameter or return attributes.
2006bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2007 bool HaveError = false;
2008
2009 B.clear();
2010
2011 while (true) {
2012 lltok::Kind Token = Lex.getKind();
2013 if (Token == lltok::StringConstant) {
2014 if (parseStringAttribute(B))
2015 return true;
2016 continue;
2017 }
2018
2019 if (Token == lltok::kw_nocapture) {
2020 Lex.Lex();
2021 B.addCapturesAttr(CaptureInfo::none());
2022 continue;
2023 }
2024
2025 SMLoc Loc = Lex.getLoc();
2027 if (Attr == Attribute::None)
2028 return HaveError;
2029
2030 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2031 return true;
2032
2033 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2034 HaveError |= error(Loc, "this attribute does not apply to parameters");
2035 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2036 HaveError |= error(Loc, "this attribute does not apply to return values");
2037 }
2038}
2039
2040static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2041 HasLinkage = true;
2042 switch (Kind) {
2043 default:
2044 HasLinkage = false;
2046 case lltok::kw_private:
2048 case lltok::kw_internal:
2050 case lltok::kw_weak:
2052 case lltok::kw_weak_odr:
2054 case lltok::kw_linkonce:
2062 case lltok::kw_common:
2066 case lltok::kw_external:
2068 }
2069}
2070
2071/// parseOptionalLinkage
2072/// ::= /*empty*/
2073/// ::= 'private'
2074/// ::= 'internal'
2075/// ::= 'weak'
2076/// ::= 'weak_odr'
2077/// ::= 'linkonce'
2078/// ::= 'linkonce_odr'
2079/// ::= 'available_externally'
2080/// ::= 'appending'
2081/// ::= 'common'
2082/// ::= 'extern_weak'
2083/// ::= 'external'
2084bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2085 unsigned &Visibility,
2086 unsigned &DLLStorageClass, bool &DSOLocal) {
2087 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2088 if (HasLinkage)
2089 Lex.Lex();
2090 parseOptionalDSOLocal(DSOLocal);
2091 parseOptionalVisibility(Visibility);
2092 parseOptionalDLLStorageClass(DLLStorageClass);
2093
2094 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2095 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2096 }
2097
2098 return false;
2099}
2100
2101void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2102 switch (Lex.getKind()) {
2103 default:
2104 DSOLocal = false;
2105 break;
2107 DSOLocal = true;
2108 Lex.Lex();
2109 break;
2111 DSOLocal = false;
2112 Lex.Lex();
2113 break;
2114 }
2115}
2116
2117/// parseOptionalVisibility
2118/// ::= /*empty*/
2119/// ::= 'default'
2120/// ::= 'hidden'
2121/// ::= 'protected'
2122///
2123void LLParser::parseOptionalVisibility(unsigned &Res) {
2124 switch (Lex.getKind()) {
2125 default:
2127 return;
2128 case lltok::kw_default:
2130 break;
2131 case lltok::kw_hidden:
2133 break;
2136 break;
2137 }
2138 Lex.Lex();
2139}
2140
2141bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2143 switch (Kind) {
2144 default:
2145 return tokError("unknown import kind. Expect definition or declaration.");
2148 return false;
2151 return false;
2152 }
2153}
2154
2155/// parseOptionalDLLStorageClass
2156/// ::= /*empty*/
2157/// ::= 'dllimport'
2158/// ::= 'dllexport'
2159///
2160void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2161 switch (Lex.getKind()) {
2162 default:
2164 return;
2167 break;
2170 break;
2171 }
2172 Lex.Lex();
2173}
2174
2175/// parseOptionalCallingConv
2176/// ::= /*empty*/
2177/// ::= 'ccc'
2178/// ::= 'fastcc'
2179/// ::= 'intel_ocl_bicc'
2180/// ::= 'coldcc'
2181/// ::= 'cfguard_checkcc'
2182/// ::= 'x86_stdcallcc'
2183/// ::= 'x86_fastcallcc'
2184/// ::= 'x86_thiscallcc'
2185/// ::= 'x86_vectorcallcc'
2186/// ::= 'arm_apcscc'
2187/// ::= 'arm_aapcscc'
2188/// ::= 'arm_aapcs_vfpcc'
2189/// ::= 'aarch64_vector_pcs'
2190/// ::= 'aarch64_sve_vector_pcs'
2191/// ::= 'aarch64_sme_preservemost_from_x0'
2192/// ::= 'aarch64_sme_preservemost_from_x1'
2193/// ::= 'aarch64_sme_preservemost_from_x2'
2194/// ::= 'msp430_intrcc'
2195/// ::= 'avr_intrcc'
2196/// ::= 'avr_signalcc'
2197/// ::= 'ptx_kernel'
2198/// ::= 'ptx_device'
2199/// ::= 'spir_func'
2200/// ::= 'spir_kernel'
2201/// ::= 'x86_64_sysvcc'
2202/// ::= 'win64cc'
2203/// ::= 'anyregcc'
2204/// ::= 'preserve_mostcc'
2205/// ::= 'preserve_allcc'
2206/// ::= 'preserve_nonecc'
2207/// ::= 'ghccc'
2208/// ::= 'swiftcc'
2209/// ::= 'swifttailcc'
2210/// ::= 'x86_intrcc'
2211/// ::= 'hhvmcc'
2212/// ::= 'hhvm_ccc'
2213/// ::= 'cxx_fast_tlscc'
2214/// ::= 'amdgpu_vs'
2215/// ::= 'amdgpu_ls'
2216/// ::= 'amdgpu_hs'
2217/// ::= 'amdgpu_es'
2218/// ::= 'amdgpu_gs'
2219/// ::= 'amdgpu_ps'
2220/// ::= 'amdgpu_cs'
2221/// ::= 'amdgpu_cs_chain'
2222/// ::= 'amdgpu_cs_chain_preserve'
2223/// ::= 'amdgpu_kernel'
2224/// ::= 'tailcc'
2225/// ::= 'm68k_rtdcc'
2226/// ::= 'graalcc'
2227/// ::= 'riscv_vector_cc'
2228/// ::= 'riscv_vls_cc'
2229/// ::= 'cc' UINT
2230///
2231bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2232 switch (Lex.getKind()) {
2233 default: CC = CallingConv::C; return false;
2234 case lltok::kw_ccc: CC = CallingConv::C; break;
2235 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2236 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2249 break;
2252 break;
2255 break;
2258 break;
2268 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2269 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2273 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2274 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2277 case lltok::kw_hhvmcc:
2279 break;
2280 case lltok::kw_hhvm_ccc:
2282 break;
2294 break;
2297 break;
2301 break;
2302 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2304 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2307 break;
2309 // Default ABI_VLEN
2311 Lex.Lex();
2312 if (!EatIfPresent(lltok::lparen))
2313 break;
2314 uint32_t ABIVlen;
2315 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2316 return true;
2317 switch (ABIVlen) {
2318 default:
2319 return tokError("unknown RISC-V ABI VLEN");
2320#define CC_VLS_CASE(ABIVlen) \
2321 case ABIVlen: \
2322 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2323 break;
2324 CC_VLS_CASE(32)
2325 CC_VLS_CASE(64)
2326 CC_VLS_CASE(128)
2327 CC_VLS_CASE(256)
2328 CC_VLS_CASE(512)
2329 CC_VLS_CASE(1024)
2330 CC_VLS_CASE(2048)
2331 CC_VLS_CASE(4096)
2332 CC_VLS_CASE(8192)
2333 CC_VLS_CASE(16384)
2334 CC_VLS_CASE(32768)
2335 CC_VLS_CASE(65536)
2336#undef CC_VLS_CASE
2337 }
2338 return false;
2341 break;
2344 break;
2347 break;
2348 case lltok::kw_cc: {
2349 Lex.Lex();
2350 return parseUInt32(CC);
2351 }
2352 }
2353
2354 Lex.Lex();
2355 return false;
2356}
2357
2358/// parseMetadataAttachment
2359/// ::= !dbg !42
2360bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2361 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2362
2363 std::string Name = Lex.getStrVal();
2364 Kind = M->getMDKindID(Name);
2365 Lex.Lex();
2366
2367 return parseMDNode(MD);
2368}
2369
2370/// parseInstructionMetadata
2371/// ::= !dbg !42 (',' !dbg !57)*
2372bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2373 do {
2374 if (Lex.getKind() != lltok::MetadataVar)
2375 return tokError("expected metadata after comma");
2376
2377 unsigned MDK;
2378 MDNode *N;
2379 if (parseMetadataAttachment(MDK, N))
2380 return true;
2381
2382 if (MDK == LLVMContext::MD_DIAssignID)
2383 TempDIAssignIDAttachments[N].push_back(&Inst);
2384 else
2385 Inst.setMetadata(MDK, N);
2386
2387 if (MDK == LLVMContext::MD_tbaa)
2388 InstsWithTBAATag.push_back(&Inst);
2389
2390 // If this is the end of the list, we're done.
2391 } while (EatIfPresent(lltok::comma));
2392 return false;
2393}
2394
2395/// parseGlobalObjectMetadataAttachment
2396/// ::= !dbg !57
2397bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2398 unsigned MDK;
2399 MDNode *N;
2400 if (parseMetadataAttachment(MDK, N))
2401 return true;
2402
2403 GO.addMetadata(MDK, *N);
2404 return false;
2405}
2406
2407/// parseOptionalFunctionMetadata
2408/// ::= (!dbg !57)*
2409bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2410 while (Lex.getKind() == lltok::MetadataVar)
2411 if (parseGlobalObjectMetadataAttachment(F))
2412 return true;
2413 return false;
2414}
2415
2416/// parseOptionalAlignment
2417/// ::= /* empty */
2418/// ::= 'align' 4
2419bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2420 Alignment = std::nullopt;
2421 if (!EatIfPresent(lltok::kw_align))
2422 return false;
2423 LocTy AlignLoc = Lex.getLoc();
2424 uint64_t Value = 0;
2425
2426 LocTy ParenLoc = Lex.getLoc();
2427 bool HaveParens = false;
2428 if (AllowParens) {
2429 if (EatIfPresent(lltok::lparen))
2430 HaveParens = true;
2431 }
2432
2433 if (parseUInt64(Value))
2434 return true;
2435
2436 if (HaveParens && !EatIfPresent(lltok::rparen))
2437 return error(ParenLoc, "expected ')'");
2438
2439 if (!isPowerOf2_64(Value))
2440 return error(AlignLoc, "alignment is not a power of two");
2442 return error(AlignLoc, "huge alignments are not supported yet");
2443 Alignment = Align(Value);
2444 return false;
2445}
2446
2447/// parseOptionalCodeModel
2448/// ::= /* empty */
2449/// ::= 'code_model' "large"
2450bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2451 Lex.Lex();
2452 auto StrVal = Lex.getStrVal();
2453 auto ErrMsg = "expected global code model string";
2454 if (StrVal == "tiny")
2455 model = CodeModel::Tiny;
2456 else if (StrVal == "small")
2457 model = CodeModel::Small;
2458 else if (StrVal == "kernel")
2459 model = CodeModel::Kernel;
2460 else if (StrVal == "medium")
2461 model = CodeModel::Medium;
2462 else if (StrVal == "large")
2463 model = CodeModel::Large;
2464 else
2465 return tokError(ErrMsg);
2466 if (parseToken(lltok::StringConstant, ErrMsg))
2467 return true;
2468 return false;
2469}
2470
2471/// parseOptionalDerefAttrBytes
2472/// ::= /* empty */
2473/// ::= AttrKind '(' 4 ')'
2474///
2475/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2476bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2477 uint64_t &Bytes) {
2478 assert((AttrKind == lltok::kw_dereferenceable ||
2479 AttrKind == lltok::kw_dereferenceable_or_null) &&
2480 "contract!");
2481
2482 Bytes = 0;
2483 if (!EatIfPresent(AttrKind))
2484 return false;
2485 LocTy ParenLoc = Lex.getLoc();
2486 if (!EatIfPresent(lltok::lparen))
2487 return error(ParenLoc, "expected '('");
2488 LocTy DerefLoc = Lex.getLoc();
2489 if (parseUInt64(Bytes))
2490 return true;
2491 ParenLoc = Lex.getLoc();
2492 if (!EatIfPresent(lltok::rparen))
2493 return error(ParenLoc, "expected ')'");
2494 if (!Bytes)
2495 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2496 return false;
2497}
2498
2499bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2500 Lex.Lex();
2502 if (!EatIfPresent(lltok::lparen))
2503 return false;
2504 LocTy KindLoc = Lex.getLoc();
2505 if (Lex.getKind() == lltok::kw_sync)
2507 else if (Lex.getKind() == lltok::kw_async)
2509 else
2510 return error(KindLoc, "expected unwind table kind");
2511 Lex.Lex();
2512 return parseToken(lltok::rparen, "expected ')'");
2513}
2514
2515bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2516 Lex.Lex();
2517 LocTy ParenLoc = Lex.getLoc();
2518 if (!EatIfPresent(lltok::lparen))
2519 return error(ParenLoc, "expected '('");
2520 LocTy KindLoc = Lex.getLoc();
2521 std::string Arg;
2522 if (parseStringConstant(Arg))
2523 return error(KindLoc, "expected allockind value");
2524 for (StringRef A : llvm::split(Arg, ",")) {
2525 if (A == "alloc") {
2527 } else if (A == "realloc") {
2529 } else if (A == "free") {
2531 } else if (A == "uninitialized") {
2533 } else if (A == "zeroed") {
2535 } else if (A == "aligned") {
2537 } else {
2538 return error(KindLoc, Twine("unknown allockind ") + A);
2539 }
2540 }
2541 ParenLoc = Lex.getLoc();
2542 if (!EatIfPresent(lltok::rparen))
2543 return error(ParenLoc, "expected ')'");
2544 if (Kind == AllocFnKind::Unknown)
2545 return error(KindLoc, "expected allockind value");
2546 return false;
2547}
2548
2549static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2550 switch (Tok) {
2551 case lltok::kw_argmem:
2552 return IRMemLocation::ArgMem;
2555 case lltok::kw_errnomem:
2561 default:
2562 return std::nullopt;
2563 }
2564}
2565
2566static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2567 switch (Tok) {
2568 case lltok::kw_none:
2569 return ModRefInfo::NoModRef;
2570 case lltok::kw_read:
2571 return ModRefInfo::Ref;
2572 case lltok::kw_write:
2573 return ModRefInfo::Mod;
2575 return ModRefInfo::ModRef;
2576 default:
2577 return std::nullopt;
2578 }
2579}
2580
2581std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2583
2584 // We use syntax like memory(argmem: read), so the colon should not be
2585 // interpreted as a label terminator.
2586 Lex.setIgnoreColonInIdentifiers(true);
2587 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2588
2589 Lex.Lex();
2590 if (!EatIfPresent(lltok::lparen)) {
2591 tokError("expected '('");
2592 return std::nullopt;
2593 }
2594
2595 bool SeenLoc = false;
2596 do {
2597 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2598 if (Loc) {
2599 Lex.Lex();
2600 if (!EatIfPresent(lltok::colon)) {
2601 tokError("expected ':' after location");
2602 return std::nullopt;
2603 }
2604 }
2605
2606 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2607 if (!MR) {
2608 if (!Loc)
2609 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2610 "or access kind (none, read, write, readwrite)");
2611 else
2612 tokError("expected access kind (none, read, write, readwrite)");
2613 return std::nullopt;
2614 }
2615
2616 Lex.Lex();
2617 if (Loc) {
2618 SeenLoc = true;
2619 ME = ME.getWithModRef(*Loc, *MR);
2620 } else {
2621 if (SeenLoc) {
2622 tokError("default access kind must be specified first");
2623 return std::nullopt;
2624 }
2625 ME = MemoryEffects(*MR);
2626 }
2627
2628 if (EatIfPresent(lltok::rparen))
2629 return ME;
2630 } while (EatIfPresent(lltok::comma));
2631
2632 tokError("unterminated memory attribute");
2633 return std::nullopt;
2634}
2635
2636static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2637 switch (Tok) {
2638 case lltok::kw_all:
2639 return fcAllFlags;
2640 case lltok::kw_nan:
2641 return fcNan;
2642 case lltok::kw_snan:
2643 return fcSNan;
2644 case lltok::kw_qnan:
2645 return fcQNan;
2646 case lltok::kw_inf:
2647 return fcInf;
2648 case lltok::kw_ninf:
2649 return fcNegInf;
2650 case lltok::kw_pinf:
2651 return fcPosInf;
2652 case lltok::kw_norm:
2653 return fcNormal;
2654 case lltok::kw_nnorm:
2655 return fcNegNormal;
2656 case lltok::kw_pnorm:
2657 return fcPosNormal;
2658 case lltok::kw_sub:
2659 return fcSubnormal;
2660 case lltok::kw_nsub:
2661 return fcNegSubnormal;
2662 case lltok::kw_psub:
2663 return fcPosSubnormal;
2664 case lltok::kw_zero:
2665 return fcZero;
2666 case lltok::kw_nzero:
2667 return fcNegZero;
2668 case lltok::kw_pzero:
2669 return fcPosZero;
2670 default:
2671 return 0;
2672 }
2673}
2674
2675unsigned LLParser::parseNoFPClassAttr() {
2676 unsigned Mask = fcNone;
2677
2678 Lex.Lex();
2679 if (!EatIfPresent(lltok::lparen)) {
2680 tokError("expected '('");
2681 return 0;
2682 }
2683
2684 do {
2685 uint64_t Value = 0;
2686 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2687 if (TestMask != 0) {
2688 Mask |= TestMask;
2689 // TODO: Disallow overlapping masks to avoid copy paste errors
2690 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2691 !parseUInt64(Value)) {
2692 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2693 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2694 return 0;
2695 }
2696
2697 if (!EatIfPresent(lltok::rparen)) {
2698 error(Lex.getLoc(), "expected ')'");
2699 return 0;
2700 }
2701
2702 return Value;
2703 } else {
2704 error(Lex.getLoc(), "expected nofpclass test mask");
2705 return 0;
2706 }
2707
2708 Lex.Lex();
2709 if (EatIfPresent(lltok::rparen))
2710 return Mask;
2711 } while (1);
2712
2713 llvm_unreachable("unterminated nofpclass attribute");
2714}
2715
2716/// parseOptionalCommaAlign
2717/// ::=
2718/// ::= ',' align 4
2719///
2720/// This returns with AteExtraComma set to true if it ate an excess comma at the
2721/// end.
2722bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2723 bool &AteExtraComma) {
2724 AteExtraComma = false;
2725 while (EatIfPresent(lltok::comma)) {
2726 // Metadata at the end is an early exit.
2727 if (Lex.getKind() == lltok::MetadataVar) {
2728 AteExtraComma = true;
2729 return false;
2730 }
2731
2732 if (Lex.getKind() != lltok::kw_align)
2733 return error(Lex.getLoc(), "expected metadata or 'align'");
2734
2735 if (parseOptionalAlignment(Alignment))
2736 return true;
2737 }
2738
2739 return false;
2740}
2741
2742/// parseOptionalCommaAddrSpace
2743/// ::=
2744/// ::= ',' addrspace(1)
2745///
2746/// This returns with AteExtraComma set to true if it ate an excess comma at the
2747/// end.
2748bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2749 bool &AteExtraComma) {
2750 AteExtraComma = false;
2751 while (EatIfPresent(lltok::comma)) {
2752 // Metadata at the end is an early exit.
2753 if (Lex.getKind() == lltok::MetadataVar) {
2754 AteExtraComma = true;
2755 return false;
2756 }
2757
2758 Loc = Lex.getLoc();
2759 if (Lex.getKind() != lltok::kw_addrspace)
2760 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2761
2762 if (parseOptionalAddrSpace(AddrSpace))
2763 return true;
2764 }
2765
2766 return false;
2767}
2768
2769bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2770 std::optional<unsigned> &HowManyArg) {
2771 Lex.Lex();
2772
2773 auto StartParen = Lex.getLoc();
2774 if (!EatIfPresent(lltok::lparen))
2775 return error(StartParen, "expected '('");
2776
2777 if (parseUInt32(BaseSizeArg))
2778 return true;
2779
2780 if (EatIfPresent(lltok::comma)) {
2781 auto HowManyAt = Lex.getLoc();
2782 unsigned HowMany;
2783 if (parseUInt32(HowMany))
2784 return true;
2785 if (HowMany == BaseSizeArg)
2786 return error(HowManyAt,
2787 "'allocsize' indices can't refer to the same parameter");
2788 HowManyArg = HowMany;
2789 } else
2790 HowManyArg = std::nullopt;
2791
2792 auto EndParen = Lex.getLoc();
2793 if (!EatIfPresent(lltok::rparen))
2794 return error(EndParen, "expected ')'");
2795 return false;
2796}
2797
2798bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2799 unsigned &MaxValue) {
2800 Lex.Lex();
2801
2802 auto StartParen = Lex.getLoc();
2803 if (!EatIfPresent(lltok::lparen))
2804 return error(StartParen, "expected '('");
2805
2806 if (parseUInt32(MinValue))
2807 return true;
2808
2809 if (EatIfPresent(lltok::comma)) {
2810 if (parseUInt32(MaxValue))
2811 return true;
2812 } else
2813 MaxValue = MinValue;
2814
2815 auto EndParen = Lex.getLoc();
2816 if (!EatIfPresent(lltok::rparen))
2817 return error(EndParen, "expected ')'");
2818 return false;
2819}
2820
2821/// parseScopeAndOrdering
2822/// if isAtomic: ::= SyncScope? AtomicOrdering
2823/// else: ::=
2824///
2825/// This sets Scope and Ordering to the parsed values.
2826bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2827 AtomicOrdering &Ordering) {
2828 if (!IsAtomic)
2829 return false;
2830
2831 return parseScope(SSID) || parseOrdering(Ordering);
2832}
2833
2834/// parseScope
2835/// ::= syncscope("singlethread" | "<target scope>")?
2836///
2837/// This sets synchronization scope ID to the ID of the parsed value.
2838bool LLParser::parseScope(SyncScope::ID &SSID) {
2839 SSID = SyncScope::System;
2840 if (EatIfPresent(lltok::kw_syncscope)) {
2841 auto StartParenAt = Lex.getLoc();
2842 if (!EatIfPresent(lltok::lparen))
2843 return error(StartParenAt, "Expected '(' in syncscope");
2844
2845 std::string SSN;
2846 auto SSNAt = Lex.getLoc();
2847 if (parseStringConstant(SSN))
2848 return error(SSNAt, "Expected synchronization scope name");
2849
2850 auto EndParenAt = Lex.getLoc();
2851 if (!EatIfPresent(lltok::rparen))
2852 return error(EndParenAt, "Expected ')' in syncscope");
2853
2854 SSID = Context.getOrInsertSyncScopeID(SSN);
2855 }
2856
2857 return false;
2858}
2859
2860/// parseOrdering
2861/// ::= AtomicOrdering
2862///
2863/// This sets Ordering to the parsed value.
2864bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2865 switch (Lex.getKind()) {
2866 default:
2867 return tokError("Expected ordering on atomic instruction");
2870 // Not specified yet:
2871 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2875 case lltok::kw_seq_cst:
2877 break;
2878 }
2879 Lex.Lex();
2880 return false;
2881}
2882
2883/// parseOptionalStackAlignment
2884/// ::= /* empty */
2885/// ::= 'alignstack' '(' 4 ')'
2886bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2887 Alignment = 0;
2888 if (!EatIfPresent(lltok::kw_alignstack))
2889 return false;
2890 LocTy ParenLoc = Lex.getLoc();
2891 if (!EatIfPresent(lltok::lparen))
2892 return error(ParenLoc, "expected '('");
2893 LocTy AlignLoc = Lex.getLoc();
2894 if (parseUInt32(Alignment))
2895 return true;
2896 ParenLoc = Lex.getLoc();
2897 if (!EatIfPresent(lltok::rparen))
2898 return error(ParenLoc, "expected ')'");
2899 if (!isPowerOf2_32(Alignment))
2900 return error(AlignLoc, "stack alignment is not a power of two");
2901 return false;
2902}
2903
2904/// parseIndexList - This parses the index list for an insert/extractvalue
2905/// instruction. This sets AteExtraComma in the case where we eat an extra
2906/// comma at the end of the line and find that it is followed by metadata.
2907/// Clients that don't allow metadata can call the version of this function that
2908/// only takes one argument.
2909///
2910/// parseIndexList
2911/// ::= (',' uint32)+
2912///
2913bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2914 bool &AteExtraComma) {
2915 AteExtraComma = false;
2916
2917 if (Lex.getKind() != lltok::comma)
2918 return tokError("expected ',' as start of index list");
2919
2920 while (EatIfPresent(lltok::comma)) {
2921 if (Lex.getKind() == lltok::MetadataVar) {
2922 if (Indices.empty())
2923 return tokError("expected index");
2924 AteExtraComma = true;
2925 return false;
2926 }
2927 unsigned Idx = 0;
2928 if (parseUInt32(Idx))
2929 return true;
2930 Indices.push_back(Idx);
2931 }
2932
2933 return false;
2934}
2935
2936//===----------------------------------------------------------------------===//
2937// Type Parsing.
2938//===----------------------------------------------------------------------===//
2939
2940/// parseType - parse a type.
2941bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2942 SMLoc TypeLoc = Lex.getLoc();
2943 switch (Lex.getKind()) {
2944 default:
2945 return tokError(Msg);
2946 case lltok::Type:
2947 // Type ::= 'float' | 'void' (etc)
2948 Result = Lex.getTyVal();
2949 Lex.Lex();
2950
2951 // Handle "ptr" opaque pointer type.
2952 //
2953 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2954 if (Result->isPointerTy()) {
2955 unsigned AddrSpace;
2956 if (parseOptionalAddrSpace(AddrSpace))
2957 return true;
2958 Result = PointerType::get(getContext(), AddrSpace);
2959
2960 // Give a nice error for 'ptr*'.
2961 if (Lex.getKind() == lltok::star)
2962 return tokError("ptr* is invalid - use ptr instead");
2963
2964 // Fall through to parsing the type suffixes only if this 'ptr' is a
2965 // function return. Otherwise, return success, implicitly rejecting other
2966 // suffixes.
2967 if (Lex.getKind() != lltok::lparen)
2968 return false;
2969 }
2970 break;
2971 case lltok::kw_target: {
2972 // Type ::= TargetExtType
2973 if (parseTargetExtType(Result))
2974 return true;
2975 break;
2976 }
2977 case lltok::lbrace:
2978 // Type ::= StructType
2979 if (parseAnonStructType(Result, false))
2980 return true;
2981 break;
2982 case lltok::lsquare:
2983 // Type ::= '[' ... ']'
2984 Lex.Lex(); // eat the lsquare.
2985 if (parseArrayVectorType(Result, false))
2986 return true;
2987 break;
2988 case lltok::less: // Either vector or packed struct.
2989 // Type ::= '<' ... '>'
2990 Lex.Lex();
2991 if (Lex.getKind() == lltok::lbrace) {
2992 if (parseAnonStructType(Result, true) ||
2993 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2994 return true;
2995 } else if (parseArrayVectorType(Result, true))
2996 return true;
2997 break;
2998 case lltok::LocalVar: {
2999 // Type ::= %foo
3000 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3001
3002 // If the type hasn't been defined yet, create a forward definition and
3003 // remember where that forward def'n was seen (in case it never is defined).
3004 if (!Entry.first) {
3005 Entry.first = StructType::create(Context, Lex.getStrVal());
3006 Entry.second = Lex.getLoc();
3007 }
3008 Result = Entry.first;
3009 Lex.Lex();
3010 break;
3011 }
3012
3013 case lltok::LocalVarID: {
3014 // Type ::= %4
3015 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3016
3017 // If the type hasn't been defined yet, create a forward definition and
3018 // remember where that forward def'n was seen (in case it never is defined).
3019 if (!Entry.first) {
3020 Entry.first = StructType::create(Context);
3021 Entry.second = Lex.getLoc();
3022 }
3023 Result = Entry.first;
3024 Lex.Lex();
3025 break;
3026 }
3027 }
3028
3029 // parse the type suffixes.
3030 while (true) {
3031 switch (Lex.getKind()) {
3032 // End of type.
3033 default:
3034 if (!AllowVoid && Result->isVoidTy())
3035 return error(TypeLoc, "void type only allowed for function results");
3036 return false;
3037
3038 // Type ::= Type '*'
3039 case lltok::star:
3040 if (Result->isLabelTy())
3041 return tokError("basic block pointers are invalid");
3042 if (Result->isVoidTy())
3043 return tokError("pointers to void are invalid - use i8* instead");
3045 return tokError("pointer to this type is invalid");
3046 Result = PointerType::getUnqual(Context);
3047 Lex.Lex();
3048 break;
3049
3050 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3051 case lltok::kw_addrspace: {
3052 if (Result->isLabelTy())
3053 return tokError("basic block pointers are invalid");
3054 if (Result->isVoidTy())
3055 return tokError("pointers to void are invalid; use i8* instead");
3057 return tokError("pointer to this type is invalid");
3058 unsigned AddrSpace;
3059 if (parseOptionalAddrSpace(AddrSpace) ||
3060 parseToken(lltok::star, "expected '*' in address space"))
3061 return true;
3062
3063 Result = PointerType::get(Context, AddrSpace);
3064 break;
3065 }
3066
3067 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3068 case lltok::lparen:
3069 if (parseFunctionType(Result))
3070 return true;
3071 break;
3072 }
3073 }
3074}
3075
3076/// parseParameterList
3077/// ::= '(' ')'
3078/// ::= '(' Arg (',' Arg)* ')'
3079/// Arg
3080/// ::= Type OptionalAttributes Value OptionalAttributes
3081bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3082 PerFunctionState &PFS, bool IsMustTailCall,
3083 bool InVarArgsFunc) {
3084 if (parseToken(lltok::lparen, "expected '(' in call"))
3085 return true;
3086
3087 while (Lex.getKind() != lltok::rparen) {
3088 // If this isn't the first argument, we need a comma.
3089 if (!ArgList.empty() &&
3090 parseToken(lltok::comma, "expected ',' in argument list"))
3091 return true;
3092
3093 // parse an ellipsis if this is a musttail call in a variadic function.
3094 if (Lex.getKind() == lltok::dotdotdot) {
3095 const char *Msg = "unexpected ellipsis in argument list for ";
3096 if (!IsMustTailCall)
3097 return tokError(Twine(Msg) + "non-musttail call");
3098 if (!InVarArgsFunc)
3099 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3100 Lex.Lex(); // Lex the '...', it is purely for readability.
3101 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3102 }
3103
3104 // parse the argument.
3105 LocTy ArgLoc;
3106 Type *ArgTy = nullptr;
3107 Value *V;
3108 if (parseType(ArgTy, ArgLoc))
3109 return true;
3111 return error(ArgLoc, "invalid type for function argument");
3112
3113 AttrBuilder ArgAttrs(M->getContext());
3114
3115 if (ArgTy->isMetadataTy()) {
3116 if (parseMetadataAsValue(V, PFS))
3117 return true;
3118 } else {
3119 // Otherwise, handle normal operands.
3120 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3121 return true;
3122 }
3123 ArgList.push_back(ParamInfo(
3124 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3125 }
3126
3127 if (IsMustTailCall && InVarArgsFunc)
3128 return tokError("expected '...' at end of argument list for musttail call "
3129 "in varargs function");
3130
3131 Lex.Lex(); // Lex the ')'.
3132 return false;
3133}
3134
3135/// parseRequiredTypeAttr
3136/// ::= attrname(<ty>)
3137bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3138 Attribute::AttrKind AttrKind) {
3139 Type *Ty = nullptr;
3140 if (!EatIfPresent(AttrToken))
3141 return true;
3142 if (!EatIfPresent(lltok::lparen))
3143 return error(Lex.getLoc(), "expected '('");
3144 if (parseType(Ty))
3145 return true;
3146 if (!EatIfPresent(lltok::rparen))
3147 return error(Lex.getLoc(), "expected ')'");
3148
3149 B.addTypeAttr(AttrKind, Ty);
3150 return false;
3151}
3152
3153/// parseRangeAttr
3154/// ::= range(<ty> <n>,<n>)
3155bool LLParser::parseRangeAttr(AttrBuilder &B) {
3156 Lex.Lex();
3157
3158 APInt Lower;
3159 APInt Upper;
3160 Type *Ty = nullptr;
3161 LocTy TyLoc;
3162
3163 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3164 if (Lex.getKind() != lltok::APSInt)
3165 return tokError("expected integer");
3166 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3167 return tokError(
3168 "integer is too large for the bit width of specified type");
3169 Val = Lex.getAPSIntVal().extend(BitWidth);
3170 Lex.Lex();
3171 return false;
3172 };
3173
3174 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3175 return true;
3176 if (!Ty->isIntegerTy())
3177 return error(TyLoc, "the range must have integer type!");
3178
3179 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3180
3181 if (ParseAPSInt(BitWidth, Lower) ||
3182 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3183 return true;
3184 if (Lower == Upper && !Lower.isZero())
3185 return tokError("the range represent the empty set but limits aren't 0!");
3186
3187 if (parseToken(lltok::rparen, "expected ')'"))
3188 return true;
3189
3190 B.addRangeAttr(ConstantRange(Lower, Upper));
3191 return false;
3192}
3193
3194/// parseInitializesAttr
3195/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3196bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3197 Lex.Lex();
3198
3199 auto ParseAPSInt = [&](APInt &Val) {
3200 if (Lex.getKind() != lltok::APSInt)
3201 return tokError("expected integer");
3202 Val = Lex.getAPSIntVal().extend(64);
3203 Lex.Lex();
3204 return false;
3205 };
3206
3207 if (parseToken(lltok::lparen, "expected '('"))
3208 return true;
3209
3211 // Parse each constant range.
3212 do {
3213 APInt Lower, Upper;
3214 if (parseToken(lltok::lparen, "expected '('"))
3215 return true;
3216
3217 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3218 ParseAPSInt(Upper))
3219 return true;
3220
3221 if (Lower == Upper)
3222 return tokError("the range should not represent the full or empty set!");
3223
3224 if (parseToken(lltok::rparen, "expected ')'"))
3225 return true;
3226
3227 RangeList.push_back(ConstantRange(Lower, Upper));
3228 } while (EatIfPresent(lltok::comma));
3229
3230 if (parseToken(lltok::rparen, "expected ')'"))
3231 return true;
3232
3233 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3234 if (!CRLOrNull.has_value())
3235 return tokError("Invalid (unordered or overlapping) range list");
3236 B.addInitializesAttr(*CRLOrNull);
3237 return false;
3238}
3239
3240bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3242 std::optional<CaptureComponents> Ret;
3243
3244 // We use syntax like captures(ret: address, provenance), so the colon
3245 // should not be interpreted as a label terminator.
3246 Lex.setIgnoreColonInIdentifiers(true);
3247 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3248
3249 Lex.Lex();
3250 if (parseToken(lltok::lparen, "expected '('"))
3251 return true;
3252
3253 CaptureComponents *Current = &Other;
3254 bool SeenComponent = false;
3255 while (true) {
3256 if (EatIfPresent(lltok::kw_ret)) {
3257 if (parseToken(lltok::colon, "expected ':'"))
3258 return true;
3259 if (Ret)
3260 return tokError("duplicate 'ret' location");
3262 Current = &*Ret;
3263 SeenComponent = false;
3264 }
3265
3266 if (EatIfPresent(lltok::kw_none)) {
3267 if (SeenComponent)
3268 return tokError("cannot use 'none' with other component");
3269 *Current = CaptureComponents::None;
3270 } else {
3271 if (SeenComponent && capturesNothing(*Current))
3272 return tokError("cannot use 'none' with other component");
3273
3274 if (EatIfPresent(lltok::kw_address_is_null))
3276 else if (EatIfPresent(lltok::kw_address))
3277 *Current |= CaptureComponents::Address;
3278 else if (EatIfPresent(lltok::kw_provenance))
3280 else if (EatIfPresent(lltok::kw_read_provenance))
3282 else
3283 return tokError("expected one of 'none', 'address', 'address_is_null', "
3284 "'provenance' or 'read_provenance'");
3285 }
3286
3287 SeenComponent = true;
3288 if (EatIfPresent(lltok::rparen))
3289 break;
3290
3291 if (parseToken(lltok::comma, "expected ',' or ')'"))
3292 return true;
3293 }
3294
3295 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3296 return false;
3297}
3298
3299/// parseOptionalOperandBundles
3300/// ::= /*empty*/
3301/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3302///
3303/// OperandBundle
3304/// ::= bundle-tag '(' ')'
3305/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3306///
3307/// bundle-tag ::= String Constant
3308bool LLParser::parseOptionalOperandBundles(
3309 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3310 LocTy BeginLoc = Lex.getLoc();
3311 if (!EatIfPresent(lltok::lsquare))
3312 return false;
3313
3314 while (Lex.getKind() != lltok::rsquare) {
3315 // If this isn't the first operand bundle, we need a comma.
3316 if (!BundleList.empty() &&
3317 parseToken(lltok::comma, "expected ',' in input list"))
3318 return true;
3319
3320 std::string Tag;
3321 if (parseStringConstant(Tag))
3322 return true;
3323
3324 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3325 return true;
3326
3327 std::vector<Value *> Inputs;
3328 while (Lex.getKind() != lltok::rparen) {
3329 // If this isn't the first input, we need a comma.
3330 if (!Inputs.empty() &&
3331 parseToken(lltok::comma, "expected ',' in input list"))
3332 return true;
3333
3334 Type *Ty = nullptr;
3335 Value *Input = nullptr;
3336 if (parseType(Ty))
3337 return true;
3338 if (Ty->isMetadataTy()) {
3339 if (parseMetadataAsValue(Input, PFS))
3340 return true;
3341 } else if (parseValue(Ty, Input, PFS)) {
3342 return true;
3343 }
3344 Inputs.push_back(Input);
3345 }
3346
3347 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3348
3349 Lex.Lex(); // Lex the ')'.
3350 }
3351
3352 if (BundleList.empty())
3353 return error(BeginLoc, "operand bundle set must not be empty");
3354
3355 Lex.Lex(); // Lex the ']'.
3356 return false;
3357}
3358
3359bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3360 unsigned NextID, unsigned ID) {
3361 if (ID < NextID)
3362 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3363 Twine(NextID) + "' or greater");
3364
3365 return false;
3366}
3367
3368/// parseArgumentList - parse the argument list for a function type or function
3369/// prototype.
3370/// ::= '(' ArgTypeListI ')'
3371/// ArgTypeListI
3372/// ::= /*empty*/
3373/// ::= '...'
3374/// ::= ArgTypeList ',' '...'
3375/// ::= ArgType (',' ArgType)*
3376///
3377bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3378 SmallVectorImpl<unsigned> &UnnamedArgNums,
3379 bool &IsVarArg) {
3380 unsigned CurValID = 0;
3381 IsVarArg = false;
3382 assert(Lex.getKind() == lltok::lparen);
3383 Lex.Lex(); // eat the (.
3384
3385 if (Lex.getKind() != lltok::rparen) {
3386 do {
3387 // Handle ... at end of arg list.
3388 if (EatIfPresent(lltok::dotdotdot)) {
3389 IsVarArg = true;
3390 break;
3391 }
3392
3393 // Otherwise must be an argument type.
3394 LocTy TypeLoc = Lex.getLoc();
3395 Type *ArgTy = nullptr;
3396 AttrBuilder Attrs(M->getContext());
3397 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3398 return true;
3399
3400 if (ArgTy->isVoidTy())
3401 return error(TypeLoc, "argument can not have void type");
3402
3403 std::string Name;
3404 if (Lex.getKind() == lltok::LocalVar) {
3405 Name = Lex.getStrVal();
3406 Lex.Lex();
3407 } else {
3408 unsigned ArgID;
3409 if (Lex.getKind() == lltok::LocalVarID) {
3410 ArgID = Lex.getUIntVal();
3411 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3412 return true;
3413 Lex.Lex();
3414 } else {
3415 ArgID = CurValID;
3416 }
3417 UnnamedArgNums.push_back(ArgID);
3418 CurValID = ArgID + 1;
3419 }
3420
3422 return error(TypeLoc, "invalid type for function argument");
3423
3424 ArgList.emplace_back(TypeLoc, ArgTy,
3425 AttributeSet::get(ArgTy->getContext(), Attrs),
3426 std::move(Name));
3427 } while (EatIfPresent(lltok::comma));
3428 }
3429
3430 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3431}
3432
3433/// parseFunctionType
3434/// ::= Type ArgumentList OptionalAttrs
3435bool LLParser::parseFunctionType(Type *&Result) {
3436 assert(Lex.getKind() == lltok::lparen);
3437
3439 return tokError("invalid function return type");
3440
3442 bool IsVarArg;
3443 SmallVector<unsigned> UnnamedArgNums;
3444 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3445 return true;
3446
3447 // Reject names on the arguments lists.
3448 for (const ArgInfo &Arg : ArgList) {
3449 if (!Arg.Name.empty())
3450 return error(Arg.Loc, "argument name invalid in function type");
3451 if (Arg.Attrs.hasAttributes())
3452 return error(Arg.Loc, "argument attributes invalid in function type");
3453 }
3454
3455 SmallVector<Type*, 16> ArgListTy;
3456 for (const ArgInfo &Arg : ArgList)
3457 ArgListTy.push_back(Arg.Ty);
3458
3459 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3460 return false;
3461}
3462
3463/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3464/// other structs.
3465bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3467 if (parseStructBody(Elts))
3468 return true;
3469
3470 Result = StructType::get(Context, Elts, Packed);
3471 return false;
3472}
3473
3474/// parseStructDefinition - parse a struct in a 'type' definition.
3475bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3476 std::pair<Type *, LocTy> &Entry,
3477 Type *&ResultTy) {
3478 // If the type was already defined, diagnose the redefinition.
3479 if (Entry.first && !Entry.second.isValid())
3480 return error(TypeLoc, "redefinition of type");
3481
3482 // If we have opaque, just return without filling in the definition for the
3483 // struct. This counts as a definition as far as the .ll file goes.
3484 if (EatIfPresent(lltok::kw_opaque)) {
3485 // This type is being defined, so clear the location to indicate this.
3486 Entry.second = SMLoc();
3487
3488 // If this type number has never been uttered, create it.
3489 if (!Entry.first)
3490 Entry.first = StructType::create(Context, Name);
3491 ResultTy = Entry.first;
3492 return false;
3493 }
3494
3495 // If the type starts with '<', then it is either a packed struct or a vector.
3496 bool isPacked = EatIfPresent(lltok::less);
3497
3498 // If we don't have a struct, then we have a random type alias, which we
3499 // accept for compatibility with old files. These types are not allowed to be
3500 // forward referenced and not allowed to be recursive.
3501 if (Lex.getKind() != lltok::lbrace) {
3502 if (Entry.first)
3503 return error(TypeLoc, "forward references to non-struct type");
3504
3505 ResultTy = nullptr;
3506 if (isPacked)
3507 return parseArrayVectorType(ResultTy, true);
3508 return parseType(ResultTy);
3509 }
3510
3511 // This type is being defined, so clear the location to indicate this.
3512 Entry.second = SMLoc();
3513
3514 // If this type number has never been uttered, create it.
3515 if (!Entry.first)
3516 Entry.first = StructType::create(Context, Name);
3517
3518 StructType *STy = cast<StructType>(Entry.first);
3519
3521 if (parseStructBody(Body) ||
3522 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3523 return true;
3524
3525 if (auto E = STy->setBodyOrError(Body, isPacked))
3526 return tokError(toString(std::move(E)));
3527
3528 ResultTy = STy;
3529 return false;
3530}
3531
3532/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3533/// StructType
3534/// ::= '{' '}'
3535/// ::= '{' Type (',' Type)* '}'
3536/// ::= '<' '{' '}' '>'
3537/// ::= '<' '{' Type (',' Type)* '}' '>'
3538bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3539 assert(Lex.getKind() == lltok::lbrace);
3540 Lex.Lex(); // Consume the '{'
3541
3542 // Handle the empty struct.
3543 if (EatIfPresent(lltok::rbrace))
3544 return false;
3545
3546 LocTy EltTyLoc = Lex.getLoc();
3547 Type *Ty = nullptr;
3548 if (parseType(Ty))
3549 return true;
3550 Body.push_back(Ty);
3551
3553 return error(EltTyLoc, "invalid element type for struct");
3554
3555 while (EatIfPresent(lltok::comma)) {
3556 EltTyLoc = Lex.getLoc();
3557 if (parseType(Ty))
3558 return true;
3559
3561 return error(EltTyLoc, "invalid element type for struct");
3562
3563 Body.push_back(Ty);
3564 }
3565
3566 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3567}
3568
3569/// parseArrayVectorType - parse an array or vector type, assuming the first
3570/// token has already been consumed.
3571/// Type
3572/// ::= '[' APSINTVAL 'x' Types ']'
3573/// ::= '<' APSINTVAL 'x' Types '>'
3574/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3575bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3576 bool Scalable = false;
3577
3578 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3579 Lex.Lex(); // consume the 'vscale'
3580 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3581 return true;
3582
3583 Scalable = true;
3584 }
3585
3586 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3587 Lex.getAPSIntVal().getBitWidth() > 64)
3588 return tokError("expected number in address space");
3589
3590 LocTy SizeLoc = Lex.getLoc();
3591 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3592 Lex.Lex();
3593
3594 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3595 return true;
3596
3597 LocTy TypeLoc = Lex.getLoc();
3598 Type *EltTy = nullptr;
3599 if (parseType(EltTy))
3600 return true;
3601
3602 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3603 "expected end of sequential type"))
3604 return true;
3605
3606 if (IsVector) {
3607 if (Size == 0)
3608 return error(SizeLoc, "zero element vector is illegal");
3609 if ((unsigned)Size != Size)
3610 return error(SizeLoc, "size too large for vector");
3612 return error(TypeLoc, "invalid vector element type");
3613 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3614 } else {
3616 return error(TypeLoc, "invalid array element type");
3617 Result = ArrayType::get(EltTy, Size);
3618 }
3619 return false;
3620}
3621
3622/// parseTargetExtType - handle target extension type syntax
3623/// TargetExtType
3624/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3625///
3626/// TargetExtTypeParams
3627/// ::= /*empty*/
3628/// ::= ',' Type TargetExtTypeParams
3629///
3630/// TargetExtIntParams
3631/// ::= /*empty*/
3632/// ::= ',' uint32 TargetExtIntParams
3633bool LLParser::parseTargetExtType(Type *&Result) {
3634 Lex.Lex(); // Eat the 'target' keyword.
3635
3636 // Get the mandatory type name.
3637 std::string TypeName;
3638 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3639 parseStringConstant(TypeName))
3640 return true;
3641
3642 // Parse all of the integer and type parameters at the same time; the use of
3643 // SeenInt will allow us to catch cases where type parameters follow integer
3644 // parameters.
3645 SmallVector<Type *> TypeParams;
3646 SmallVector<unsigned> IntParams;
3647 bool SeenInt = false;
3648 while (Lex.getKind() == lltok::comma) {
3649 Lex.Lex(); // Eat the comma.
3650
3651 if (Lex.getKind() == lltok::APSInt) {
3652 SeenInt = true;
3653 unsigned IntVal;
3654 if (parseUInt32(IntVal))
3655 return true;
3656 IntParams.push_back(IntVal);
3657 } else if (SeenInt) {
3658 // The only other kind of parameter we support is type parameters, which
3659 // must precede the integer parameters. This is therefore an error.
3660 return tokError("expected uint32 param");
3661 } else {
3662 Type *TypeParam;
3663 if (parseType(TypeParam, /*AllowVoid=*/true))
3664 return true;
3665 TypeParams.push_back(TypeParam);
3666 }
3667 }
3668
3669 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3670 return true;
3671
3672 auto TTy =
3673 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3674 if (auto E = TTy.takeError())
3675 return tokError(toString(std::move(E)));
3676
3677 Result = *TTy;
3678 return false;
3679}
3680
3681//===----------------------------------------------------------------------===//
3682// Function Semantic Analysis.
3683//===----------------------------------------------------------------------===//
3684
3685LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3686 int functionNumber,
3687 ArrayRef<unsigned> UnnamedArgNums)
3688 : P(p), F(f), FunctionNumber(functionNumber) {
3689
3690 // Insert unnamed arguments into the NumberedVals list.
3691 auto It = UnnamedArgNums.begin();
3692 for (Argument &A : F.args()) {
3693 if (!A.hasName()) {
3694 unsigned ArgNum = *It++;
3695 NumberedVals.add(ArgNum, &A);
3696 }
3697 }
3698}
3699
3700LLParser::PerFunctionState::~PerFunctionState() {
3701 // If there were any forward referenced non-basicblock values, delete them.
3702
3703 for (const auto &P : ForwardRefVals) {
3704 if (isa<BasicBlock>(P.second.first))
3705 continue;
3706 P.second.first->replaceAllUsesWith(
3707 PoisonValue::get(P.second.first->getType()));
3708 P.second.first->deleteValue();
3709 }
3710
3711 for (const auto &P : ForwardRefValIDs) {
3712 if (isa<BasicBlock>(P.second.first))
3713 continue;
3714 P.second.first->replaceAllUsesWith(
3715 PoisonValue::get(P.second.first->getType()));
3716 P.second.first->deleteValue();
3717 }
3718}
3719
3720bool LLParser::PerFunctionState::finishFunction() {
3721 if (!ForwardRefVals.empty())
3722 return P.error(ForwardRefVals.begin()->second.second,
3723 "use of undefined value '%" + ForwardRefVals.begin()->first +
3724 "'");
3725 if (!ForwardRefValIDs.empty())
3726 return P.error(ForwardRefValIDs.begin()->second.second,
3727 "use of undefined value '%" +
3728 Twine(ForwardRefValIDs.begin()->first) + "'");
3729 return false;
3730}
3731
3732/// getVal - Get a value with the specified name or ID, creating a
3733/// forward reference record if needed. This can return null if the value
3734/// exists but does not have the right type.
3735Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3736 LocTy Loc) {
3737 // Look this name up in the normal function symbol table.
3738 Value *Val = F.getValueSymbolTable()->lookup(Name);
3739
3740 // If this is a forward reference for the value, see if we already created a
3741 // forward ref record.
3742 if (!Val) {
3743 auto I = ForwardRefVals.find(Name);
3744 if (I != ForwardRefVals.end())
3745 Val = I->second.first;
3746 }
3747
3748 // If we have the value in the symbol table or fwd-ref table, return it.
3749 if (Val)
3750 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3751
3752 // Don't make placeholders with invalid type.
3753 if (!Ty->isFirstClassType()) {
3754 P.error(Loc, "invalid use of a non-first-class type");
3755 return nullptr;
3756 }
3757
3758 // Otherwise, create a new forward reference for this value and remember it.
3759 Value *FwdVal;
3760 if (Ty->isLabelTy()) {
3761 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3762 } else {
3763 FwdVal = new Argument(Ty, Name);
3764 }
3765 if (FwdVal->getName() != Name) {
3766 P.error(Loc, "name is too long which can result in name collisions, "
3767 "consider making the name shorter or "
3768 "increasing -non-global-value-max-name-size");
3769 return nullptr;
3770 }
3771
3772 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3773 return FwdVal;
3774}
3775
3776Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3777 // Look this name up in the normal function symbol table.
3778 Value *Val = NumberedVals.get(ID);
3779
3780 // If this is a forward reference for the value, see if we already created a
3781 // forward ref record.
3782 if (!Val) {
3783 auto I = ForwardRefValIDs.find(ID);
3784 if (I != ForwardRefValIDs.end())
3785 Val = I->second.first;
3786 }
3787
3788 // If we have the value in the symbol table or fwd-ref table, return it.
3789 if (Val)
3790 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3791
3792 if (!Ty->isFirstClassType()) {
3793 P.error(Loc, "invalid use of a non-first-class type");
3794 return nullptr;
3795 }
3796
3797 // Otherwise, create a new forward reference for this value and remember it.
3798 Value *FwdVal;
3799 if (Ty->isLabelTy()) {
3800 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3801 } else {
3802 FwdVal = new Argument(Ty);
3803 }
3804
3805 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3806 return FwdVal;
3807}
3808
3809/// setInstName - After an instruction is parsed and inserted into its
3810/// basic block, this installs its name.
3811bool LLParser::PerFunctionState::setInstName(int NameID,
3812 const std::string &NameStr,
3813 LocTy NameLoc, Instruction *Inst) {
3814 // If this instruction has void type, it cannot have a name or ID specified.
3815 if (Inst->getType()->isVoidTy()) {
3816 if (NameID != -1 || !NameStr.empty())
3817 return P.error(NameLoc, "instructions returning void cannot have a name");
3818 return false;
3819 }
3820
3821 // If this was a numbered instruction, verify that the instruction is the
3822 // expected value and resolve any forward references.
3823 if (NameStr.empty()) {
3824 // If neither a name nor an ID was specified, just use the next ID.
3825 if (NameID == -1)
3826 NameID = NumberedVals.getNext();
3827
3828 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3829 NameID))
3830 return true;
3831
3832 auto FI = ForwardRefValIDs.find(NameID);
3833 if (FI != ForwardRefValIDs.end()) {
3834 Value *Sentinel = FI->second.first;
3835 if (Sentinel->getType() != Inst->getType())
3836 return P.error(NameLoc, "instruction forward referenced with type '" +
3837 getTypeString(FI->second.first->getType()) +
3838 "'");
3839
3840 Sentinel->replaceAllUsesWith(Inst);
3841 Sentinel->deleteValue();
3842 ForwardRefValIDs.erase(FI);
3843 }
3844
3845 NumberedVals.add(NameID, Inst);
3846 return false;
3847 }
3848
3849 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3850 auto FI = ForwardRefVals.find(NameStr);
3851 if (FI != ForwardRefVals.end()) {
3852 Value *Sentinel = FI->second.first;
3853 if (Sentinel->getType() != Inst->getType())
3854 return P.error(NameLoc, "instruction forward referenced with type '" +
3855 getTypeString(FI->second.first->getType()) +
3856 "'");
3857
3858 Sentinel->replaceAllUsesWith(Inst);
3859 Sentinel->deleteValue();
3860 ForwardRefVals.erase(FI);
3861 }
3862
3863 // Set the name on the instruction.
3864 Inst->setName(NameStr);
3865
3866 if (Inst->getName() != NameStr)
3867 return P.error(NameLoc, "multiple definition of local value named '" +
3868 NameStr + "'");
3869 return false;
3870}
3871
3872/// getBB - Get a basic block with the specified name or ID, creating a
3873/// forward reference record if needed.
3874BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3875 LocTy Loc) {
3877 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3878}
3879
3880BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3882 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3883}
3884
3885/// defineBB - Define the specified basic block, which is either named or
3886/// unnamed. If there is an error, this returns null otherwise it returns
3887/// the block being defined.
3888BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3889 int NameID, LocTy Loc) {
3890 BasicBlock *BB;
3891 if (Name.empty()) {
3892 if (NameID != -1) {
3893 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3894 return nullptr;
3895 } else {
3896 NameID = NumberedVals.getNext();
3897 }
3898 BB = getBB(NameID, Loc);
3899 if (!BB) {
3900 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3901 return nullptr;
3902 }
3903 } else {
3904 BB = getBB(Name, Loc);
3905 if (!BB) {
3906 P.error(Loc, "unable to create block named '" + Name + "'");
3907 return nullptr;
3908 }
3909 }
3910
3911 // Move the block to the end of the function. Forward ref'd blocks are
3912 // inserted wherever they happen to be referenced.
3913 F.splice(F.end(), &F, BB->getIterator());
3914
3915 // Remove the block from forward ref sets.
3916 if (Name.empty()) {
3917 ForwardRefValIDs.erase(NameID);
3918 NumberedVals.add(NameID, BB);
3919 } else {
3920 // BB forward references are already in the function symbol table.
3921 ForwardRefVals.erase(Name);
3922 }
3923
3924 return BB;
3925}
3926
3927//===----------------------------------------------------------------------===//
3928// Constants.
3929//===----------------------------------------------------------------------===//
3930
3931/// parseValID - parse an abstract value that doesn't necessarily have a
3932/// type implied. For example, if we parse "4" we don't know what integer type
3933/// it has. The value will later be combined with its type and checked for
3934/// basic correctness. PFS is used to convert function-local operands of
3935/// metadata (since metadata operands are not just parsed here but also
3936/// converted to values). PFS can be null when we are not parsing metadata
3937/// values inside a function.
3938bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3939 ID.Loc = Lex.getLoc();
3940 switch (Lex.getKind()) {
3941 default:
3942 return tokError("expected value token");
3943 case lltok::GlobalID: // @42
3944 ID.UIntVal = Lex.getUIntVal();
3945 ID.Kind = ValID::t_GlobalID;
3946 break;
3947 case lltok::GlobalVar: // @foo
3948 ID.StrVal = Lex.getStrVal();
3949 ID.Kind = ValID::t_GlobalName;
3950 break;
3951 case lltok::LocalVarID: // %42
3952 ID.UIntVal = Lex.getUIntVal();
3953 ID.Kind = ValID::t_LocalID;
3954 break;
3955 case lltok::LocalVar: // %foo
3956 ID.StrVal = Lex.getStrVal();
3957 ID.Kind = ValID::t_LocalName;
3958 break;
3959 case lltok::APSInt:
3960 ID.APSIntVal = Lex.getAPSIntVal();
3961 ID.Kind = ValID::t_APSInt;
3962 break;
3963 case lltok::APFloat:
3964 ID.APFloatVal = Lex.getAPFloatVal();
3965 ID.Kind = ValID::t_APFloat;
3966 break;
3967 case lltok::kw_true:
3968 ID.ConstantVal = ConstantInt::getTrue(Context);
3969 ID.Kind = ValID::t_Constant;
3970 break;
3971 case lltok::kw_false:
3972 ID.ConstantVal = ConstantInt::getFalse(Context);
3973 ID.Kind = ValID::t_Constant;
3974 break;
3975 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3976 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3977 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3978 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3979 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3980
3981 case lltok::lbrace: {
3982 // ValID ::= '{' ConstVector '}'
3983 Lex.Lex();
3985 if (parseGlobalValueVector(Elts) ||
3986 parseToken(lltok::rbrace, "expected end of struct constant"))
3987 return true;
3988
3989 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3990 ID.UIntVal = Elts.size();
3991 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3992 Elts.size() * sizeof(Elts[0]));
3994 return false;
3995 }
3996 case lltok::less: {
3997 // ValID ::= '<' ConstVector '>' --> Vector.
3998 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3999 Lex.Lex();
4000 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4001
4003 LocTy FirstEltLoc = Lex.getLoc();
4004 if (parseGlobalValueVector(Elts) ||
4005 (isPackedStruct &&
4006 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4007 parseToken(lltok::greater, "expected end of constant"))
4008 return true;
4009
4010 if (isPackedStruct) {
4011 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4012 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4013 Elts.size() * sizeof(Elts[0]));
4014 ID.UIntVal = Elts.size();
4016 return false;
4017 }
4018
4019 if (Elts.empty())
4020 return error(ID.Loc, "constant vector must not be empty");
4021
4022 if (!Elts[0]->getType()->isIntegerTy() &&
4023 !Elts[0]->getType()->isFloatingPointTy() &&
4024 !Elts[0]->getType()->isPointerTy())
4025 return error(
4026 FirstEltLoc,
4027 "vector elements must have integer, pointer or floating point type");
4028
4029 // Verify that all the vector elements have the same type.
4030 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4031 if (Elts[i]->getType() != Elts[0]->getType())
4032 return error(FirstEltLoc, "vector element #" + Twine(i) +
4033 " is not of type '" +
4034 getTypeString(Elts[0]->getType()));
4035
4036 ID.ConstantVal = ConstantVector::get(Elts);
4037 ID.Kind = ValID::t_Constant;
4038 return false;
4039 }
4040 case lltok::lsquare: { // Array Constant
4041 Lex.Lex();
4043 LocTy FirstEltLoc = Lex.getLoc();
4044 if (parseGlobalValueVector(Elts) ||
4045 parseToken(lltok::rsquare, "expected end of array constant"))
4046 return true;
4047
4048 // Handle empty element.
4049 if (Elts.empty()) {
4050 // Use undef instead of an array because it's inconvenient to determine
4051 // the element type at this point, there being no elements to examine.
4052 ID.Kind = ValID::t_EmptyArray;
4053 return false;
4054 }
4055
4056 if (!Elts[0]->getType()->isFirstClassType())
4057 return error(FirstEltLoc, "invalid array element type: " +
4058 getTypeString(Elts[0]->getType()));
4059
4060 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4061
4062 // Verify all elements are correct type!
4063 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4064 if (Elts[i]->getType() != Elts[0]->getType())
4065 return error(FirstEltLoc, "array element #" + Twine(i) +
4066 " is not of type '" +
4067 getTypeString(Elts[0]->getType()));
4068 }
4069
4070 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4071 ID.Kind = ValID::t_Constant;
4072 return false;
4073 }
4074 case lltok::kw_c: // c "foo"
4075 Lex.Lex();
4076 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4077 false);
4078 if (parseToken(lltok::StringConstant, "expected string"))
4079 return true;
4080 ID.Kind = ValID::t_Constant;
4081 return false;
4082
4083 case lltok::kw_asm: {
4084 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4085 // STRINGCONSTANT
4086 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4087 Lex.Lex();
4088 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4089 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4090 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4091 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4092 parseStringConstant(ID.StrVal) ||
4093 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4094 parseToken(lltok::StringConstant, "expected constraint string"))
4095 return true;
4096 ID.StrVal2 = Lex.getStrVal();
4097 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4098 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4099 ID.Kind = ValID::t_InlineAsm;
4100 return false;
4101 }
4102
4104 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4105 Lex.Lex();
4106
4107 ValID Fn, Label;
4108
4109 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4110 parseValID(Fn, PFS) ||
4111 parseToken(lltok::comma,
4112 "expected comma in block address expression") ||
4113 parseValID(Label, PFS) ||
4114 parseToken(lltok::rparen, "expected ')' in block address expression"))
4115 return true;
4116
4118 return error(Fn.Loc, "expected function name in blockaddress");
4119 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4120 return error(Label.Loc, "expected basic block name in blockaddress");
4121
4122 // Try to find the function (but skip it if it's forward-referenced).
4123 GlobalValue *GV = nullptr;
4124 if (Fn.Kind == ValID::t_GlobalID) {
4125 GV = NumberedVals.get(Fn.UIntVal);
4126 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4127 GV = M->getNamedValue(Fn.StrVal);
4128 }
4129 Function *F = nullptr;
4130 if (GV) {
4131 // Confirm that it's actually a function with a definition.
4132 if (!isa<Function>(GV))
4133 return error(Fn.Loc, "expected function name in blockaddress");
4134 F = cast<Function>(GV);
4135 if (F->isDeclaration())
4136 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4137 }
4138
4139 if (!F) {
4140 // Make a global variable as a placeholder for this reference.
4141 GlobalValue *&FwdRef =
4142 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4143 if (!FwdRef) {
4144 unsigned FwdDeclAS;
4145 if (ExpectedTy) {
4146 // If we know the type that the blockaddress is being assigned to,
4147 // we can use the address space of that type.
4148 if (!ExpectedTy->isPointerTy())
4149 return error(ID.Loc,
4150 "type of blockaddress must be a pointer and not '" +
4151 getTypeString(ExpectedTy) + "'");
4152 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4153 } else if (PFS) {
4154 // Otherwise, we default the address space of the current function.
4155 FwdDeclAS = PFS->getFunction().getAddressSpace();
4156 } else {
4157 llvm_unreachable("Unknown address space for blockaddress");
4158 }
4159 FwdRef = new GlobalVariable(
4160 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4161 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4162 }
4163
4164 ID.ConstantVal = FwdRef;
4165 ID.Kind = ValID::t_Constant;
4166 return false;
4167 }
4168
4169 // We found the function; now find the basic block. Don't use PFS, since we
4170 // might be inside a constant expression.
4171 BasicBlock *BB;
4172 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4173 if (Label.Kind == ValID::t_LocalID)
4174 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4175 else
4176 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4177 if (!BB)
4178 return error(Label.Loc, "referenced value is not a basic block");
4179 } else {
4180 if (Label.Kind == ValID::t_LocalID)
4181 return error(Label.Loc, "cannot take address of numeric label after "
4182 "the function is defined");
4184 F->getValueSymbolTable()->lookup(Label.StrVal));
4185 if (!BB)
4186 return error(Label.Loc, "referenced value is not a basic block");
4187 }
4188
4189 ID.ConstantVal = BlockAddress::get(F, BB);
4190 ID.Kind = ValID::t_Constant;
4191 return false;
4192 }
4193
4195 // ValID ::= 'dso_local_equivalent' @foo
4196 Lex.Lex();
4197
4198 ValID Fn;
4199
4200 if (parseValID(Fn, PFS))
4201 return true;
4202
4204 return error(Fn.Loc,
4205 "expected global value name in dso_local_equivalent");
4206
4207 // Try to find the function (but skip it if it's forward-referenced).
4208 GlobalValue *GV = nullptr;
4209 if (Fn.Kind == ValID::t_GlobalID) {
4210 GV = NumberedVals.get(Fn.UIntVal);
4211 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4212 GV = M->getNamedValue(Fn.StrVal);
4213 }
4214
4215 if (!GV) {
4216 // Make a placeholder global variable as a placeholder for this reference.
4217 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4218 ? ForwardRefDSOLocalEquivalentIDs
4219 : ForwardRefDSOLocalEquivalentNames;
4220 GlobalValue *&FwdRef = FwdRefMap[Fn];
4221 if (!FwdRef) {
4222 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4223 GlobalValue::InternalLinkage, nullptr, "",
4225 }
4226
4227 ID.ConstantVal = FwdRef;
4228 ID.Kind = ValID::t_Constant;
4229 return false;
4230 }
4231
4232 if (!GV->getValueType()->isFunctionTy())
4233 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4234 "in dso_local_equivalent");
4235
4236 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4237 ID.Kind = ValID::t_Constant;
4238 return false;
4239 }
4240
4241 case lltok::kw_no_cfi: {
4242 // ValID ::= 'no_cfi' @foo
4243 Lex.Lex();
4244
4245 if (parseValID(ID, PFS))
4246 return true;
4247
4248 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4249 return error(ID.Loc, "expected global value name in no_cfi");
4250
4251 ID.NoCFI = true;
4252 return false;
4253 }
4254 case lltok::kw_ptrauth: {
4255 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4256 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4257 // )? )? ')'
4258 Lex.Lex();
4259
4260 Constant *Ptr, *Key;
4261 Constant *Disc = nullptr, *AddrDisc = nullptr,
4262 *DeactivationSymbol = nullptr;
4263
4264 if (parseToken(lltok::lparen,
4265 "expected '(' in constant ptrauth expression") ||
4266 parseGlobalTypeAndValue(Ptr) ||
4267 parseToken(lltok::comma,
4268 "expected comma in constant ptrauth expression") ||
4269 parseGlobalTypeAndValue(Key))
4270 return true;
4271 // If present, parse the optional disc/addrdisc/ds.
4272 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4273 return true;
4274 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4275 return true;
4276 if (EatIfPresent(lltok::comma) &&
4277 parseGlobalTypeAndValue(DeactivationSymbol))
4278 return true;
4279 if (parseToken(lltok::rparen,
4280 "expected ')' in constant ptrauth expression"))
4281 return true;
4282
4283 if (!Ptr->getType()->isPointerTy())
4284 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4285
4286 auto *KeyC = dyn_cast<ConstantInt>(Key);
4287 if (!KeyC || KeyC->getBitWidth() != 32)
4288 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4289
4290 ConstantInt *DiscC = nullptr;
4291 if (Disc) {
4292 DiscC = dyn_cast<ConstantInt>(Disc);
4293 if (!DiscC || DiscC->getBitWidth() != 64)
4294 return error(
4295 ID.Loc,
4296 "constant ptrauth integer discriminator must be i64 constant");
4297 } else {
4298 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4299 }
4300
4301 if (AddrDisc) {
4302 if (!AddrDisc->getType()->isPointerTy())
4303 return error(
4304 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4305 } else {
4306 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4307 }
4308
4309 if (!DeactivationSymbol)
4310 DeactivationSymbol =
4312 if (!DeactivationSymbol->getType()->isPointerTy())
4313 return error(ID.Loc,
4314 "constant ptrauth deactivation symbol must be a pointer");
4315
4316 ID.ConstantVal =
4317 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4318 ID.Kind = ValID::t_Constant;
4319 return false;
4320 }
4321
4322 case lltok::kw_trunc:
4323 case lltok::kw_bitcast:
4325 case lltok::kw_inttoptr:
4327 case lltok::kw_ptrtoint: {
4328 unsigned Opc = Lex.getUIntVal();
4329 Type *DestTy = nullptr;
4330 Constant *SrcVal;
4331 Lex.Lex();
4332 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4333 parseGlobalTypeAndValue(SrcVal) ||
4334 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4335 parseType(DestTy) ||
4336 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4337 return true;
4338 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4339 return error(ID.Loc, "invalid cast opcode for cast from '" +
4340 getTypeString(SrcVal->getType()) + "' to '" +
4341 getTypeString(DestTy) + "'");
4343 SrcVal, DestTy);
4344 ID.Kind = ValID::t_Constant;
4345 return false;
4346 }
4348 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4350 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4351 case lltok::kw_udiv:
4352 return error(ID.Loc, "udiv constexprs are no longer supported");
4353 case lltok::kw_sdiv:
4354 return error(ID.Loc, "sdiv constexprs are no longer supported");
4355 case lltok::kw_urem:
4356 return error(ID.Loc, "urem constexprs are no longer supported");
4357 case lltok::kw_srem:
4358 return error(ID.Loc, "srem constexprs are no longer supported");
4359 case lltok::kw_fadd:
4360 return error(ID.Loc, "fadd constexprs are no longer supported");
4361 case lltok::kw_fsub:
4362 return error(ID.Loc, "fsub constexprs are no longer supported");
4363 case lltok::kw_fmul:
4364 return error(ID.Loc, "fmul constexprs are no longer supported");
4365 case lltok::kw_fdiv:
4366 return error(ID.Loc, "fdiv constexprs are no longer supported");
4367 case lltok::kw_frem:
4368 return error(ID.Loc, "frem constexprs are no longer supported");
4369 case lltok::kw_and:
4370 return error(ID.Loc, "and constexprs are no longer supported");
4371 case lltok::kw_or:
4372 return error(ID.Loc, "or constexprs are no longer supported");
4373 case lltok::kw_lshr:
4374 return error(ID.Loc, "lshr constexprs are no longer supported");
4375 case lltok::kw_ashr:
4376 return error(ID.Loc, "ashr constexprs are no longer supported");
4377 case lltok::kw_shl:
4378 return error(ID.Loc, "shl constexprs are no longer supported");
4379 case lltok::kw_mul:
4380 return error(ID.Loc, "mul constexprs are no longer supported");
4381 case lltok::kw_fneg:
4382 return error(ID.Loc, "fneg constexprs are no longer supported");
4383 case lltok::kw_select:
4384 return error(ID.Loc, "select constexprs are no longer supported");
4385 case lltok::kw_zext:
4386 return error(ID.Loc, "zext constexprs are no longer supported");
4387 case lltok::kw_sext:
4388 return error(ID.Loc, "sext constexprs are no longer supported");
4389 case lltok::kw_fptrunc:
4390 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4391 case lltok::kw_fpext:
4392 return error(ID.Loc, "fpext constexprs are no longer supported");
4393 case lltok::kw_uitofp:
4394 return error(ID.Loc, "uitofp constexprs are no longer supported");
4395 case lltok::kw_sitofp:
4396 return error(ID.Loc, "sitofp constexprs are no longer supported");
4397 case lltok::kw_fptoui:
4398 return error(ID.Loc, "fptoui constexprs are no longer supported");
4399 case lltok::kw_fptosi:
4400 return error(ID.Loc, "fptosi constexprs are no longer supported");
4401 case lltok::kw_icmp:
4402 return error(ID.Loc, "icmp constexprs are no longer supported");
4403 case lltok::kw_fcmp:
4404 return error(ID.Loc, "fcmp constexprs are no longer supported");
4405
4406 // Binary Operators.
4407 case lltok::kw_add:
4408 case lltok::kw_sub:
4409 case lltok::kw_xor: {
4410 bool NUW = false;
4411 bool NSW = false;
4412 unsigned Opc = Lex.getUIntVal();
4413 Constant *Val0, *Val1;
4414 Lex.Lex();
4415 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4416 Opc == Instruction::Mul) {
4417 if (EatIfPresent(lltok::kw_nuw))
4418 NUW = true;
4419 if (EatIfPresent(lltok::kw_nsw)) {
4420 NSW = true;
4421 if (EatIfPresent(lltok::kw_nuw))
4422 NUW = true;
4423 }
4424 }
4425 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4426 parseGlobalTypeAndValue(Val0) ||
4427 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4428 parseGlobalTypeAndValue(Val1) ||
4429 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4430 return true;
4431 if (Val0->getType() != Val1->getType())
4432 return error(ID.Loc, "operands of constexpr must have same type");
4433 // Check that the type is valid for the operator.
4434 if (!Val0->getType()->isIntOrIntVectorTy())
4435 return error(ID.Loc,
4436 "constexpr requires integer or integer vector operands");
4437 unsigned Flags = 0;
4440 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4441 ID.Kind = ValID::t_Constant;
4442 return false;
4443 }
4444
4445 case lltok::kw_splat: {
4446 Lex.Lex();
4447 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4448 return true;
4449 Constant *C;
4450 if (parseGlobalTypeAndValue(C))
4451 return true;
4452 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4453 return true;
4454
4455 ID.ConstantVal = C;
4457 return false;
4458 }
4459
4464 unsigned Opc = Lex.getUIntVal();
4466 GEPNoWrapFlags NW;
4467 bool HasInRange = false;
4468 APSInt InRangeStart;
4469 APSInt InRangeEnd;
4470 Type *Ty;
4471 Lex.Lex();
4472
4473 if (Opc == Instruction::GetElementPtr) {
4474 while (true) {
4475 if (EatIfPresent(lltok::kw_inbounds))
4477 else if (EatIfPresent(lltok::kw_nusw))
4479 else if (EatIfPresent(lltok::kw_nuw))
4481 else
4482 break;
4483 }
4484
4485 if (EatIfPresent(lltok::kw_inrange)) {
4486 if (parseToken(lltok::lparen, "expected '('"))
4487 return true;
4488 if (Lex.getKind() != lltok::APSInt)
4489 return tokError("expected integer");
4490 InRangeStart = Lex.getAPSIntVal();
4491 Lex.Lex();
4492 if (parseToken(lltok::comma, "expected ','"))
4493 return true;
4494 if (Lex.getKind() != lltok::APSInt)
4495 return tokError("expected integer");
4496 InRangeEnd = Lex.getAPSIntVal();
4497 Lex.Lex();
4498 if (parseToken(lltok::rparen, "expected ')'"))
4499 return true;
4500 HasInRange = true;
4501 }
4502 }
4503
4504 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4505 return true;
4506
4507 if (Opc == Instruction::GetElementPtr) {
4508 if (parseType(Ty) ||
4509 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4510 return true;
4511 }
4512
4513 if (parseGlobalValueVector(Elts) ||
4514 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4515 return true;
4516
4517 if (Opc == Instruction::GetElementPtr) {
4518 if (Elts.size() == 0 ||
4519 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4520 return error(ID.Loc, "base of getelementptr must be a pointer");
4521
4522 Type *BaseType = Elts[0]->getType();
4523 std::optional<ConstantRange> InRange;
4524 if (HasInRange) {
4525 unsigned IndexWidth =
4526 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4527 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4528 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4529 if (InRangeStart.sge(InRangeEnd))
4530 return error(ID.Loc, "expected end to be larger than start");
4531 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4532 }
4533
4534 unsigned GEPWidth =
4535 BaseType->isVectorTy()
4536 ? cast<FixedVectorType>(BaseType)->getNumElements()
4537 : 0;
4538
4539 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4540 for (Constant *Val : Indices) {
4541 Type *ValTy = Val->getType();
4542 if (!ValTy->isIntOrIntVectorTy())
4543 return error(ID.Loc, "getelementptr index must be an integer");
4544 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4545 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4546 if (GEPWidth && (ValNumEl != GEPWidth))
4547 return error(
4548 ID.Loc,
4549 "getelementptr vector index has a wrong number of elements");
4550 // GEPWidth may have been unknown because the base is a scalar,
4551 // but it is known now.
4552 GEPWidth = ValNumEl;
4553 }
4554 }
4555
4556 SmallPtrSet<Type*, 4> Visited;
4557 if (!Indices.empty() && !Ty->isSized(&Visited))
4558 return error(ID.Loc, "base element of getelementptr must be sized");
4559
4561 return error(ID.Loc, "invalid base element for constant getelementptr");
4562
4563 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4564 return error(ID.Loc, "invalid getelementptr indices");
4565
4566 ID.ConstantVal =
4567 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4568 } else if (Opc == Instruction::ShuffleVector) {
4569 if (Elts.size() != 3)
4570 return error(ID.Loc, "expected three operands to shufflevector");
4571 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4572 return error(ID.Loc, "invalid operands to shufflevector");
4573 SmallVector<int, 16> Mask;
4575 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4576 } else if (Opc == Instruction::ExtractElement) {
4577 if (Elts.size() != 2)
4578 return error(ID.Loc, "expected two operands to extractelement");
4579 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4580 return error(ID.Loc, "invalid extractelement operands");
4581 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4582 } else {
4583 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4584 if (Elts.size() != 3)
4585 return error(ID.Loc, "expected three operands to insertelement");
4586 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4587 return error(ID.Loc, "invalid insertelement operands");
4588 ID.ConstantVal =
4589 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4590 }
4591
4592 ID.Kind = ValID::t_Constant;
4593 return false;
4594 }
4595 }
4596
4597 Lex.Lex();
4598 return false;
4599}
4600
4601/// parseGlobalValue - parse a global value with the specified type.
4602bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4603 C = nullptr;
4604 ValID ID;
4605 Value *V = nullptr;
4606 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4607 convertValIDToValue(Ty, ID, V, nullptr);
4608 if (V && !(C = dyn_cast<Constant>(V)))
4609 return error(ID.Loc, "global values must be constants");
4610 return Parsed;
4611}
4612
4613bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4614 Type *Ty = nullptr;
4615 return parseType(Ty) || parseGlobalValue(Ty, V);
4616}
4617
4618bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4619 C = nullptr;
4620
4621 LocTy KwLoc = Lex.getLoc();
4622 if (!EatIfPresent(lltok::kw_comdat))
4623 return false;
4624
4625 if (EatIfPresent(lltok::lparen)) {
4626 if (Lex.getKind() != lltok::ComdatVar)
4627 return tokError("expected comdat variable");
4628 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4629 Lex.Lex();
4630 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4631 return true;
4632 } else {
4633 if (GlobalName.empty())
4634 return tokError("comdat cannot be unnamed");
4635 C = getComdat(std::string(GlobalName), KwLoc);
4636 }
4637
4638 return false;
4639}
4640
4641/// parseGlobalValueVector
4642/// ::= /*empty*/
4643/// ::= TypeAndValue (',' TypeAndValue)*
4644bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4645 // Empty list.
4646 if (Lex.getKind() == lltok::rbrace ||
4647 Lex.getKind() == lltok::rsquare ||
4648 Lex.getKind() == lltok::greater ||
4649 Lex.getKind() == lltok::rparen)
4650 return false;
4651
4652 do {
4653 // Let the caller deal with inrange.
4654 if (Lex.getKind() == lltok::kw_inrange)
4655 return false;
4656
4657 Constant *C;
4658 if (parseGlobalTypeAndValue(C))
4659 return true;
4660 Elts.push_back(C);
4661 } while (EatIfPresent(lltok::comma));
4662
4663 return false;
4664}
4665
4666bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4668 if (parseMDNodeVector(Elts))
4669 return true;
4670
4671 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4672 return false;
4673}
4674
4675/// MDNode:
4676/// ::= !{ ... }
4677/// ::= !7
4678/// ::= !DILocation(...)
4679bool LLParser::parseMDNode(MDNode *&N) {
4680 if (Lex.getKind() == lltok::MetadataVar)
4681 return parseSpecializedMDNode(N);
4682
4683 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4684}
4685
4686bool LLParser::parseMDNodeTail(MDNode *&N) {
4687 // !{ ... }
4688 if (Lex.getKind() == lltok::lbrace)
4689 return parseMDTuple(N);
4690
4691 // !42
4692 return parseMDNodeID(N);
4693}
4694
4695namespace {
4696
4697/// Structure to represent an optional metadata field.
4698template <class FieldTy> struct MDFieldImpl {
4699 typedef MDFieldImpl ImplTy;
4700 FieldTy Val;
4701 bool Seen;
4702
4703 void assign(FieldTy Val) {
4704 Seen = true;
4705 this->Val = std::move(Val);
4706 }
4707
4708 explicit MDFieldImpl(FieldTy Default)
4709 : Val(std::move(Default)), Seen(false) {}
4710};
4711
4712/// Structure to represent an optional metadata field that
4713/// can be of either type (A or B) and encapsulates the
4714/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4715/// to reimplement the specifics for representing each Field.
4716template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4717 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4718 FieldTypeA A;
4719 FieldTypeB B;
4720 bool Seen;
4721
4722 enum {
4723 IsInvalid = 0,
4724 IsTypeA = 1,
4725 IsTypeB = 2
4726 } WhatIs;
4727
4728 void assign(FieldTypeA A) {
4729 Seen = true;
4730 this->A = std::move(A);
4731 WhatIs = IsTypeA;
4732 }
4733
4734 void assign(FieldTypeB B) {
4735 Seen = true;
4736 this->B = std::move(B);
4737 WhatIs = IsTypeB;
4738 }
4739
4740 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4741 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4742 WhatIs(IsInvalid) {}
4743};
4744
4745struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4746 uint64_t Max;
4747
4748 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4749 : ImplTy(Default), Max(Max) {}
4750};
4751
4752struct LineField : public MDUnsignedField {
4753 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4754};
4755
4756struct ColumnField : public MDUnsignedField {
4757 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4758};
4759
4760struct DwarfTagField : public MDUnsignedField {
4761 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4762 DwarfTagField(dwarf::Tag DefaultTag)
4763 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4764};
4765
4766struct DwarfMacinfoTypeField : public MDUnsignedField {
4767 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4768 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4769 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4770};
4771
4772struct DwarfAttEncodingField : public MDUnsignedField {
4773 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4774};
4775
4776struct DwarfVirtualityField : public MDUnsignedField {
4777 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4778};
4779
4780struct DwarfLangField : public MDUnsignedField {
4781 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4782};
4783
4784struct DwarfSourceLangNameField : public MDUnsignedField {
4785 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4786};
4787
4788struct DwarfCCField : public MDUnsignedField {
4789 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4790};
4791
4792struct DwarfEnumKindField : public MDUnsignedField {
4793 DwarfEnumKindField()
4794 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4795 dwarf::DW_APPLE_ENUM_KIND_max) {}
4796};
4797
4798struct EmissionKindField : public MDUnsignedField {
4799 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4800};
4801
4802struct FixedPointKindField : public MDUnsignedField {
4803 FixedPointKindField()
4804 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4805};
4806
4807struct NameTableKindField : public MDUnsignedField {
4808 NameTableKindField()
4809 : MDUnsignedField(
4810 0, (unsigned)
4811 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4812};
4813
4814struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4815 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4816};
4817
4818struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4819 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4820};
4821
4822struct MDAPSIntField : public MDFieldImpl<APSInt> {
4823 MDAPSIntField() : ImplTy(APSInt()) {}
4824};
4825
4826struct MDSignedField : public MDFieldImpl<int64_t> {
4827 int64_t Min = INT64_MIN;
4828 int64_t Max = INT64_MAX;
4829
4830 MDSignedField(int64_t Default = 0)
4831 : ImplTy(Default) {}
4832 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4833 : ImplTy(Default), Min(Min), Max(Max) {}
4834};
4835
4836struct MDBoolField : public MDFieldImpl<bool> {
4837 MDBoolField(bool Default = false) : ImplTy(Default) {}
4838};
4839
4840struct MDField : public MDFieldImpl<Metadata *> {
4841 bool AllowNull;
4842
4843 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4844};
4845
4846struct MDStringField : public MDFieldImpl<MDString *> {
4847 enum class EmptyIs {
4848 Null, //< Allow empty input string, map to nullptr
4849 Empty, //< Allow empty input string, map to an empty MDString
4850 Error, //< Disallow empty string, map to an error
4851 } EmptyIs;
4852 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4853 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4854};
4855
4856struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4857 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4858};
4859
4860struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4861 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4862};
4863
4864struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4865 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4866 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4867
4868 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4869 bool AllowNull = true)
4870 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4871
4872 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4873 bool isMDField() const { return WhatIs == IsTypeB; }
4874 int64_t getMDSignedValue() const {
4875 assert(isMDSignedField() && "Wrong field type");
4876 return A.Val;
4877 }
4878 Metadata *getMDFieldValue() const {
4879 assert(isMDField() && "Wrong field type");
4880 return B.Val;
4881 }
4882};
4883
4884struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4885 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4886 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4887
4888 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4889 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4890
4891 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4892 bool isMDField() const { return WhatIs == IsTypeB; }
4893 uint64_t getMDUnsignedValue() const {
4894 assert(isMDUnsignedField() && "Wrong field type");
4895 return A.Val;
4896 }
4897 Metadata *getMDFieldValue() const {
4898 assert(isMDField() && "Wrong field type");
4899 return B.Val;
4900 }
4901
4902 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4903 if (isMDUnsignedField())
4905 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4906 if (isMDField())
4907 return getMDFieldValue();
4908 return nullptr;
4909 }
4910};
4911
4912} // end anonymous namespace
4913
4914namespace llvm {
4915
4916template <>
4917bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4918 if (Lex.getKind() != lltok::APSInt)
4919 return tokError("expected integer");
4920
4921 Result.assign(Lex.getAPSIntVal());
4922 Lex.Lex();
4923 return false;
4924}
4925
4926template <>
4927bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4928 MDUnsignedField &Result) {
4929 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4930 return tokError("expected unsigned integer");
4931
4932 auto &U = Lex.getAPSIntVal();
4933 if (U.ugt(Result.Max))
4934 return tokError("value for '" + Name + "' too large, limit is " +
4935 Twine(Result.Max));
4936 Result.assign(U.getZExtValue());
4937 assert(Result.Val <= Result.Max && "Expected value in range");
4938 Lex.Lex();
4939 return false;
4940}
4941
4942template <>
4943bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4944 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4945}
4946template <>
4947bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4948 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4949}
4950
4951template <>
4952bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4953 if (Lex.getKind() == lltok::APSInt)
4954 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4955
4956 if (Lex.getKind() != lltok::DwarfTag)
4957 return tokError("expected DWARF tag");
4958
4959 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4961 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4962 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4963
4964 Result.assign(Tag);
4965 Lex.Lex();
4966 return false;
4967}
4968
4969template <>
4970bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4971 DwarfMacinfoTypeField &Result) {
4972 if (Lex.getKind() == lltok::APSInt)
4973 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4974
4975 if (Lex.getKind() != lltok::DwarfMacinfo)
4976 return tokError("expected DWARF macinfo type");
4977
4978 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4979 if (Macinfo == dwarf::DW_MACINFO_invalid)
4980 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4981 Lex.getStrVal() + "'");
4982 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4983
4984 Result.assign(Macinfo);
4985 Lex.Lex();
4986 return false;
4987}
4988
4989template <>
4990bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4991 DwarfVirtualityField &Result) {
4992 if (Lex.getKind() == lltok::APSInt)
4993 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4994
4995 if (Lex.getKind() != lltok::DwarfVirtuality)
4996 return tokError("expected DWARF virtuality code");
4997
4998 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4999 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5000 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5001 Lex.getStrVal() + "'");
5002 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5003 Result.assign(Virtuality);
5004 Lex.Lex();
5005 return false;
5006}
5007
5008template <>
5009bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5010 DwarfEnumKindField &Result) {
5011 if (Lex.getKind() == lltok::APSInt)
5012 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5013
5014 if (Lex.getKind() != lltok::DwarfEnumKind)
5015 return tokError("expected DWARF enum kind code");
5016
5017 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5018 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5019 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5020 Lex.getStrVal() + "'");
5021 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5022 Result.assign(EnumKind);
5023 Lex.Lex();
5024 return false;
5025}
5026
5027template <>
5028bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5029 if (Lex.getKind() == lltok::APSInt)
5030 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5031
5032 if (Lex.getKind() != lltok::DwarfLang)
5033 return tokError("expected DWARF language");
5034
5035 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5036 if (!Lang)
5037 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5038 "'");
5039 assert(Lang <= Result.Max && "Expected valid DWARF language");
5040 Result.assign(Lang);
5041 Lex.Lex();
5042 return false;
5043}
5044
5045template <>
5046bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5047 DwarfSourceLangNameField &Result) {
5048 if (Lex.getKind() == lltok::APSInt)
5049 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5050
5051 if (Lex.getKind() != lltok::DwarfSourceLangName)
5052 return tokError("expected DWARF source language name");
5053
5054 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5055 if (!Lang)
5056 return tokError("invalid DWARF source language name" + Twine(" '") +
5057 Lex.getStrVal() + "'");
5058 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5059 Result.assign(Lang);
5060 Lex.Lex();
5061 return false;
5062}
5063
5064template <>
5065bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5066 if (Lex.getKind() == lltok::APSInt)
5067 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5068
5069 if (Lex.getKind() != lltok::DwarfCC)
5070 return tokError("expected DWARF calling convention");
5071
5072 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5073 if (!CC)
5074 return tokError("invalid DWARF calling convention" + Twine(" '") +
5075 Lex.getStrVal() + "'");
5076 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5077 Result.assign(CC);
5078 Lex.Lex();
5079 return false;
5080}
5081
5082template <>
5083bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5084 EmissionKindField &Result) {
5085 if (Lex.getKind() == lltok::APSInt)
5086 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5087
5088 if (Lex.getKind() != lltok::EmissionKind)
5089 return tokError("expected emission kind");
5090
5091 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5092 if (!Kind)
5093 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5094 "'");
5095 assert(*Kind <= Result.Max && "Expected valid emission kind");
5096 Result.assign(*Kind);
5097 Lex.Lex();
5098 return false;
5099}
5100
5101template <>
5102bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5103 FixedPointKindField &Result) {
5104 if (Lex.getKind() == lltok::APSInt)
5105 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5106
5107 if (Lex.getKind() != lltok::FixedPointKind)
5108 return tokError("expected fixed-point kind");
5109
5110 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5111 if (!Kind)
5112 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5113 "'");
5114 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5115 Result.assign(*Kind);
5116 Lex.Lex();
5117 return false;
5118}
5119
5120template <>
5121bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5122 NameTableKindField &Result) {
5123 if (Lex.getKind() == lltok::APSInt)
5124 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5125
5126 if (Lex.getKind() != lltok::NameTableKind)
5127 return tokError("expected nameTable kind");
5128
5129 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5130 if (!Kind)
5131 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5132 "'");
5133 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5134 Result.assign((unsigned)*Kind);
5135 Lex.Lex();
5136 return false;
5137}
5138
5139template <>
5140bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5141 DwarfAttEncodingField &Result) {
5142 if (Lex.getKind() == lltok::APSInt)
5143 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5144
5145 if (Lex.getKind() != lltok::DwarfAttEncoding)
5146 return tokError("expected DWARF type attribute encoding");
5147
5148 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5149 if (!Encoding)
5150 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5151 Lex.getStrVal() + "'");
5152 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5153 Result.assign(Encoding);
5154 Lex.Lex();
5155 return false;
5156}
5157
5158/// DIFlagField
5159/// ::= uint32
5160/// ::= DIFlagVector
5161/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5162template <>
5163bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5164
5165 // parser for a single flag.
5166 auto parseFlag = [&](DINode::DIFlags &Val) {
5167 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5168 uint32_t TempVal = static_cast<uint32_t>(Val);
5169 bool Res = parseUInt32(TempVal);
5170 Val = static_cast<DINode::DIFlags>(TempVal);
5171 return Res;
5172 }
5173
5174 if (Lex.getKind() != lltok::DIFlag)
5175 return tokError("expected debug info flag");
5176
5177 Val = DINode::getFlag(Lex.getStrVal());
5178 if (!Val)
5179 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5180 "'");
5181 Lex.Lex();
5182 return false;
5183 };
5184
5185 // parse the flags and combine them together.
5186 DINode::DIFlags Combined = DINode::FlagZero;
5187 do {
5188 DINode::DIFlags Val;
5189 if (parseFlag(Val))
5190 return true;
5191 Combined |= Val;
5192 } while (EatIfPresent(lltok::bar));
5193
5194 Result.assign(Combined);
5195 return false;
5196}
5197
5198/// DISPFlagField
5199/// ::= uint32
5200/// ::= DISPFlagVector
5201/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5202template <>
5203bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5204
5205 // parser for a single flag.
5206 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5207 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5208 uint32_t TempVal = static_cast<uint32_t>(Val);
5209 bool Res = parseUInt32(TempVal);
5210 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5211 return Res;
5212 }
5213
5214 if (Lex.getKind() != lltok::DISPFlag)
5215 return tokError("expected debug info flag");
5216
5217 Val = DISubprogram::getFlag(Lex.getStrVal());
5218 if (!Val)
5219 return tokError(Twine("invalid subprogram debug info flag '") +
5220 Lex.getStrVal() + "'");
5221 Lex.Lex();
5222 return false;
5223 };
5224
5225 // parse the flags and combine them together.
5226 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5227 do {
5229 if (parseFlag(Val))
5230 return true;
5231 Combined |= Val;
5232 } while (EatIfPresent(lltok::bar));
5233
5234 Result.assign(Combined);
5235 return false;
5236}
5237
5238template <>
5239bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5240 if (Lex.getKind() != lltok::APSInt)
5241 return tokError("expected signed integer");
5242
5243 auto &S = Lex.getAPSIntVal();
5244 if (S < Result.Min)
5245 return tokError("value for '" + Name + "' too small, limit is " +
5246 Twine(Result.Min));
5247 if (S > Result.Max)
5248 return tokError("value for '" + Name + "' too large, limit is " +
5249 Twine(Result.Max));
5250 Result.assign(S.getExtValue());
5251 assert(Result.Val >= Result.Min && "Expected value in range");
5252 assert(Result.Val <= Result.Max && "Expected value in range");
5253 Lex.Lex();
5254 return false;
5255}
5256
5257template <>
5258bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5259 switch (Lex.getKind()) {
5260 default:
5261 return tokError("expected 'true' or 'false'");
5262 case lltok::kw_true:
5263 Result.assign(true);
5264 break;
5265 case lltok::kw_false:
5266 Result.assign(false);
5267 break;
5268 }
5269 Lex.Lex();
5270 return false;
5271}
5272
5273template <>
5274bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5275 if (Lex.getKind() == lltok::kw_null) {
5276 if (!Result.AllowNull)
5277 return tokError("'" + Name + "' cannot be null");
5278 Lex.Lex();
5279 Result.assign(nullptr);
5280 return false;
5281 }
5282
5283 Metadata *MD;
5284 if (parseMetadata(MD, nullptr))
5285 return true;
5286
5287 Result.assign(MD);
5288 return false;
5289}
5290
5291template <>
5292bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5293 MDSignedOrMDField &Result) {
5294 // Try to parse a signed int.
5295 if (Lex.getKind() == lltok::APSInt) {
5296 MDSignedField Res = Result.A;
5297 if (!parseMDField(Loc, Name, Res)) {
5298 Result.assign(Res);
5299 return false;
5300 }
5301 return true;
5302 }
5303
5304 // Otherwise, try to parse as an MDField.
5305 MDField Res = Result.B;
5306 if (!parseMDField(Loc, Name, Res)) {
5307 Result.assign(Res);
5308 return false;
5309 }
5310
5311 return true;
5312}
5313
5314template <>
5315bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5316 MDUnsignedOrMDField &Result) {
5317 // Try to parse an unsigned int.
5318 if (Lex.getKind() == lltok::APSInt) {
5319 MDUnsignedField Res = Result.A;
5320 if (!parseMDField(Loc, Name, Res)) {
5321 Result.assign(Res);
5322 return false;
5323 }
5324 return true;
5325 }
5326
5327 // Otherwise, try to parse as an MDField.
5328 MDField Res = Result.B;
5329 if (!parseMDField(Loc, Name, Res)) {
5330 Result.assign(Res);
5331 return false;
5332 }
5333
5334 return true;
5335}
5336
5337template <>
5338bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5339 LocTy ValueLoc = Lex.getLoc();
5340 std::string S;
5341 if (parseStringConstant(S))
5342 return true;
5343
5344 if (S.empty()) {
5345 switch (Result.EmptyIs) {
5346 case MDStringField::EmptyIs::Null:
5347 Result.assign(nullptr);
5348 return false;
5349 case MDStringField::EmptyIs::Empty:
5350 break;
5351 case MDStringField::EmptyIs::Error:
5352 return error(ValueLoc, "'" + Name + "' cannot be empty");
5353 }
5354 }
5355
5356 Result.assign(MDString::get(Context, S));
5357 return false;
5358}
5359
5360template <>
5361bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5363 if (parseMDNodeVector(MDs))
5364 return true;
5365
5366 Result.assign(std::move(MDs));
5367 return false;
5368}
5369
5370template <>
5371bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5372 ChecksumKindField &Result) {
5373 std::optional<DIFile::ChecksumKind> CSKind =
5374 DIFile::getChecksumKind(Lex.getStrVal());
5375
5376 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5377 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5378 "'");
5379
5380 Result.assign(*CSKind);
5381 Lex.Lex();
5382 return false;
5383}
5384
5385} // end namespace llvm
5386
5387template <class ParserTy>
5388bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5389 do {
5390 if (Lex.getKind() != lltok::LabelStr)
5391 return tokError("expected field label here");
5392
5393 if (ParseField())
5394 return true;
5395 } while (EatIfPresent(lltok::comma));
5396
5397 return false;
5398}
5399
5400template <class ParserTy>
5401bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5402 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5403 Lex.Lex();
5404
5405 if (parseToken(lltok::lparen, "expected '(' here"))
5406 return true;
5407 if (Lex.getKind() != lltok::rparen)
5408 if (parseMDFieldsImplBody(ParseField))
5409 return true;
5410
5411 ClosingLoc = Lex.getLoc();
5412 return parseToken(lltok::rparen, "expected ')' here");
5413}
5414
5415template <class FieldTy>
5416bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5417 if (Result.Seen)
5418 return tokError("field '" + Name + "' cannot be specified more than once");
5419
5420 LocTy Loc = Lex.getLoc();
5421 Lex.Lex();
5422 return parseMDField(Loc, Name, Result);
5423}
5424
5425bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5426 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5427
5428#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5429 if (Lex.getStrVal() == #CLASS) \
5430 return parse##CLASS(N, IsDistinct);
5431#include "llvm/IR/Metadata.def"
5432
5433 return tokError("expected metadata type");
5434}
5435
5436#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5437#define NOP_FIELD(NAME, TYPE, INIT)
5438#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5439 if (!NAME.Seen) \
5440 return error(ClosingLoc, "missing required field '" #NAME "'");
5441#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5442 if (Lex.getStrVal() == #NAME) \
5443 return parseMDField(#NAME, NAME);
5444#define PARSE_MD_FIELDS() \
5445 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5446 do { \
5447 LocTy ClosingLoc; \
5448 if (parseMDFieldsImpl( \
5449 [&]() -> bool { \
5450 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5451 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5452 "'"); \
5453 }, \
5454 ClosingLoc)) \
5455 return true; \
5456 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5457 } while (false)
5458#define GET_OR_DISTINCT(CLASS, ARGS) \
5459 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5460
5461/// parseDILocationFields:
5462/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5463/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5464bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5465#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5466 OPTIONAL(line, LineField, ); \
5467 OPTIONAL(column, ColumnField, ); \
5468 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5469 OPTIONAL(inlinedAt, MDField, ); \
5470 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5471 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5472 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5474#undef VISIT_MD_FIELDS
5475
5476 Result = GET_OR_DISTINCT(
5477 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5478 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5479 return false;
5480}
5481
5482/// parseDIAssignID:
5483/// ::= distinct !DIAssignID()
5484bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5485 if (!IsDistinct)
5486 return tokError("missing 'distinct', required for !DIAssignID()");
5487
5488 Lex.Lex();
5489
5490 // Now eat the parens.
5491 if (parseToken(lltok::lparen, "expected '(' here"))
5492 return true;
5493 if (parseToken(lltok::rparen, "expected ')' here"))
5494 return true;
5495
5497 return false;
5498}
5499
5500/// parseGenericDINode:
5501/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5502bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5503#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5504 REQUIRED(tag, DwarfTagField, ); \
5505 OPTIONAL(header, MDStringField, ); \
5506 OPTIONAL(operands, MDFieldList, );
5508#undef VISIT_MD_FIELDS
5509
5510 Result = GET_OR_DISTINCT(GenericDINode,
5511 (Context, tag.Val, header.Val, operands.Val));
5512 return false;
5513}
5514
5515/// parseDISubrangeType:
5516/// ::= !DISubrangeType(name: "whatever", file: !0,
5517/// line: 7, scope: !1, baseType: !2, size: 32,
5518/// align: 32, flags: 0, lowerBound: !3
5519/// upperBound: !4, stride: !5, bias: !6)
5520bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5521#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5522 OPTIONAL(name, MDStringField, ); \
5523 OPTIONAL(file, MDField, ); \
5524 OPTIONAL(line, LineField, ); \
5525 OPTIONAL(scope, MDField, ); \
5526 OPTIONAL(baseType, MDField, ); \
5527 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5528 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5529 OPTIONAL(flags, DIFlagField, ); \
5530 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5531 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5532 OPTIONAL(stride, MDSignedOrMDField, ); \
5533 OPTIONAL(bias, MDSignedOrMDField, );
5535#undef VISIT_MD_FIELDS
5536
5537 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5538 if (Bound.isMDSignedField())
5540 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5541 if (Bound.isMDField())
5542 return Bound.getMDFieldValue();
5543 return nullptr;
5544 };
5545
5546 Metadata *LowerBound = convToMetadata(lowerBound);
5547 Metadata *UpperBound = convToMetadata(upperBound);
5548 Metadata *Stride = convToMetadata(stride);
5549 Metadata *Bias = convToMetadata(bias);
5550
5552 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5553 size.getValueAsMetadata(Context), align.Val, flags.Val,
5554 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5555
5556 return false;
5557}
5558
5559/// parseDISubrange:
5560/// ::= !DISubrange(count: 30, lowerBound: 2)
5561/// ::= !DISubrange(count: !node, lowerBound: 2)
5562/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5563bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5564#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5565 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5566 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5567 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5568 OPTIONAL(stride, MDSignedOrMDField, );
5570#undef VISIT_MD_FIELDS
5571
5572 Metadata *Count = nullptr;
5573 Metadata *LowerBound = nullptr;
5574 Metadata *UpperBound = nullptr;
5575 Metadata *Stride = nullptr;
5576
5577 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5578 if (Bound.isMDSignedField())
5580 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5581 if (Bound.isMDField())
5582 return Bound.getMDFieldValue();
5583 return nullptr;
5584 };
5585
5586 Count = convToMetadata(count);
5587 LowerBound = convToMetadata(lowerBound);
5588 UpperBound = convToMetadata(upperBound);
5589 Stride = convToMetadata(stride);
5590
5591 Result = GET_OR_DISTINCT(DISubrange,
5592 (Context, Count, LowerBound, UpperBound, Stride));
5593
5594 return false;
5595}
5596
5597/// parseDIGenericSubrange:
5598/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5599/// !node3)
5600bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5601#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5602 OPTIONAL(count, MDSignedOrMDField, ); \
5603 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5604 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5605 OPTIONAL(stride, MDSignedOrMDField, );
5607#undef VISIT_MD_FIELDS
5608
5609 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5610 if (Bound.isMDSignedField())
5611 return DIExpression::get(
5612 Context, {dwarf::DW_OP_consts,
5613 static_cast<uint64_t>(Bound.getMDSignedValue())});
5614 if (Bound.isMDField())
5615 return Bound.getMDFieldValue();
5616 return nullptr;
5617 };
5618
5619 Metadata *Count = ConvToMetadata(count);
5620 Metadata *LowerBound = ConvToMetadata(lowerBound);
5621 Metadata *UpperBound = ConvToMetadata(upperBound);
5622 Metadata *Stride = ConvToMetadata(stride);
5623
5624 Result = GET_OR_DISTINCT(DIGenericSubrange,
5625 (Context, Count, LowerBound, UpperBound, Stride));
5626
5627 return false;
5628}
5629
5630/// parseDIEnumerator:
5631/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5632bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5633#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5634 REQUIRED(name, MDStringField, ); \
5635 REQUIRED(value, MDAPSIntField, ); \
5636 OPTIONAL(isUnsigned, MDBoolField, (false));
5638#undef VISIT_MD_FIELDS
5639
5640 if (isUnsigned.Val && value.Val.isNegative())
5641 return tokError("unsigned enumerator with negative value");
5642
5643 APSInt Value(value.Val);
5644 // Add a leading zero so that unsigned values with the msb set are not
5645 // mistaken for negative values when used for signed enumerators.
5646 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5647 Value = Value.zext(Value.getBitWidth() + 1);
5648
5649 Result =
5650 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5651
5652 return false;
5653}
5654
5655/// parseDIBasicType:
5656/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5657/// encoding: DW_ATE_encoding, flags: 0)
5658bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5659#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5660 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5661 OPTIONAL(name, MDStringField, ); \
5662 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5663 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5664 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5665 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5666 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5667 OPTIONAL(flags, DIFlagField, );
5669#undef VISIT_MD_FIELDS
5670
5672 DIBasicType,
5673 (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val,
5674 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5675 return false;
5676}
5677
5678/// parseDIFixedPointType:
5679/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5680/// align: 32, encoding: DW_ATE_signed_fixed,
5681/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5682/// denominator: 8)
5683bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5684#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5685 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5686 OPTIONAL(name, MDStringField, ); \
5687 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5688 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5689 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5690 OPTIONAL(flags, DIFlagField, ); \
5691 OPTIONAL(kind, FixedPointKindField, ); \
5692 OPTIONAL(factor, MDSignedField, ); \
5693 OPTIONAL(numerator, MDAPSIntField, ); \
5694 OPTIONAL(denominator, MDAPSIntField, );
5696#undef VISIT_MD_FIELDS
5697
5698 Result = GET_OR_DISTINCT(DIFixedPointType,
5699 (Context, tag.Val, name.Val,
5700 size.getValueAsMetadata(Context), align.Val,
5701 encoding.Val, flags.Val, kind.Val, factor.Val,
5702 numerator.Val, denominator.Val));
5703 return false;
5704}
5705
5706/// parseDIStringType:
5707/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5708bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5709#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5710 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5711 OPTIONAL(name, MDStringField, ); \
5712 OPTIONAL(stringLength, MDField, ); \
5713 OPTIONAL(stringLengthExpression, MDField, ); \
5714 OPTIONAL(stringLocationExpression, MDField, ); \
5715 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5716 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5717 OPTIONAL(encoding, DwarfAttEncodingField, );
5719#undef VISIT_MD_FIELDS
5720
5722 DIStringType,
5723 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5724 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5725 align.Val, encoding.Val));
5726 return false;
5727}
5728
5729/// parseDIDerivedType:
5730/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5731/// line: 7, scope: !1, baseType: !2, size: 32,
5732/// align: 32, offset: 0, flags: 0, extraData: !3,
5733/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5734/// ptrAuthIsAddressDiscriminated: true,
5735/// ptrAuthExtraDiscriminator: 0x1234,
5736/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5737/// )
5738bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5739#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5740 REQUIRED(tag, DwarfTagField, ); \
5741 OPTIONAL(name, MDStringField, ); \
5742 OPTIONAL(file, MDField, ); \
5743 OPTIONAL(line, LineField, ); \
5744 OPTIONAL(scope, MDField, ); \
5745 REQUIRED(baseType, MDField, ); \
5746 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5747 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5748 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5749 OPTIONAL(flags, DIFlagField, ); \
5750 OPTIONAL(extraData, MDField, ); \
5751 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5752 OPTIONAL(annotations, MDField, ); \
5753 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5754 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5755 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5756 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5757 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5759#undef VISIT_MD_FIELDS
5760
5761 std::optional<unsigned> DWARFAddressSpace;
5762 if (dwarfAddressSpace.Val != UINT32_MAX)
5763 DWARFAddressSpace = dwarfAddressSpace.Val;
5764 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5765 if (ptrAuthKey.Val)
5766 PtrAuthData.emplace(
5767 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5768 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5769 ptrAuthAuthenticatesNullValues.Val);
5770
5772 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5773 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5774 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5775 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5776 return false;
5777}
5778
5779bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5780#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5781 REQUIRED(tag, DwarfTagField, ); \
5782 OPTIONAL(name, MDStringField, ); \
5783 OPTIONAL(file, MDField, ); \
5784 OPTIONAL(line, LineField, ); \
5785 OPTIONAL(scope, MDField, ); \
5786 OPTIONAL(baseType, MDField, ); \
5787 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5788 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5789 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5790 OPTIONAL(flags, DIFlagField, ); \
5791 OPTIONAL(elements, MDField, ); \
5792 OPTIONAL(runtimeLang, DwarfLangField, ); \
5793 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5794 OPTIONAL(vtableHolder, MDField, ); \
5795 OPTIONAL(templateParams, MDField, ); \
5796 OPTIONAL(identifier, MDStringField, ); \
5797 OPTIONAL(discriminator, MDField, ); \
5798 OPTIONAL(dataLocation, MDField, ); \
5799 OPTIONAL(associated, MDField, ); \
5800 OPTIONAL(allocated, MDField, ); \
5801 OPTIONAL(rank, MDSignedOrMDField, ); \
5802 OPTIONAL(annotations, MDField, ); \
5803 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5804 OPTIONAL(specification, MDField, ); \
5805 OPTIONAL(bitStride, MDField, );
5807#undef VISIT_MD_FIELDS
5808
5809 Metadata *Rank = nullptr;
5810 if (rank.isMDSignedField())
5812 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5813 else if (rank.isMDField())
5814 Rank = rank.getMDFieldValue();
5815
5816 std::optional<unsigned> EnumKind;
5817 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5818 EnumKind = enumKind.Val;
5819
5820 // If this has an identifier try to build an ODR type.
5821 if (identifier.Val)
5822 if (auto *CT = DICompositeType::buildODRType(
5823 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5824 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5825 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5826 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5827 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5828 dataLocation.Val, associated.Val, allocated.Val, Rank,
5829 annotations.Val, bitStride.Val)) {
5830 Result = CT;
5831 return false;
5832 }
5833
5834 // Create a new node, and save it in the context if it belongs in the type
5835 // map.
5837 DICompositeType,
5838 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5839 size.getValueAsMetadata(Context), align.Val,
5840 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5841 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5842 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5843 allocated.Val, Rank, annotations.Val, specification.Val,
5844 num_extra_inhabitants.Val, bitStride.Val));
5845 return false;
5846}
5847
5848bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5849#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5850 OPTIONAL(flags, DIFlagField, ); \
5851 OPTIONAL(cc, DwarfCCField, ); \
5852 REQUIRED(types, MDField, );
5854#undef VISIT_MD_FIELDS
5855
5856 Result = GET_OR_DISTINCT(DISubroutineType,
5857 (Context, flags.Val, cc.Val, types.Val));
5858 return false;
5859}
5860
5861/// parseDIFileType:
5862/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5863/// checksumkind: CSK_MD5,
5864/// checksum: "000102030405060708090a0b0c0d0e0f",
5865/// source: "source file contents")
5866bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5867 // The default constructed value for checksumkind is required, but will never
5868 // be used, as the parser checks if the field was actually Seen before using
5869 // the Val.
5870#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5871 REQUIRED(filename, MDStringField, ); \
5872 REQUIRED(directory, MDStringField, ); \
5873 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5874 OPTIONAL(checksum, MDStringField, ); \
5875 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5877#undef VISIT_MD_FIELDS
5878
5879 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5880 if (checksumkind.Seen && checksum.Seen)
5881 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5882 else if (checksumkind.Seen || checksum.Seen)
5883 return tokError("'checksumkind' and 'checksum' must be provided together");
5884
5885 MDString *Source = nullptr;
5886 if (source.Seen)
5887 Source = source.Val;
5889 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5890 return false;
5891}
5892
5893/// parseDICompileUnit:
5894/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5895/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5896/// splitDebugFilename: "abc.debug",
5897/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5898/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5899/// sysroot: "/", sdk: "MacOSX.sdk")
5900bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5901 if (!IsDistinct)
5902 return tokError("missing 'distinct', required for !DICompileUnit");
5903
5904 LocTy Loc = Lex.getLoc();
5905
5906#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5907 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5908 OPTIONAL(language, DwarfLangField, ); \
5909 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
5910 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
5911 OPTIONAL(producer, MDStringField, ); \
5912 OPTIONAL(isOptimized, MDBoolField, ); \
5913 OPTIONAL(flags, MDStringField, ); \
5914 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5915 OPTIONAL(splitDebugFilename, MDStringField, ); \
5916 OPTIONAL(emissionKind, EmissionKindField, ); \
5917 OPTIONAL(enums, MDField, ); \
5918 OPTIONAL(retainedTypes, MDField, ); \
5919 OPTIONAL(globals, MDField, ); \
5920 OPTIONAL(imports, MDField, ); \
5921 OPTIONAL(macros, MDField, ); \
5922 OPTIONAL(dwoId, MDUnsignedField, ); \
5923 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5924 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5925 OPTIONAL(nameTableKind, NameTableKindField, ); \
5926 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5927 OPTIONAL(sysroot, MDStringField, ); \
5928 OPTIONAL(sdk, MDStringField, );
5930#undef VISIT_MD_FIELDS
5931
5932 if (!language.Seen && !sourceLanguageName.Seen)
5933 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
5934 "required for !DICompileUnit");
5935
5936 if (language.Seen && sourceLanguageName.Seen)
5937 return error(Loc, "can only specify one of 'language' and "
5938 "'sourceLanguageName' on !DICompileUnit");
5939
5940 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
5941 return error(Loc, "'sourceLanguageVersion' requires an associated "
5942 "'sourceLanguageName' on !DICompileUnit");
5943
5945 Context,
5946 language.Seen ? DISourceLanguageName(language.Val)
5947 : DISourceLanguageName(sourceLanguageName.Val,
5948 sourceLanguageVersion.Val),
5949 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
5950 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
5951 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
5952 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
5953 sysroot.Val, sdk.Val);
5954 return false;
5955}
5956
5957/// parseDISubprogram:
5958/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5959/// file: !1, line: 7, type: !2, isLocal: false,
5960/// isDefinition: true, scopeLine: 8, containingType: !3,
5961/// virtuality: DW_VIRTUALTIY_pure_virtual,
5962/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5963/// spFlags: 10, isOptimized: false, templateParams: !4,
5964/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5965/// annotations: !8)
5966bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5967 auto Loc = Lex.getLoc();
5968#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5969 OPTIONAL(scope, MDField, ); \
5970 OPTIONAL(name, MDStringField, ); \
5971 OPTIONAL(linkageName, MDStringField, ); \
5972 OPTIONAL(file, MDField, ); \
5973 OPTIONAL(line, LineField, ); \
5974 OPTIONAL(type, MDField, ); \
5975 OPTIONAL(isLocal, MDBoolField, ); \
5976 OPTIONAL(isDefinition, MDBoolField, (true)); \
5977 OPTIONAL(scopeLine, LineField, ); \
5978 OPTIONAL(containingType, MDField, ); \
5979 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5980 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5981 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5982 OPTIONAL(flags, DIFlagField, ); \
5983 OPTIONAL(spFlags, DISPFlagField, ); \
5984 OPTIONAL(isOptimized, MDBoolField, ); \
5985 OPTIONAL(unit, MDField, ); \
5986 OPTIONAL(templateParams, MDField, ); \
5987 OPTIONAL(declaration, MDField, ); \
5988 OPTIONAL(retainedNodes, MDField, ); \
5989 OPTIONAL(thrownTypes, MDField, ); \
5990 OPTIONAL(annotations, MDField, ); \
5991 OPTIONAL(targetFuncName, MDStringField, ); \
5992 OPTIONAL(keyInstructions, MDBoolField, );
5994#undef VISIT_MD_FIELDS
5995
5996 // An explicit spFlags field takes precedence over individual fields in
5997 // older IR versions.
5998 DISubprogram::DISPFlags SPFlags =
5999 spFlags.Seen ? spFlags.Val
6000 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6001 isOptimized.Val, virtuality.Val);
6002 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6003 return error(
6004 Loc,
6005 "missing 'distinct', required for !DISubprogram that is a Definition");
6007 DISubprogram,
6008 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6009 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6010 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6011 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6012 targetFuncName.Val, keyInstructions.Val));
6013 return false;
6014}
6015
6016/// parseDILexicalBlock:
6017/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6018bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6019#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6020 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6021 OPTIONAL(file, MDField, ); \
6022 OPTIONAL(line, LineField, ); \
6023 OPTIONAL(column, ColumnField, );
6025#undef VISIT_MD_FIELDS
6026
6028 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6029 return false;
6030}
6031
6032/// parseDILexicalBlockFile:
6033/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6034bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6035#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6036 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6037 OPTIONAL(file, MDField, ); \
6038 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6040#undef VISIT_MD_FIELDS
6041
6042 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6043 (Context, scope.Val, file.Val, discriminator.Val));
6044 return false;
6045}
6046
6047/// parseDICommonBlock:
6048/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6049bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6050#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6051 REQUIRED(scope, MDField, ); \
6052 OPTIONAL(declaration, MDField, ); \
6053 OPTIONAL(name, MDStringField, ); \
6054 OPTIONAL(file, MDField, ); \
6055 OPTIONAL(line, LineField, );
6057#undef VISIT_MD_FIELDS
6058
6059 Result = GET_OR_DISTINCT(DICommonBlock,
6060 (Context, scope.Val, declaration.Val, name.Val,
6061 file.Val, line.Val));
6062 return false;
6063}
6064
6065/// parseDINamespace:
6066/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6067bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6068#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6069 REQUIRED(scope, MDField, ); \
6070 OPTIONAL(name, MDStringField, ); \
6071 OPTIONAL(exportSymbols, MDBoolField, );
6073#undef VISIT_MD_FIELDS
6074
6075 Result = GET_OR_DISTINCT(DINamespace,
6076 (Context, scope.Val, name.Val, exportSymbols.Val));
6077 return false;
6078}
6079
6080/// parseDIMacro:
6081/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6082/// "SomeValue")
6083bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6084#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6085 REQUIRED(type, DwarfMacinfoTypeField, ); \
6086 OPTIONAL(line, LineField, ); \
6087 REQUIRED(name, MDStringField, ); \
6088 OPTIONAL(value, MDStringField, );
6090#undef VISIT_MD_FIELDS
6091
6092 Result = GET_OR_DISTINCT(DIMacro,
6093 (Context, type.Val, line.Val, name.Val, value.Val));
6094 return false;
6095}
6096
6097/// parseDIMacroFile:
6098/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6099bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6100#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6101 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6102 OPTIONAL(line, LineField, ); \
6103 REQUIRED(file, MDField, ); \
6104 OPTIONAL(nodes, MDField, );
6106#undef VISIT_MD_FIELDS
6107
6108 Result = GET_OR_DISTINCT(DIMacroFile,
6109 (Context, type.Val, line.Val, file.Val, nodes.Val));
6110 return false;
6111}
6112
6113/// parseDIModule:
6114/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6115/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6116/// file: !1, line: 4, isDecl: false)
6117bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6118#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6119 REQUIRED(scope, MDField, ); \
6120 REQUIRED(name, MDStringField, ); \
6121 OPTIONAL(configMacros, MDStringField, ); \
6122 OPTIONAL(includePath, MDStringField, ); \
6123 OPTIONAL(apinotes, MDStringField, ); \
6124 OPTIONAL(file, MDField, ); \
6125 OPTIONAL(line, LineField, ); \
6126 OPTIONAL(isDecl, MDBoolField, );
6128#undef VISIT_MD_FIELDS
6129
6130 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6131 configMacros.Val, includePath.Val,
6132 apinotes.Val, line.Val, isDecl.Val));
6133 return false;
6134}
6135
6136/// parseDITemplateTypeParameter:
6137/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6138bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6139#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6140 OPTIONAL(name, MDStringField, ); \
6141 REQUIRED(type, MDField, ); \
6142 OPTIONAL(defaulted, MDBoolField, );
6144#undef VISIT_MD_FIELDS
6145
6146 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6147 (Context, name.Val, type.Val, defaulted.Val));
6148 return false;
6149}
6150
6151/// parseDITemplateValueParameter:
6152/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6153/// name: "V", type: !1, defaulted: false,
6154/// value: i32 7)
6155bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6156#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6157 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6158 OPTIONAL(name, MDStringField, ); \
6159 OPTIONAL(type, MDField, ); \
6160 OPTIONAL(defaulted, MDBoolField, ); \
6161 REQUIRED(value, MDField, );
6162
6164#undef VISIT_MD_FIELDS
6165
6167 DITemplateValueParameter,
6168 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6169 return false;
6170}
6171
6172/// parseDIGlobalVariable:
6173/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6174/// file: !1, line: 7, type: !2, isLocal: false,
6175/// isDefinition: true, templateParams: !3,
6176/// declaration: !4, align: 8)
6177bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6178#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6179 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6180 OPTIONAL(scope, MDField, ); \
6181 OPTIONAL(linkageName, MDStringField, ); \
6182 OPTIONAL(file, MDField, ); \
6183 OPTIONAL(line, LineField, ); \
6184 OPTIONAL(type, MDField, ); \
6185 OPTIONAL(isLocal, MDBoolField, ); \
6186 OPTIONAL(isDefinition, MDBoolField, (true)); \
6187 OPTIONAL(templateParams, MDField, ); \
6188 OPTIONAL(declaration, MDField, ); \
6189 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6190 OPTIONAL(annotations, MDField, );
6192#undef VISIT_MD_FIELDS
6193
6194 Result =
6195 GET_OR_DISTINCT(DIGlobalVariable,
6196 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6197 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6198 declaration.Val, templateParams.Val, align.Val,
6199 annotations.Val));
6200 return false;
6201}
6202
6203/// parseDILocalVariable:
6204/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6205/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6206/// align: 8)
6207/// ::= !DILocalVariable(scope: !0, name: "foo",
6208/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6209/// align: 8)
6210bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6211#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6212 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6213 OPTIONAL(name, MDStringField, ); \
6214 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6215 OPTIONAL(file, MDField, ); \
6216 OPTIONAL(line, LineField, ); \
6217 OPTIONAL(type, MDField, ); \
6218 OPTIONAL(flags, DIFlagField, ); \
6219 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6220 OPTIONAL(annotations, MDField, );
6222#undef VISIT_MD_FIELDS
6223
6224 Result = GET_OR_DISTINCT(DILocalVariable,
6225 (Context, scope.Val, name.Val, file.Val, line.Val,
6226 type.Val, arg.Val, flags.Val, align.Val,
6227 annotations.Val));
6228 return false;
6229}
6230
6231/// parseDILabel:
6232/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6233bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6234#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6235 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6236 REQUIRED(name, MDStringField, ); \
6237 REQUIRED(file, MDField, ); \
6238 REQUIRED(line, LineField, ); \
6239 OPTIONAL(column, ColumnField, ); \
6240 OPTIONAL(isArtificial, MDBoolField, ); \
6241 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6243#undef VISIT_MD_FIELDS
6244
6245 std::optional<unsigned> CoroSuspendIdx =
6246 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6247 : std::nullopt;
6248
6249 Result = GET_OR_DISTINCT(DILabel,
6250 (Context, scope.Val, name.Val, file.Val, line.Val,
6251 column.Val, isArtificial.Val, CoroSuspendIdx));
6252 return false;
6253}
6254
6255/// parseDIExpressionBody:
6256/// ::= (0, 7, -1)
6257bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6258 if (parseToken(lltok::lparen, "expected '(' here"))
6259 return true;
6260
6261 SmallVector<uint64_t, 8> Elements;
6262 if (Lex.getKind() != lltok::rparen)
6263 do {
6264 if (Lex.getKind() == lltok::DwarfOp) {
6265 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6266 Lex.Lex();
6267 Elements.push_back(Op);
6268 continue;
6269 }
6270 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6271 }
6272
6273 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6274 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6275 Lex.Lex();
6276 Elements.push_back(Op);
6277 continue;
6278 }
6279 return tokError(Twine("invalid DWARF attribute encoding '") +
6280 Lex.getStrVal() + "'");
6281 }
6282
6283 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6284 return tokError("expected unsigned integer");
6285
6286 auto &U = Lex.getAPSIntVal();
6287 if (U.ugt(UINT64_MAX))
6288 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6289 Elements.push_back(U.getZExtValue());
6290 Lex.Lex();
6291 } while (EatIfPresent(lltok::comma));
6292
6293 if (parseToken(lltok::rparen, "expected ')' here"))
6294 return true;
6295
6296 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6297 return false;
6298}
6299
6300/// parseDIExpression:
6301/// ::= !DIExpression(0, 7, -1)
6302bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6303 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6304 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6305 Lex.Lex();
6306
6307 return parseDIExpressionBody(Result, IsDistinct);
6308}
6309
6310/// ParseDIArgList:
6311/// ::= !DIArgList(i32 7, i64 %0)
6312bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6313 assert(PFS && "Expected valid function state");
6314 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6315 Lex.Lex();
6316
6317 if (parseToken(lltok::lparen, "expected '(' here"))
6318 return true;
6319
6321 if (Lex.getKind() != lltok::rparen)
6322 do {
6323 Metadata *MD;
6324 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6325 return true;
6326 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6327 } while (EatIfPresent(lltok::comma));
6328
6329 if (parseToken(lltok::rparen, "expected ')' here"))
6330 return true;
6331
6332 MD = DIArgList::get(Context, Args);
6333 return false;
6334}
6335
6336/// parseDIGlobalVariableExpression:
6337/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6338bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6339 bool IsDistinct) {
6340#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6341 REQUIRED(var, MDField, ); \
6342 REQUIRED(expr, MDField, );
6344#undef VISIT_MD_FIELDS
6345
6346 Result =
6347 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6348 return false;
6349}
6350
6351/// parseDIObjCProperty:
6352/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6353/// getter: "getFoo", attributes: 7, type: !2)
6354bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6355#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6356 OPTIONAL(name, MDStringField, ); \
6357 OPTIONAL(file, MDField, ); \
6358 OPTIONAL(line, LineField, ); \
6359 OPTIONAL(setter, MDStringField, ); \
6360 OPTIONAL(getter, MDStringField, ); \
6361 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6362 OPTIONAL(type, MDField, );
6364#undef VISIT_MD_FIELDS
6365
6366 Result = GET_OR_DISTINCT(DIObjCProperty,
6367 (Context, name.Val, file.Val, line.Val, getter.Val,
6368 setter.Val, attributes.Val, type.Val));
6369 return false;
6370}
6371
6372/// parseDIImportedEntity:
6373/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6374/// line: 7, name: "foo", elements: !2)
6375bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6376#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6377 REQUIRED(tag, DwarfTagField, ); \
6378 REQUIRED(scope, MDField, ); \
6379 OPTIONAL(entity, MDField, ); \
6380 OPTIONAL(file, MDField, ); \
6381 OPTIONAL(line, LineField, ); \
6382 OPTIONAL(name, MDStringField, ); \
6383 OPTIONAL(elements, MDField, );
6385#undef VISIT_MD_FIELDS
6386
6387 Result = GET_OR_DISTINCT(DIImportedEntity,
6388 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6389 line.Val, name.Val, elements.Val));
6390 return false;
6391}
6392
6393#undef PARSE_MD_FIELD
6394#undef NOP_FIELD
6395#undef REQUIRE_FIELD
6396#undef DECLARE_FIELD
6397
6398/// parseMetadataAsValue
6399/// ::= metadata i32 %local
6400/// ::= metadata i32 @global
6401/// ::= metadata i32 7
6402/// ::= metadata !0
6403/// ::= metadata !{...}
6404/// ::= metadata !"string"
6405bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6406 // Note: the type 'metadata' has already been parsed.
6407 Metadata *MD;
6408 if (parseMetadata(MD, &PFS))
6409 return true;
6410
6411 V = MetadataAsValue::get(Context, MD);
6412 return false;
6413}
6414
6415/// parseValueAsMetadata
6416/// ::= i32 %local
6417/// ::= i32 @global
6418/// ::= i32 7
6419bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6420 PerFunctionState *PFS) {
6421 Type *Ty;
6422 LocTy Loc;
6423 if (parseType(Ty, TypeMsg, Loc))
6424 return true;
6425 if (Ty->isMetadataTy())
6426 return error(Loc, "invalid metadata-value-metadata roundtrip");
6427
6428 Value *V;
6429 if (parseValue(Ty, V, PFS))
6430 return true;
6431
6432 MD = ValueAsMetadata::get(V);
6433 return false;
6434}
6435
6436/// parseMetadata
6437/// ::= i32 %local
6438/// ::= i32 @global
6439/// ::= i32 7
6440/// ::= !42
6441/// ::= !{...}
6442/// ::= !"string"
6443/// ::= !DILocation(...)
6444bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6445 if (Lex.getKind() == lltok::MetadataVar) {
6446 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6447 // so parsing this requires a Function State.
6448 if (Lex.getStrVal() == "DIArgList") {
6449 Metadata *AL;
6450 if (parseDIArgList(AL, PFS))
6451 return true;
6452 MD = AL;
6453 return false;
6454 }
6455 MDNode *N;
6456 if (parseSpecializedMDNode(N)) {
6457 return true;
6458 }
6459 MD = N;
6460 return false;
6461 }
6462
6463 // ValueAsMetadata:
6464 // <type> <value>
6465 if (Lex.getKind() != lltok::exclaim)
6466 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6467
6468 // '!'.
6469 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6470 Lex.Lex();
6471
6472 // MDString:
6473 // ::= '!' STRINGCONSTANT
6474 if (Lex.getKind() == lltok::StringConstant) {
6475 MDString *S;
6476 if (parseMDString(S))
6477 return true;
6478 MD = S;
6479 return false;
6480 }
6481
6482 // MDNode:
6483 // !{ ... }
6484 // !7
6485 MDNode *N;
6486 if (parseMDNodeTail(N))
6487 return true;
6488 MD = N;
6489 return false;
6490}
6491
6492//===----------------------------------------------------------------------===//
6493// Function Parsing.
6494//===----------------------------------------------------------------------===//
6495
6496bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6497 PerFunctionState *PFS) {
6498 if (Ty->isFunctionTy())
6499 return error(ID.Loc, "functions are not values, refer to them as pointers");
6500
6501 switch (ID.Kind) {
6502 case ValID::t_LocalID:
6503 if (!PFS)
6504 return error(ID.Loc, "invalid use of function-local name");
6505 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6506 return V == nullptr;
6507 case ValID::t_LocalName:
6508 if (!PFS)
6509 return error(ID.Loc, "invalid use of function-local name");
6510 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6511 return V == nullptr;
6512 case ValID::t_InlineAsm: {
6513 if (!ID.FTy)
6514 return error(ID.Loc, "invalid type for inline asm constraint string");
6515 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6516 return error(ID.Loc, toString(std::move(Err)));
6517 V = InlineAsm::get(
6518 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6519 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6520 return false;
6521 }
6523 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6524 if (V && ID.NoCFI)
6526 return V == nullptr;
6527 case ValID::t_GlobalID:
6528 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6529 if (V && ID.NoCFI)
6531 return V == nullptr;
6532 case ValID::t_APSInt:
6533 if (!Ty->isIntegerTy())
6534 return error(ID.Loc, "integer constant must have integer type");
6535 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6536 V = ConstantInt::get(Context, ID.APSIntVal);
6537 return false;
6538 case ValID::t_APFloat:
6539 if (!Ty->isFloatingPointTy() ||
6540 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6541 return error(ID.Loc, "floating point constant invalid for type");
6542
6543 // The lexer has no type info, so builds all half, bfloat, float, and double
6544 // FP constants as double. Fix this here. Long double does not need this.
6545 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6546 // Check for signaling before potentially converting and losing that info.
6547 bool IsSNAN = ID.APFloatVal.isSignaling();
6548 bool Ignored;
6549 if (Ty->isHalfTy())
6551 &Ignored);
6552 else if (Ty->isBFloatTy())
6553 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6554 &Ignored);
6555 else if (Ty->isFloatTy())
6557 &Ignored);
6558 if (IsSNAN) {
6559 // The convert call above may quiet an SNaN, so manufacture another
6560 // SNaN. The bitcast works because the payload (significand) parameter
6561 // is truncated to fit.
6562 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6563 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6564 ID.APFloatVal.isNegative(), &Payload);
6565 }
6566 }
6567 V = ConstantFP::get(Context, ID.APFloatVal);
6568
6569 if (V->getType() != Ty)
6570 return error(ID.Loc, "floating point constant does not have type '" +
6571 getTypeString(Ty) + "'");
6572
6573 return false;
6574 case ValID::t_Null:
6575 if (!Ty->isPointerTy())
6576 return error(ID.Loc, "null must be a pointer type");
6578 return false;
6579 case ValID::t_Undef:
6580 // FIXME: LabelTy should not be a first-class type.
6581 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6582 return error(ID.Loc, "invalid type for undef constant");
6583 V = UndefValue::get(Ty);
6584 return false;
6586 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6587 return error(ID.Loc, "invalid empty array initializer");
6588 V = PoisonValue::get(Ty);
6589 return false;
6590 case ValID::t_Zero:
6591 // FIXME: LabelTy should not be a first-class type.
6592 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6593 return error(ID.Loc, "invalid type for null constant");
6594 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6595 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6596 return error(ID.Loc, "invalid type for null constant");
6598 return false;
6599 case ValID::t_None:
6600 if (!Ty->isTokenTy())
6601 return error(ID.Loc, "invalid type for none constant");
6603 return false;
6604 case ValID::t_Poison:
6605 // FIXME: LabelTy should not be a first-class type.
6606 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6607 return error(ID.Loc, "invalid type for poison constant");
6608 V = PoisonValue::get(Ty);
6609 return false;
6610 case ValID::t_Constant:
6611 if (ID.ConstantVal->getType() != Ty)
6612 return error(ID.Loc, "constant expression type mismatch: got type '" +
6613 getTypeString(ID.ConstantVal->getType()) +
6614 "' but expected '" + getTypeString(Ty) + "'");
6615 V = ID.ConstantVal;
6616 return false;
6618 if (!Ty->isVectorTy())
6619 return error(ID.Loc, "vector constant must have vector type");
6620 if (ID.ConstantVal->getType() != Ty->getScalarType())
6621 return error(ID.Loc, "constant expression type mismatch: got type '" +
6622 getTypeString(ID.ConstantVal->getType()) +
6623 "' but expected '" +
6624 getTypeString(Ty->getScalarType()) + "'");
6625 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6626 ID.ConstantVal);
6627 return false;
6630 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6631 if (ST->getNumElements() != ID.UIntVal)
6632 return error(ID.Loc,
6633 "initializer with struct type has wrong # elements");
6634 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6635 return error(ID.Loc, "packed'ness of initializer and type don't match");
6636
6637 // Verify that the elements are compatible with the structtype.
6638 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6639 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6640 return error(
6641 ID.Loc,
6642 "element " + Twine(i) +
6643 " of struct initializer doesn't match struct element type");
6644
6646 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6647 } else
6648 return error(ID.Loc, "constant expression type mismatch");
6649 return false;
6650 }
6651 llvm_unreachable("Invalid ValID");
6652}
6653
6654bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6655 C = nullptr;
6656 ValID ID;
6657 auto Loc = Lex.getLoc();
6658 if (parseValID(ID, /*PFS=*/nullptr))
6659 return true;
6660 switch (ID.Kind) {
6661 case ValID::t_APSInt:
6662 case ValID::t_APFloat:
6663 case ValID::t_Undef:
6664 case ValID::t_Poison:
6665 case ValID::t_Zero:
6666 case ValID::t_Constant:
6670 Value *V;
6671 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6672 return true;
6673 assert(isa<Constant>(V) && "Expected a constant value");
6674 C = cast<Constant>(V);
6675 return false;
6676 }
6677 case ValID::t_Null:
6679 return false;
6680 default:
6681 return error(Loc, "expected a constant value");
6682 }
6683}
6684
6685bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6686 V = nullptr;
6687 ValID ID;
6688 return parseValID(ID, PFS, Ty) ||
6689 convertValIDToValue(Ty, ID, V, PFS);
6690}
6691
6692bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6693 Type *Ty = nullptr;
6694 return parseType(Ty) || parseValue(Ty, V, PFS);
6695}
6696
6697bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6698 PerFunctionState &PFS) {
6699 Value *V;
6700 Loc = Lex.getLoc();
6701 if (parseTypeAndValue(V, PFS))
6702 return true;
6703 if (!isa<BasicBlock>(V))
6704 return error(Loc, "expected a basic block");
6705 BB = cast<BasicBlock>(V);
6706 return false;
6707}
6708
6710 // Exit early for the common (non-debug-intrinsic) case.
6711 // We can make this the only check when we begin supporting all "llvm.dbg"
6712 // intrinsics in the new debug info format.
6713 if (!Name.starts_with("llvm.dbg."))
6714 return false;
6716 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6717 FnID == Intrinsic::dbg_assign;
6718}
6719
6720/// FunctionHeader
6721/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6722/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6723/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6724/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6725bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6726 unsigned &FunctionNumber,
6727 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6728 // parse the linkage.
6729 LocTy LinkageLoc = Lex.getLoc();
6730 unsigned Linkage;
6731 unsigned Visibility;
6732 unsigned DLLStorageClass;
6733 bool DSOLocal;
6734 AttrBuilder RetAttrs(M->getContext());
6735 unsigned CC;
6736 bool HasLinkage;
6737 Type *RetType = nullptr;
6738 LocTy RetTypeLoc = Lex.getLoc();
6739 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6740 DSOLocal) ||
6741 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6742 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6743 return true;
6744
6745 // Verify that the linkage is ok.
6748 break; // always ok.
6750 if (IsDefine)
6751 return error(LinkageLoc, "invalid linkage for function definition");
6752 break;
6760 if (!IsDefine)
6761 return error(LinkageLoc, "invalid linkage for function declaration");
6762 break;
6765 return error(LinkageLoc, "invalid function linkage type");
6766 }
6767
6768 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6769 return error(LinkageLoc,
6770 "symbol with local linkage must have default visibility");
6771
6772 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6773 return error(LinkageLoc,
6774 "symbol with local linkage cannot have a DLL storage class");
6775
6776 if (!FunctionType::isValidReturnType(RetType))
6777 return error(RetTypeLoc, "invalid function return type");
6778
6779 LocTy NameLoc = Lex.getLoc();
6780
6781 std::string FunctionName;
6782 if (Lex.getKind() == lltok::GlobalVar) {
6783 FunctionName = Lex.getStrVal();
6784 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6785 FunctionNumber = Lex.getUIntVal();
6786 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6787 FunctionNumber))
6788 return true;
6789 } else {
6790 return tokError("expected function name");
6791 }
6792
6793 Lex.Lex();
6794
6795 if (Lex.getKind() != lltok::lparen)
6796 return tokError("expected '(' in function argument list");
6797
6799 bool IsVarArg;
6800 AttrBuilder FuncAttrs(M->getContext());
6801 std::vector<unsigned> FwdRefAttrGrps;
6802 LocTy BuiltinLoc;
6803 std::string Section;
6804 std::string Partition;
6805 MaybeAlign Alignment;
6806 std::string GC;
6808 unsigned AddrSpace = 0;
6809 Constant *Prefix = nullptr;
6810 Constant *Prologue = nullptr;
6811 Constant *PersonalityFn = nullptr;
6812 Comdat *C;
6813
6814 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6815 parseOptionalUnnamedAddr(UnnamedAddr) ||
6816 parseOptionalProgramAddrSpace(AddrSpace) ||
6817 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6818 BuiltinLoc) ||
6819 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6820 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6821 parseOptionalComdat(FunctionName, C) ||
6822 parseOptionalAlignment(Alignment) ||
6823 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6824 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6825 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6826 (EatIfPresent(lltok::kw_personality) &&
6827 parseGlobalTypeAndValue(PersonalityFn)))
6828 return true;
6829
6830 if (FuncAttrs.contains(Attribute::Builtin))
6831 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6832
6833 // If the alignment was parsed as an attribute, move to the alignment field.
6834 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6835 Alignment = A;
6836 FuncAttrs.removeAttribute(Attribute::Alignment);
6837 }
6838
6839 // Okay, if we got here, the function is syntactically valid. Convert types
6840 // and do semantic checks.
6841 std::vector<Type*> ParamTypeList;
6843
6844 for (const ArgInfo &Arg : ArgList) {
6845 ParamTypeList.push_back(Arg.Ty);
6846 Attrs.push_back(Arg.Attrs);
6847 }
6848
6849 AttributeList PAL =
6850 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6851 AttributeSet::get(Context, RetAttrs), Attrs);
6852
6853 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6854 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6855
6856 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6857 PointerType *PFT = PointerType::get(Context, AddrSpace);
6858
6859 Fn = nullptr;
6860 GlobalValue *FwdFn = nullptr;
6861 if (!FunctionName.empty()) {
6862 // If this was a definition of a forward reference, remove the definition
6863 // from the forward reference table and fill in the forward ref.
6864 auto FRVI = ForwardRefVals.find(FunctionName);
6865 if (FRVI != ForwardRefVals.end()) {
6866 FwdFn = FRVI->second.first;
6867 if (FwdFn->getType() != PFT)
6868 return error(FRVI->second.second,
6869 "invalid forward reference to "
6870 "function '" +
6871 FunctionName +
6872 "' with wrong type: "
6873 "expected '" +
6874 getTypeString(PFT) + "' but was '" +
6875 getTypeString(FwdFn->getType()) + "'");
6876 ForwardRefVals.erase(FRVI);
6877 } else if ((Fn = M->getFunction(FunctionName))) {
6878 // Reject redefinitions.
6879 return error(NameLoc,
6880 "invalid redefinition of function '" + FunctionName + "'");
6881 } else if (M->getNamedValue(FunctionName)) {
6882 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6883 }
6884
6885 } else {
6886 // Handle @"", where a name is syntactically specified, but semantically
6887 // missing.
6888 if (FunctionNumber == (unsigned)-1)
6889 FunctionNumber = NumberedVals.getNext();
6890
6891 // If this is a definition of a forward referenced function, make sure the
6892 // types agree.
6893 auto I = ForwardRefValIDs.find(FunctionNumber);
6894 if (I != ForwardRefValIDs.end()) {
6895 FwdFn = I->second.first;
6896 if (FwdFn->getType() != PFT)
6897 return error(NameLoc, "type of definition and forward reference of '@" +
6898 Twine(FunctionNumber) +
6899 "' disagree: "
6900 "expected '" +
6901 getTypeString(PFT) + "' but was '" +
6902 getTypeString(FwdFn->getType()) + "'");
6903 ForwardRefValIDs.erase(I);
6904 }
6905 }
6906
6908 FunctionName, M);
6909
6910 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6911
6912 if (FunctionName.empty())
6913 NumberedVals.add(FunctionNumber, Fn);
6914
6916 maybeSetDSOLocal(DSOLocal, *Fn);
6919 Fn->setCallingConv(CC);
6920 Fn->setAttributes(PAL);
6921 Fn->setUnnamedAddr(UnnamedAddr);
6922 if (Alignment)
6923 Fn->setAlignment(*Alignment);
6924 Fn->setSection(Section);
6925 Fn->setPartition(Partition);
6926 Fn->setComdat(C);
6927 Fn->setPersonalityFn(PersonalityFn);
6928 if (!GC.empty()) Fn->setGC(GC);
6929 Fn->setPrefixData(Prefix);
6930 Fn->setPrologueData(Prologue);
6931 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6932
6933 // Add all of the arguments we parsed to the function.
6934 Function::arg_iterator ArgIt = Fn->arg_begin();
6935 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6936 // If the argument has a name, insert it into the argument symbol table.
6937 if (ArgList[i].Name.empty()) continue;
6938
6939 // Set the name, if it conflicted, it will be auto-renamed.
6940 ArgIt->setName(ArgList[i].Name);
6941
6942 if (ArgIt->getName() != ArgList[i].Name)
6943 return error(ArgList[i].Loc,
6944 "redefinition of argument '%" + ArgList[i].Name + "'");
6945 }
6946
6947 if (FwdFn) {
6948 FwdFn->replaceAllUsesWith(Fn);
6949 FwdFn->eraseFromParent();
6950 }
6951
6952 if (IsDefine)
6953 return false;
6954
6955 // Check the declaration has no block address forward references.
6956 ValID ID;
6957 if (FunctionName.empty()) {
6958 ID.Kind = ValID::t_GlobalID;
6959 ID.UIntVal = FunctionNumber;
6960 } else {
6961 ID.Kind = ValID::t_GlobalName;
6962 ID.StrVal = FunctionName;
6963 }
6964 auto Blocks = ForwardRefBlockAddresses.find(ID);
6965 if (Blocks != ForwardRefBlockAddresses.end())
6966 return error(Blocks->first.Loc,
6967 "cannot take blockaddress inside a declaration");
6968 return false;
6969}
6970
6971bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6972 ValID ID;
6973 if (FunctionNumber == -1) {
6974 ID.Kind = ValID::t_GlobalName;
6975 ID.StrVal = std::string(F.getName());
6976 } else {
6977 ID.Kind = ValID::t_GlobalID;
6978 ID.UIntVal = FunctionNumber;
6979 }
6980
6981 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6982 if (Blocks == P.ForwardRefBlockAddresses.end())
6983 return false;
6984
6985 for (const auto &I : Blocks->second) {
6986 const ValID &BBID = I.first;
6987 GlobalValue *GV = I.second;
6988
6989 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6990 "Expected local id or name");
6991 BasicBlock *BB;
6992 if (BBID.Kind == ValID::t_LocalName)
6993 BB = getBB(BBID.StrVal, BBID.Loc);
6994 else
6995 BB = getBB(BBID.UIntVal, BBID.Loc);
6996 if (!BB)
6997 return P.error(BBID.Loc, "referenced value is not a basic block");
6998
6999 Value *ResolvedVal = BlockAddress::get(&F, BB);
7000 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7001 ResolvedVal);
7002 if (!ResolvedVal)
7003 return true;
7004 GV->replaceAllUsesWith(ResolvedVal);
7005 GV->eraseFromParent();
7006 }
7007
7008 P.ForwardRefBlockAddresses.erase(Blocks);
7009 return false;
7010}
7011
7012/// parseFunctionBody
7013/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7014bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7015 ArrayRef<unsigned> UnnamedArgNums) {
7016 if (Lex.getKind() != lltok::lbrace)
7017 return tokError("expected '{' in function body");
7018 Lex.Lex(); // eat the {.
7019
7020 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7021
7022 // Resolve block addresses and allow basic blocks to be forward-declared
7023 // within this function.
7024 if (PFS.resolveForwardRefBlockAddresses())
7025 return true;
7026 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7027
7028 // We need at least one basic block.
7029 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7030 return tokError("function body requires at least one basic block");
7031
7032 while (Lex.getKind() != lltok::rbrace &&
7033 Lex.getKind() != lltok::kw_uselistorder)
7034 if (parseBasicBlock(PFS))
7035 return true;
7036
7037 while (Lex.getKind() != lltok::rbrace)
7038 if (parseUseListOrder(&PFS))
7039 return true;
7040
7041 // Eat the }.
7042 Lex.Lex();
7043
7044 // Verify function is ok.
7045 return PFS.finishFunction();
7046}
7047
7048/// parseBasicBlock
7049/// ::= (LabelStr|LabelID)? Instruction*
7050bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7051 FileLoc BBStart(Lex.getTokLineColumnPos());
7052
7053 // If this basic block starts out with a name, remember it.
7054 std::string Name;
7055 int NameID = -1;
7056 LocTy NameLoc = Lex.getLoc();
7057 if (Lex.getKind() == lltok::LabelStr) {
7058 Name = Lex.getStrVal();
7059 Lex.Lex();
7060 } else if (Lex.getKind() == lltok::LabelID) {
7061 NameID = Lex.getUIntVal();
7062 Lex.Lex();
7063 }
7064
7065 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7066 if (!BB)
7067 return true;
7068
7069 std::string NameStr;
7070
7071 // Parse the instructions and debug values in this block until we get a
7072 // terminator.
7073 Instruction *Inst;
7074 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7075 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7076 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7077 do {
7078 // Handle debug records first - there should always be an instruction
7079 // following the debug records, i.e. they cannot appear after the block
7080 // terminator.
7081 while (Lex.getKind() == lltok::hash) {
7082 if (SeenOldDbgInfoFormat)
7083 return error(Lex.getLoc(), "debug record should not appear in a module "
7084 "containing debug info intrinsics");
7085 SeenNewDbgInfoFormat = true;
7086 Lex.Lex();
7087
7088 DbgRecord *DR;
7089 if (parseDebugRecord(DR, PFS))
7090 return true;
7091 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7092 }
7093
7094 FileLoc InstStart(Lex.getTokLineColumnPos());
7095 // This instruction may have three possibilities for a name: a) none
7096 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7097 LocTy NameLoc = Lex.getLoc();
7098 int NameID = -1;
7099 NameStr = "";
7100
7101 if (Lex.getKind() == lltok::LocalVarID) {
7102 NameID = Lex.getUIntVal();
7103 Lex.Lex();
7104 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7105 return true;
7106 } else if (Lex.getKind() == lltok::LocalVar) {
7107 NameStr = Lex.getStrVal();
7108 Lex.Lex();
7109 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7110 return true;
7111 }
7112
7113 switch (parseInstruction(Inst, BB, PFS)) {
7114 default:
7115 llvm_unreachable("Unknown parseInstruction result!");
7116 case InstError: return true;
7117 case InstNormal:
7118 Inst->insertInto(BB, BB->end());
7119
7120 // With a normal result, we check to see if the instruction is followed by
7121 // a comma and metadata.
7122 if (EatIfPresent(lltok::comma))
7123 if (parseInstructionMetadata(*Inst))
7124 return true;
7125 break;
7126 case InstExtraComma:
7127 Inst->insertInto(BB, BB->end());
7128
7129 // If the instruction parser ate an extra comma at the end of it, it
7130 // *must* be followed by metadata.
7131 if (parseInstructionMetadata(*Inst))
7132 return true;
7133 break;
7134 }
7135
7136 // Set the name on the instruction.
7137 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7138 return true;
7139
7140 // Attach any preceding debug values to this instruction.
7141 for (DbgRecordPtr &DR : TrailingDbgRecord)
7142 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7143 TrailingDbgRecord.clear();
7144 if (ParserContext) {
7145 ParserContext->addInstructionLocation(
7146 Inst, FileLocRange(InstStart, Lex.getPrevTokEndLineColumnPos()));
7147 }
7148 } while (!Inst->isTerminator());
7149
7150 if (ParserContext)
7151 ParserContext->addBlockLocation(
7152 BB, FileLocRange(BBStart, Lex.getPrevTokEndLineColumnPos()));
7153
7154 assert(TrailingDbgRecord.empty() &&
7155 "All debug values should have been attached to an instruction.");
7156
7157 return false;
7158}
7159
7160/// parseDebugRecord
7161/// ::= #dbg_label '(' MDNode ')'
7162/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7163/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7164bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7165 using RecordKind = DbgRecord::Kind;
7166 using LocType = DbgVariableRecord::LocationType;
7167 LocTy DVRLoc = Lex.getLoc();
7168 if (Lex.getKind() != lltok::DbgRecordType)
7169 return error(DVRLoc, "expected debug record type here");
7170 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7171 .Case("declare", RecordKind::ValueKind)
7172 .Case("value", RecordKind::ValueKind)
7173 .Case("assign", RecordKind::ValueKind)
7174 .Case("label", RecordKind::LabelKind)
7175 .Case("declare_value", RecordKind::ValueKind);
7176
7177 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7178 // full DbgVariableRecord processing stage.
7179 if (RecordType == RecordKind::LabelKind) {
7180 Lex.Lex();
7181 if (parseToken(lltok::lparen, "Expected '(' here"))
7182 return true;
7183 MDNode *Label;
7184 if (parseMDNode(Label))
7185 return true;
7186 if (parseToken(lltok::comma, "Expected ',' here"))
7187 return true;
7188 MDNode *DbgLoc;
7189 if (parseMDNode(DbgLoc))
7190 return true;
7191 if (parseToken(lltok::rparen, "Expected ')' here"))
7192 return true;
7194 return false;
7195 }
7196
7197 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7198 .Case("declare", LocType::Declare)
7199 .Case("value", LocType::Value)
7200 .Case("assign", LocType::Assign)
7201 .Case("declare_value", LocType::DeclareValue);
7202
7203 Lex.Lex();
7204 if (parseToken(lltok::lparen, "Expected '(' here"))
7205 return true;
7206
7207 // Parse Value field.
7208 Metadata *ValLocMD;
7209 if (parseMetadata(ValLocMD, &PFS))
7210 return true;
7211 if (parseToken(lltok::comma, "Expected ',' here"))
7212 return true;
7213
7214 // Parse Variable field.
7215 MDNode *Variable;
7216 if (parseMDNode(Variable))
7217 return true;
7218 if (parseToken(lltok::comma, "Expected ',' here"))
7219 return true;
7220
7221 // Parse Expression field.
7222 MDNode *Expression;
7223 if (parseMDNode(Expression))
7224 return true;
7225 if (parseToken(lltok::comma, "Expected ',' here"))
7226 return true;
7227
7228 // Parse additional fields for #dbg_assign.
7229 MDNode *AssignID = nullptr;
7230 Metadata *AddressLocation = nullptr;
7231 MDNode *AddressExpression = nullptr;
7232 if (ValueType == LocType::Assign) {
7233 // Parse DIAssignID.
7234 if (parseMDNode(AssignID))
7235 return true;
7236 if (parseToken(lltok::comma, "Expected ',' here"))
7237 return true;
7238
7239 // Parse address ValueAsMetadata.
7240 if (parseMetadata(AddressLocation, &PFS))
7241 return true;
7242 if (parseToken(lltok::comma, "Expected ',' here"))
7243 return true;
7244
7245 // Parse address DIExpression.
7246 if (parseMDNode(AddressExpression))
7247 return true;
7248 if (parseToken(lltok::comma, "Expected ',' here"))
7249 return true;
7250 }
7251
7252 /// Parse DILocation.
7253 MDNode *DebugLoc;
7254 if (parseMDNode(DebugLoc))
7255 return true;
7256
7257 if (parseToken(lltok::rparen, "Expected ')' here"))
7258 return true;
7260 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7261 AddressExpression, DebugLoc);
7262 return false;
7263}
7264//===----------------------------------------------------------------------===//
7265// Instruction Parsing.
7266//===----------------------------------------------------------------------===//
7267
7268/// parseInstruction - parse one of the many different instructions.
7269///
7270int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7271 PerFunctionState &PFS) {
7272 lltok::Kind Token = Lex.getKind();
7273 if (Token == lltok::Eof)
7274 return tokError("found end of file when expecting more instructions");
7275 LocTy Loc = Lex.getLoc();
7276 unsigned KeywordVal = Lex.getUIntVal();
7277 Lex.Lex(); // Eat the keyword.
7278
7279 switch (Token) {
7280 default:
7281 return error(Loc, "expected instruction opcode");
7282 // Terminator Instructions.
7283 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7284 case lltok::kw_ret:
7285 return parseRet(Inst, BB, PFS);
7286 case lltok::kw_br:
7287 return parseBr(Inst, PFS);
7288 case lltok::kw_switch:
7289 return parseSwitch(Inst, PFS);
7291 return parseIndirectBr(Inst, PFS);
7292 case lltok::kw_invoke:
7293 return parseInvoke(Inst, PFS);
7294 case lltok::kw_resume:
7295 return parseResume(Inst, PFS);
7297 return parseCleanupRet(Inst, PFS);
7298 case lltok::kw_catchret:
7299 return parseCatchRet(Inst, PFS);
7301 return parseCatchSwitch(Inst, PFS);
7302 case lltok::kw_catchpad:
7303 return parseCatchPad(Inst, PFS);
7305 return parseCleanupPad(Inst, PFS);
7306 case lltok::kw_callbr:
7307 return parseCallBr(Inst, PFS);
7308 // Unary Operators.
7309 case lltok::kw_fneg: {
7310 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7311 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7312 if (Res != 0)
7313 return Res;
7314 if (FMF.any())
7315 Inst->setFastMathFlags(FMF);
7316 return false;
7317 }
7318 // Binary Operators.
7319 case lltok::kw_add:
7320 case lltok::kw_sub:
7321 case lltok::kw_mul:
7322 case lltok::kw_shl: {
7323 bool NUW = EatIfPresent(lltok::kw_nuw);
7324 bool NSW = EatIfPresent(lltok::kw_nsw);
7325 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7326
7327 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7328 return true;
7329
7330 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7331 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7332 return false;
7333 }
7334 case lltok::kw_fadd:
7335 case lltok::kw_fsub:
7336 case lltok::kw_fmul:
7337 case lltok::kw_fdiv:
7338 case lltok::kw_frem: {
7339 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7340 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7341 if (Res != 0)
7342 return Res;
7343 if (FMF.any())
7344 Inst->setFastMathFlags(FMF);
7345 return 0;
7346 }
7347
7348 case lltok::kw_sdiv:
7349 case lltok::kw_udiv:
7350 case lltok::kw_lshr:
7351 case lltok::kw_ashr: {
7352 bool Exact = EatIfPresent(lltok::kw_exact);
7353
7354 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7355 return true;
7356 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7357 return false;
7358 }
7359
7360 case lltok::kw_urem:
7361 case lltok::kw_srem:
7362 return parseArithmetic(Inst, PFS, KeywordVal,
7363 /*IsFP*/ false);
7364 case lltok::kw_or: {
7365 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7366 if (parseLogical(Inst, PFS, KeywordVal))
7367 return true;
7368 if (Disjoint)
7369 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7370 return false;
7371 }
7372 case lltok::kw_and:
7373 case lltok::kw_xor:
7374 return parseLogical(Inst, PFS, KeywordVal);
7375 case lltok::kw_icmp: {
7376 bool SameSign = EatIfPresent(lltok::kw_samesign);
7377 if (parseCompare(Inst, PFS, KeywordVal))
7378 return true;
7379 if (SameSign)
7380 cast<ICmpInst>(Inst)->setSameSign();
7381 return false;
7382 }
7383 case lltok::kw_fcmp: {
7384 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7385 int Res = parseCompare(Inst, PFS, KeywordVal);
7386 if (Res != 0)
7387 return Res;
7388 if (FMF.any())
7389 Inst->setFastMathFlags(FMF);
7390 return 0;
7391 }
7392
7393 // Casts.
7394 case lltok::kw_uitofp:
7395 case lltok::kw_zext: {
7396 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7397 bool Res = parseCast(Inst, PFS, KeywordVal);
7398 if (Res != 0)
7399 return Res;
7400 if (NonNeg)
7401 Inst->setNonNeg();
7402 return 0;
7403 }
7404 case lltok::kw_trunc: {
7405 bool NUW = EatIfPresent(lltok::kw_nuw);
7406 bool NSW = EatIfPresent(lltok::kw_nsw);
7407 if (!NUW)
7408 NUW = EatIfPresent(lltok::kw_nuw);
7409 if (parseCast(Inst, PFS, KeywordVal))
7410 return true;
7411 if (NUW)
7412 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7413 if (NSW)
7414 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7415 return false;
7416 }
7417 case lltok::kw_sext:
7418 case lltok::kw_bitcast:
7420 case lltok::kw_sitofp:
7421 case lltok::kw_fptoui:
7422 case lltok::kw_fptosi:
7423 case lltok::kw_inttoptr:
7425 case lltok::kw_ptrtoint:
7426 return parseCast(Inst, PFS, KeywordVal);
7427 case lltok::kw_fptrunc:
7428 case lltok::kw_fpext: {
7429 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7430 if (parseCast(Inst, PFS, KeywordVal))
7431 return true;
7432 if (FMF.any())
7433 Inst->setFastMathFlags(FMF);
7434 return false;
7435 }
7436
7437 // Other.
7438 case lltok::kw_select: {
7439 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7440 int Res = parseSelect(Inst, PFS);
7441 if (Res != 0)
7442 return Res;
7443 if (FMF.any()) {
7444 if (!isa<FPMathOperator>(Inst))
7445 return error(Loc, "fast-math-flags specified for select without "
7446 "floating-point scalar or vector return type");
7447 Inst->setFastMathFlags(FMF);
7448 }
7449 return 0;
7450 }
7451 case lltok::kw_va_arg:
7452 return parseVAArg(Inst, PFS);
7454 return parseExtractElement(Inst, PFS);
7456 return parseInsertElement(Inst, PFS);
7458 return parseShuffleVector(Inst, PFS);
7459 case lltok::kw_phi: {
7460 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7461 int Res = parsePHI(Inst, PFS);
7462 if (Res != 0)
7463 return Res;
7464 if (FMF.any()) {
7465 if (!isa<FPMathOperator>(Inst))
7466 return error(Loc, "fast-math-flags specified for phi without "
7467 "floating-point scalar or vector return type");
7468 Inst->setFastMathFlags(FMF);
7469 }
7470 return 0;
7471 }
7473 return parseLandingPad(Inst, PFS);
7474 case lltok::kw_freeze:
7475 return parseFreeze(Inst, PFS);
7476 // Call.
7477 case lltok::kw_call:
7478 return parseCall(Inst, PFS, CallInst::TCK_None);
7479 case lltok::kw_tail:
7480 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7481 case lltok::kw_musttail:
7482 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7483 case lltok::kw_notail:
7484 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7485 // Memory.
7486 case lltok::kw_alloca:
7487 return parseAlloc(Inst, PFS);
7488 case lltok::kw_load:
7489 return parseLoad(Inst, PFS);
7490 case lltok::kw_store:
7491 return parseStore(Inst, PFS);
7492 case lltok::kw_cmpxchg:
7493 return parseCmpXchg(Inst, PFS);
7495 return parseAtomicRMW(Inst, PFS);
7496 case lltok::kw_fence:
7497 return parseFence(Inst, PFS);
7499 return parseGetElementPtr(Inst, PFS);
7501 return parseExtractValue(Inst, PFS);
7503 return parseInsertValue(Inst, PFS);
7504 }
7505}
7506
7507/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7508bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7509 if (Opc == Instruction::FCmp) {
7510 switch (Lex.getKind()) {
7511 default:
7512 return tokError("expected fcmp predicate (e.g. 'oeq')");
7513 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7514 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7515 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7516 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7517 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7518 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7519 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7520 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7521 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7522 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7523 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7524 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7525 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7526 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7527 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7528 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7529 }
7530 } else {
7531 switch (Lex.getKind()) {
7532 default:
7533 return tokError("expected icmp predicate (e.g. 'eq')");
7534 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7535 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7536 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7537 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7538 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7539 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7540 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7541 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7542 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7543 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7544 }
7545 }
7546 Lex.Lex();
7547 return false;
7548}
7549
7550//===----------------------------------------------------------------------===//
7551// Terminator Instructions.
7552//===----------------------------------------------------------------------===//
7553
7554/// parseRet - parse a return instruction.
7555/// ::= 'ret' void (',' !dbg, !1)*
7556/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7557bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7558 PerFunctionState &PFS) {
7559 SMLoc TypeLoc = Lex.getLoc();
7560 Type *Ty = nullptr;
7561 if (parseType(Ty, true /*void allowed*/))
7562 return true;
7563
7564 Type *ResType = PFS.getFunction().getReturnType();
7565
7566 if (Ty->isVoidTy()) {
7567 if (!ResType->isVoidTy())
7568 return error(TypeLoc, "value doesn't match function result type '" +
7569 getTypeString(ResType) + "'");
7570
7571 Inst = ReturnInst::Create(Context);
7572 return false;
7573 }
7574
7575 Value *RV;
7576 if (parseValue(Ty, RV, PFS))
7577 return true;
7578
7579 if (ResType != RV->getType())
7580 return error(TypeLoc, "value doesn't match function result type '" +
7581 getTypeString(ResType) + "'");
7582
7583 Inst = ReturnInst::Create(Context, RV);
7584 return false;
7585}
7586
7587/// parseBr
7588/// ::= 'br' TypeAndValue
7589/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7590bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7591 LocTy Loc, Loc2;
7592 Value *Op0;
7593 BasicBlock *Op1, *Op2;
7594 if (parseTypeAndValue(Op0, Loc, PFS))
7595 return true;
7596
7597 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7598 Inst = BranchInst::Create(BB);
7599 return false;
7600 }
7601
7602 if (Op0->getType() != Type::getInt1Ty(Context))
7603 return error(Loc, "branch condition must have 'i1' type");
7604
7605 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7606 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7607 parseToken(lltok::comma, "expected ',' after true destination") ||
7608 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7609 return true;
7610
7611 Inst = BranchInst::Create(Op1, Op2, Op0);
7612 return false;
7613}
7614
7615/// parseSwitch
7616/// Instruction
7617/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7618/// JumpTable
7619/// ::= (TypeAndValue ',' TypeAndValue)*
7620bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7621 LocTy CondLoc, BBLoc;
7622 Value *Cond;
7623 BasicBlock *DefaultBB;
7624 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7625 parseToken(lltok::comma, "expected ',' after switch condition") ||
7626 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7627 parseToken(lltok::lsquare, "expected '[' with switch table"))
7628 return true;
7629
7630 if (!Cond->getType()->isIntegerTy())
7631 return error(CondLoc, "switch condition must have integer type");
7632
7633 // parse the jump table pairs.
7634 SmallPtrSet<Value*, 32> SeenCases;
7636 while (Lex.getKind() != lltok::rsquare) {
7637 Value *Constant;
7638 BasicBlock *DestBB;
7639
7640 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7641 parseToken(lltok::comma, "expected ',' after case value") ||
7642 parseTypeAndBasicBlock(DestBB, PFS))
7643 return true;
7644
7645 if (!SeenCases.insert(Constant).second)
7646 return error(CondLoc, "duplicate case value in switch");
7647 if (!isa<ConstantInt>(Constant))
7648 return error(CondLoc, "case value is not a constant integer");
7649
7650 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7651 }
7652
7653 Lex.Lex(); // Eat the ']'.
7654
7655 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7656 for (const auto &[OnVal, Dest] : Table)
7657 SI->addCase(OnVal, Dest);
7658 Inst = SI;
7659 return false;
7660}
7661
7662/// parseIndirectBr
7663/// Instruction
7664/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7665bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7666 LocTy AddrLoc;
7667 Value *Address;
7668 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7669 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7670 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7671 return true;
7672
7673 if (!Address->getType()->isPointerTy())
7674 return error(AddrLoc, "indirectbr address must have pointer type");
7675
7676 // parse the destination list.
7677 SmallVector<BasicBlock*, 16> DestList;
7678
7679 if (Lex.getKind() != lltok::rsquare) {
7680 BasicBlock *DestBB;
7681 if (parseTypeAndBasicBlock(DestBB, PFS))
7682 return true;
7683 DestList.push_back(DestBB);
7684
7685 while (EatIfPresent(lltok::comma)) {
7686 if (parseTypeAndBasicBlock(DestBB, PFS))
7687 return true;
7688 DestList.push_back(DestBB);
7689 }
7690 }
7691
7692 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7693 return true;
7694
7695 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7696 for (BasicBlock *Dest : DestList)
7697 IBI->addDestination(Dest);
7698 Inst = IBI;
7699 return false;
7700}
7701
7702// If RetType is a non-function pointer type, then this is the short syntax
7703// for the call, which means that RetType is just the return type. Infer the
7704// rest of the function argument types from the arguments that are present.
7705bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7706 FunctionType *&FuncTy) {
7707 FuncTy = dyn_cast<FunctionType>(RetType);
7708 if (!FuncTy) {
7709 // Pull out the types of all of the arguments...
7710 SmallVector<Type *, 8> ParamTypes;
7711 ParamTypes.reserve(ArgList.size());
7712 for (const ParamInfo &Arg : ArgList)
7713 ParamTypes.push_back(Arg.V->getType());
7714
7715 if (!FunctionType::isValidReturnType(RetType))
7716 return true;
7717
7718 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7719 }
7720 return false;
7721}
7722
7723/// parseInvoke
7724/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7725/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7726bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7727 LocTy CallLoc = Lex.getLoc();
7728 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7729 std::vector<unsigned> FwdRefAttrGrps;
7730 LocTy NoBuiltinLoc;
7731 unsigned CC;
7732 unsigned InvokeAddrSpace;
7733 Type *RetType = nullptr;
7734 LocTy RetTypeLoc;
7735 ValID CalleeID;
7738
7739 BasicBlock *NormalBB, *UnwindBB;
7740 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7741 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7742 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7743 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7744 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7745 NoBuiltinLoc) ||
7746 parseOptionalOperandBundles(BundleList, PFS) ||
7747 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7748 parseTypeAndBasicBlock(NormalBB, PFS) ||
7749 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7750 parseTypeAndBasicBlock(UnwindBB, PFS))
7751 return true;
7752
7753 // If RetType is a non-function pointer type, then this is the short syntax
7754 // for the call, which means that RetType is just the return type. Infer the
7755 // rest of the function argument types from the arguments that are present.
7756 FunctionType *Ty;
7757 if (resolveFunctionType(RetType, ArgList, Ty))
7758 return error(RetTypeLoc, "Invalid result type for LLVM function");
7759
7760 CalleeID.FTy = Ty;
7761
7762 // Look up the callee.
7763 Value *Callee;
7764 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7765 Callee, &PFS))
7766 return true;
7767
7768 // Set up the Attribute for the function.
7769 SmallVector<Value *, 8> Args;
7771
7772 // Loop through FunctionType's arguments and ensure they are specified
7773 // correctly. Also, gather any parameter attributes.
7774 FunctionType::param_iterator I = Ty->param_begin();
7775 FunctionType::param_iterator E = Ty->param_end();
7776 for (const ParamInfo &Arg : ArgList) {
7777 Type *ExpectedTy = nullptr;
7778 if (I != E) {
7779 ExpectedTy = *I++;
7780 } else if (!Ty->isVarArg()) {
7781 return error(Arg.Loc, "too many arguments specified");
7782 }
7783
7784 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7785 return error(Arg.Loc, "argument is not of expected type '" +
7786 getTypeString(ExpectedTy) + "'");
7787 Args.push_back(Arg.V);
7788 ArgAttrs.push_back(Arg.Attrs);
7789 }
7790
7791 if (I != E)
7792 return error(CallLoc, "not enough parameters specified for call");
7793
7794 // Finish off the Attribute and check them
7795 AttributeList PAL =
7796 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7797 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7798
7799 InvokeInst *II =
7800 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7801 II->setCallingConv(CC);
7802 II->setAttributes(PAL);
7803 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7804 Inst = II;
7805 return false;
7806}
7807
7808/// parseResume
7809/// ::= 'resume' TypeAndValue
7810bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7811 Value *Exn; LocTy ExnLoc;
7812 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7813 return true;
7814
7815 ResumeInst *RI = ResumeInst::Create(Exn);
7816 Inst = RI;
7817 return false;
7818}
7819
7820bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7821 PerFunctionState &PFS) {
7822 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7823 return true;
7824
7825 while (Lex.getKind() != lltok::rsquare) {
7826 // If this isn't the first argument, we need a comma.
7827 if (!Args.empty() &&
7828 parseToken(lltok::comma, "expected ',' in argument list"))
7829 return true;
7830
7831 // parse the argument.
7832 LocTy ArgLoc;
7833 Type *ArgTy = nullptr;
7834 if (parseType(ArgTy, ArgLoc))
7835 return true;
7836
7837 Value *V;
7838 if (ArgTy->isMetadataTy()) {
7839 if (parseMetadataAsValue(V, PFS))
7840 return true;
7841 } else {
7842 if (parseValue(ArgTy, V, PFS))
7843 return true;
7844 }
7845 Args.push_back(V);
7846 }
7847
7848 Lex.Lex(); // Lex the ']'.
7849 return false;
7850}
7851
7852/// parseCleanupRet
7853/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7854bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7855 Value *CleanupPad = nullptr;
7856
7857 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7858 return true;
7859
7860 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7861 return true;
7862
7863 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7864 return true;
7865
7866 BasicBlock *UnwindBB = nullptr;
7867 if (Lex.getKind() == lltok::kw_to) {
7868 Lex.Lex();
7869 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7870 return true;
7871 } else {
7872 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7873 return true;
7874 }
7875 }
7876
7877 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7878 return false;
7879}
7880
7881/// parseCatchRet
7882/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7883bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7884 Value *CatchPad = nullptr;
7885
7886 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7887 return true;
7888
7889 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7890 return true;
7891
7892 BasicBlock *BB;
7893 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7894 parseTypeAndBasicBlock(BB, PFS))
7895 return true;
7896
7897 Inst = CatchReturnInst::Create(CatchPad, BB);
7898 return false;
7899}
7900
7901/// parseCatchSwitch
7902/// ::= 'catchswitch' within Parent
7903bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7904 Value *ParentPad;
7905
7906 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7907 return true;
7908
7909 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7910 Lex.getKind() != lltok::LocalVarID)
7911 return tokError("expected scope value for catchswitch");
7912
7913 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7914 return true;
7915
7916 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7917 return true;
7918
7920 do {
7921 BasicBlock *DestBB;
7922 if (parseTypeAndBasicBlock(DestBB, PFS))
7923 return true;
7924 Table.push_back(DestBB);
7925 } while (EatIfPresent(lltok::comma));
7926
7927 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7928 return true;
7929
7930 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7931 return true;
7932
7933 BasicBlock *UnwindBB = nullptr;
7934 if (EatIfPresent(lltok::kw_to)) {
7935 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7936 return true;
7937 } else {
7938 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7939 return true;
7940 }
7941
7942 auto *CatchSwitch =
7943 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7944 for (BasicBlock *DestBB : Table)
7945 CatchSwitch->addHandler(DestBB);
7946 Inst = CatchSwitch;
7947 return false;
7948}
7949
7950/// parseCatchPad
7951/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7952bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7953 Value *CatchSwitch = nullptr;
7954
7955 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7956 return true;
7957
7958 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7959 return tokError("expected scope value for catchpad");
7960
7961 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7962 return true;
7963
7964 SmallVector<Value *, 8> Args;
7965 if (parseExceptionArgs(Args, PFS))
7966 return true;
7967
7968 Inst = CatchPadInst::Create(CatchSwitch, Args);
7969 return false;
7970}
7971
7972/// parseCleanupPad
7973/// ::= 'cleanuppad' within Parent ParamList
7974bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7975 Value *ParentPad = nullptr;
7976
7977 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7978 return true;
7979
7980 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7981 Lex.getKind() != lltok::LocalVarID)
7982 return tokError("expected scope value for cleanuppad");
7983
7984 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7985 return true;
7986
7987 SmallVector<Value *, 8> Args;
7988 if (parseExceptionArgs(Args, PFS))
7989 return true;
7990
7991 Inst = CleanupPadInst::Create(ParentPad, Args);
7992 return false;
7993}
7994
7995//===----------------------------------------------------------------------===//
7996// Unary Operators.
7997//===----------------------------------------------------------------------===//
7998
7999/// parseUnaryOp
8000/// ::= UnaryOp TypeAndValue ',' Value
8001///
8002/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8003/// operand is allowed.
8004bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8005 unsigned Opc, bool IsFP) {
8006 LocTy Loc; Value *LHS;
8007 if (parseTypeAndValue(LHS, Loc, PFS))
8008 return true;
8009
8010 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8012
8013 if (!Valid)
8014 return error(Loc, "invalid operand type for instruction");
8015
8017 return false;
8018}
8019
8020/// parseCallBr
8021/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8022/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8023/// '[' LabelList ']'
8024bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8025 LocTy CallLoc = Lex.getLoc();
8026 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8027 std::vector<unsigned> FwdRefAttrGrps;
8028 LocTy NoBuiltinLoc;
8029 unsigned CC;
8030 Type *RetType = nullptr;
8031 LocTy RetTypeLoc;
8032 ValID CalleeID;
8035
8036 BasicBlock *DefaultDest;
8037 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8038 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8039 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8040 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8041 NoBuiltinLoc) ||
8042 parseOptionalOperandBundles(BundleList, PFS) ||
8043 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8044 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8045 parseToken(lltok::lsquare, "expected '[' in callbr"))
8046 return true;
8047
8048 // parse the destination list.
8049 SmallVector<BasicBlock *, 16> IndirectDests;
8050
8051 if (Lex.getKind() != lltok::rsquare) {
8052 BasicBlock *DestBB;
8053 if (parseTypeAndBasicBlock(DestBB, PFS))
8054 return true;
8055 IndirectDests.push_back(DestBB);
8056
8057 while (EatIfPresent(lltok::comma)) {
8058 if (parseTypeAndBasicBlock(DestBB, PFS))
8059 return true;
8060 IndirectDests.push_back(DestBB);
8061 }
8062 }
8063
8064 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8065 return true;
8066
8067 // If RetType is a non-function pointer type, then this is the short syntax
8068 // for the call, which means that RetType is just the return type. Infer the
8069 // rest of the function argument types from the arguments that are present.
8070 FunctionType *Ty;
8071 if (resolveFunctionType(RetType, ArgList, Ty))
8072 return error(RetTypeLoc, "Invalid result type for LLVM function");
8073
8074 CalleeID.FTy = Ty;
8075
8076 // Look up the callee.
8077 Value *Callee;
8078 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8079 &PFS))
8080 return true;
8081
8082 // Set up the Attribute for the function.
8083 SmallVector<Value *, 8> Args;
8085
8086 // Loop through FunctionType's arguments and ensure they are specified
8087 // correctly. Also, gather any parameter attributes.
8088 FunctionType::param_iterator I = Ty->param_begin();
8089 FunctionType::param_iterator E = Ty->param_end();
8090 for (const ParamInfo &Arg : ArgList) {
8091 Type *ExpectedTy = nullptr;
8092 if (I != E) {
8093 ExpectedTy = *I++;
8094 } else if (!Ty->isVarArg()) {
8095 return error(Arg.Loc, "too many arguments specified");
8096 }
8097
8098 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8099 return error(Arg.Loc, "argument is not of expected type '" +
8100 getTypeString(ExpectedTy) + "'");
8101 Args.push_back(Arg.V);
8102 ArgAttrs.push_back(Arg.Attrs);
8103 }
8104
8105 if (I != E)
8106 return error(CallLoc, "not enough parameters specified for call");
8107
8108 // Finish off the Attribute and check them
8109 AttributeList PAL =
8110 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8111 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8112
8113 CallBrInst *CBI =
8114 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8115 BundleList);
8116 CBI->setCallingConv(CC);
8117 CBI->setAttributes(PAL);
8118 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8119 Inst = CBI;
8120 return false;
8121}
8122
8123//===----------------------------------------------------------------------===//
8124// Binary Operators.
8125//===----------------------------------------------------------------------===//
8126
8127/// parseArithmetic
8128/// ::= ArithmeticOps TypeAndValue ',' Value
8129///
8130/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8131/// operand is allowed.
8132bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8133 unsigned Opc, bool IsFP) {
8134 LocTy Loc; Value *LHS, *RHS;
8135 if (parseTypeAndValue(LHS, Loc, PFS) ||
8136 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8137 parseValue(LHS->getType(), RHS, PFS))
8138 return true;
8139
8140 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8142
8143 if (!Valid)
8144 return error(Loc, "invalid operand type for instruction");
8145
8147 return false;
8148}
8149
8150/// parseLogical
8151/// ::= ArithmeticOps TypeAndValue ',' Value {
8152bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8153 unsigned Opc) {
8154 LocTy Loc; Value *LHS, *RHS;
8155 if (parseTypeAndValue(LHS, Loc, PFS) ||
8156 parseToken(lltok::comma, "expected ',' in logical operation") ||
8157 parseValue(LHS->getType(), RHS, PFS))
8158 return true;
8159
8160 if (!LHS->getType()->isIntOrIntVectorTy())
8161 return error(Loc,
8162 "instruction requires integer or integer vector operands");
8163
8165 return false;
8166}
8167
8168/// parseCompare
8169/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8170/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8171bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8172 unsigned Opc) {
8173 // parse the integer/fp comparison predicate.
8174 LocTy Loc;
8175 unsigned Pred;
8176 Value *LHS, *RHS;
8177 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8178 parseToken(lltok::comma, "expected ',' after compare value") ||
8179 parseValue(LHS->getType(), RHS, PFS))
8180 return true;
8181
8182 if (Opc == Instruction::FCmp) {
8183 if (!LHS->getType()->isFPOrFPVectorTy())
8184 return error(Loc, "fcmp requires floating point operands");
8185 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8186 } else {
8187 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8188 if (!LHS->getType()->isIntOrIntVectorTy() &&
8190 return error(Loc, "icmp requires integer operands");
8191 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8192 }
8193 return false;
8194}
8195
8196//===----------------------------------------------------------------------===//
8197// Other Instructions.
8198//===----------------------------------------------------------------------===//
8199
8200/// parseCast
8201/// ::= CastOpc TypeAndValue 'to' Type
8202bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8203 unsigned Opc) {
8204 LocTy Loc;
8205 Value *Op;
8206 Type *DestTy = nullptr;
8207 if (parseTypeAndValue(Op, Loc, PFS) ||
8208 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8209 parseType(DestTy))
8210 return true;
8211
8213 return error(Loc, "invalid cast opcode for cast from '" +
8214 getTypeString(Op->getType()) + "' to '" +
8215 getTypeString(DestTy) + "'");
8216 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8217 return false;
8218}
8219
8220/// parseSelect
8221/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8222bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8223 LocTy Loc;
8224 Value *Op0, *Op1, *Op2;
8225 if (parseTypeAndValue(Op0, Loc, PFS) ||
8226 parseToken(lltok::comma, "expected ',' after select condition") ||
8227 parseTypeAndValue(Op1, PFS) ||
8228 parseToken(lltok::comma, "expected ',' after select value") ||
8229 parseTypeAndValue(Op2, PFS))
8230 return true;
8231
8232 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8233 return error(Loc, Reason);
8234
8235 Inst = SelectInst::Create(Op0, Op1, Op2);
8236 return false;
8237}
8238
8239/// parseVAArg
8240/// ::= 'va_arg' TypeAndValue ',' Type
8241bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8242 Value *Op;
8243 Type *EltTy = nullptr;
8244 LocTy TypeLoc;
8245 if (parseTypeAndValue(Op, PFS) ||
8246 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8247 parseType(EltTy, TypeLoc))
8248 return true;
8249
8250 if (!EltTy->isFirstClassType())
8251 return error(TypeLoc, "va_arg requires operand with first class type");
8252
8253 Inst = new VAArgInst(Op, EltTy);
8254 return false;
8255}
8256
8257/// parseExtractElement
8258/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8259bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8260 LocTy Loc;
8261 Value *Op0, *Op1;
8262 if (parseTypeAndValue(Op0, Loc, PFS) ||
8263 parseToken(lltok::comma, "expected ',' after extract value") ||
8264 parseTypeAndValue(Op1, PFS))
8265 return true;
8266
8268 return error(Loc, "invalid extractelement operands");
8269
8270 Inst = ExtractElementInst::Create(Op0, Op1);
8271 return false;
8272}
8273
8274/// parseInsertElement
8275/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8276bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8277 LocTy Loc;
8278 Value *Op0, *Op1, *Op2;
8279 if (parseTypeAndValue(Op0, Loc, PFS) ||
8280 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8281 parseTypeAndValue(Op1, PFS) ||
8282 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8283 parseTypeAndValue(Op2, PFS))
8284 return true;
8285
8286 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8287 return error(Loc, "invalid insertelement operands");
8288
8289 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8290 return false;
8291}
8292
8293/// parseShuffleVector
8294/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8295bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8296 LocTy Loc;
8297 Value *Op0, *Op1, *Op2;
8298 if (parseTypeAndValue(Op0, Loc, PFS) ||
8299 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8300 parseTypeAndValue(Op1, PFS) ||
8301 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8302 parseTypeAndValue(Op2, PFS))
8303 return true;
8304
8305 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8306 return error(Loc, "invalid shufflevector operands");
8307
8308 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8309 return false;
8310}
8311
8312/// parsePHI
8313/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8314int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8315 Type *Ty = nullptr; LocTy TypeLoc;
8316 Value *Op0, *Op1;
8317
8318 if (parseType(Ty, TypeLoc))
8319 return true;
8320
8321 if (!Ty->isFirstClassType())
8322 return error(TypeLoc, "phi node must have first class type");
8323
8324 bool First = true;
8325 bool AteExtraComma = false;
8327
8328 while (true) {
8329 if (First) {
8330 if (Lex.getKind() != lltok::lsquare)
8331 break;
8332 First = false;
8333 } else if (!EatIfPresent(lltok::comma))
8334 break;
8335
8336 if (Lex.getKind() == lltok::MetadataVar) {
8337 AteExtraComma = true;
8338 break;
8339 }
8340
8341 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8342 parseValue(Ty, Op0, PFS) ||
8343 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8344 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8345 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8346 return true;
8347
8348 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8349 }
8350
8351 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8352 for (const auto &[Val, BB] : PHIVals)
8353 PN->addIncoming(Val, BB);
8354 Inst = PN;
8355 return AteExtraComma ? InstExtraComma : InstNormal;
8356}
8357
8358/// parseLandingPad
8359/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8360/// Clause
8361/// ::= 'catch' TypeAndValue
8362/// ::= 'filter'
8363/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8364bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8365 Type *Ty = nullptr; LocTy TyLoc;
8366
8367 if (parseType(Ty, TyLoc))
8368 return true;
8369
8370 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8371 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8372
8373 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8375 if (EatIfPresent(lltok::kw_catch))
8377 else if (EatIfPresent(lltok::kw_filter))
8379 else
8380 return tokError("expected 'catch' or 'filter' clause type");
8381
8382 Value *V;
8383 LocTy VLoc;
8384 if (parseTypeAndValue(V, VLoc, PFS))
8385 return true;
8386
8387 // A 'catch' type expects a non-array constant. A filter clause expects an
8388 // array constant.
8389 if (CT == LandingPadInst::Catch) {
8390 if (isa<ArrayType>(V->getType()))
8391 return error(VLoc, "'catch' clause has an invalid type");
8392 } else {
8393 if (!isa<ArrayType>(V->getType()))
8394 return error(VLoc, "'filter' clause has an invalid type");
8395 }
8396
8398 if (!CV)
8399 return error(VLoc, "clause argument must be a constant");
8400 LP->addClause(CV);
8401 }
8402
8403 Inst = LP.release();
8404 return false;
8405}
8406
8407/// parseFreeze
8408/// ::= 'freeze' Type Value
8409bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8410 LocTy Loc;
8411 Value *Op;
8412 if (parseTypeAndValue(Op, Loc, PFS))
8413 return true;
8414
8415 Inst = new FreezeInst(Op);
8416 return false;
8417}
8418
8419/// parseCall
8420/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8421/// OptionalAttrs Type Value ParameterList OptionalAttrs
8422/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8423/// OptionalAttrs Type Value ParameterList OptionalAttrs
8424/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8425/// OptionalAttrs Type Value ParameterList OptionalAttrs
8426/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8427/// OptionalAttrs Type Value ParameterList OptionalAttrs
8428bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8430 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8431 std::vector<unsigned> FwdRefAttrGrps;
8432 LocTy BuiltinLoc;
8433 unsigned CallAddrSpace;
8434 unsigned CC;
8435 Type *RetType = nullptr;
8436 LocTy RetTypeLoc;
8437 ValID CalleeID;
8440 LocTy CallLoc = Lex.getLoc();
8441
8442 if (TCK != CallInst::TCK_None &&
8443 parseToken(lltok::kw_call,
8444 "expected 'tail call', 'musttail call', or 'notail call'"))
8445 return true;
8446
8447 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8448
8449 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8450 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8451 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8452 parseValID(CalleeID, &PFS) ||
8453 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8454 PFS.getFunction().isVarArg()) ||
8455 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8456 parseOptionalOperandBundles(BundleList, PFS))
8457 return true;
8458
8459 // If RetType is a non-function pointer type, then this is the short syntax
8460 // for the call, which means that RetType is just the return type. Infer the
8461 // rest of the function argument types from the arguments that are present.
8462 FunctionType *Ty;
8463 if (resolveFunctionType(RetType, ArgList, Ty))
8464 return error(RetTypeLoc, "Invalid result type for LLVM function");
8465
8466 CalleeID.FTy = Ty;
8467
8468 // Look up the callee.
8469 Value *Callee;
8470 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8471 Callee, &PFS))
8472 return true;
8473
8474 // Set up the Attribute for the function.
8476
8477 SmallVector<Value*, 8> Args;
8478
8479 // Loop through FunctionType's arguments and ensure they are specified
8480 // correctly. Also, gather any parameter attributes.
8481 FunctionType::param_iterator I = Ty->param_begin();
8482 FunctionType::param_iterator E = Ty->param_end();
8483 for (const ParamInfo &Arg : ArgList) {
8484 Type *ExpectedTy = nullptr;
8485 if (I != E) {
8486 ExpectedTy = *I++;
8487 } else if (!Ty->isVarArg()) {
8488 return error(Arg.Loc, "too many arguments specified");
8489 }
8490
8491 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8492 return error(Arg.Loc, "argument is not of expected type '" +
8493 getTypeString(ExpectedTy) + "'");
8494 Args.push_back(Arg.V);
8495 Attrs.push_back(Arg.Attrs);
8496 }
8497
8498 if (I != E)
8499 return error(CallLoc, "not enough parameters specified for call");
8500
8501 // Finish off the Attribute and check them
8502 AttributeList PAL =
8503 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8504 AttributeSet::get(Context, RetAttrs), Attrs);
8505
8506 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8507 CI->setTailCallKind(TCK);
8508 CI->setCallingConv(CC);
8509 if (FMF.any()) {
8510 if (!isa<FPMathOperator>(CI)) {
8511 CI->deleteValue();
8512 return error(CallLoc, "fast-math-flags specified for call without "
8513 "floating-point scalar or vector return type");
8514 }
8515 CI->setFastMathFlags(FMF);
8516 }
8517
8518 if (CalleeID.Kind == ValID::t_GlobalName &&
8519 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8520 if (SeenNewDbgInfoFormat) {
8521 CI->deleteValue();
8522 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8523 "using non-intrinsic debug info");
8524 }
8525 SeenOldDbgInfoFormat = true;
8526 }
8527 CI->setAttributes(PAL);
8528 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8529 Inst = CI;
8530 return false;
8531}
8532
8533//===----------------------------------------------------------------------===//
8534// Memory Instructions.
8535//===----------------------------------------------------------------------===//
8536
8537/// parseAlloc
8538/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8539/// (',' 'align' i32)? (',', 'addrspace(n))?
8540int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8541 Value *Size = nullptr;
8542 LocTy SizeLoc, TyLoc, ASLoc;
8543 MaybeAlign Alignment;
8544 unsigned AddrSpace = 0;
8545 Type *Ty = nullptr;
8546
8547 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8548 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8549
8550 if (parseType(Ty, TyLoc))
8551 return true;
8552
8554 return error(TyLoc, "invalid type for alloca");
8555
8556 bool AteExtraComma = false;
8557 if (EatIfPresent(lltok::comma)) {
8558 if (Lex.getKind() == lltok::kw_align) {
8559 if (parseOptionalAlignment(Alignment))
8560 return true;
8561 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8562 return true;
8563 } else if (Lex.getKind() == lltok::kw_addrspace) {
8564 ASLoc = Lex.getLoc();
8565 if (parseOptionalAddrSpace(AddrSpace))
8566 return true;
8567 } else if (Lex.getKind() == lltok::MetadataVar) {
8568 AteExtraComma = true;
8569 } else {
8570 if (parseTypeAndValue(Size, SizeLoc, PFS))
8571 return true;
8572 if (EatIfPresent(lltok::comma)) {
8573 if (Lex.getKind() == lltok::kw_align) {
8574 if (parseOptionalAlignment(Alignment))
8575 return true;
8576 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8577 return true;
8578 } else if (Lex.getKind() == lltok::kw_addrspace) {
8579 ASLoc = Lex.getLoc();
8580 if (parseOptionalAddrSpace(AddrSpace))
8581 return true;
8582 } else if (Lex.getKind() == lltok::MetadataVar) {
8583 AteExtraComma = true;
8584 }
8585 }
8586 }
8587 }
8588
8589 if (Size && !Size->getType()->isIntegerTy())
8590 return error(SizeLoc, "element count must have integer type");
8591
8592 SmallPtrSet<Type *, 4> Visited;
8593 if (!Alignment && !Ty->isSized(&Visited))
8594 return error(TyLoc, "Cannot allocate unsized type");
8595 if (!Alignment)
8596 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8597 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8598 AI->setUsedWithInAlloca(IsInAlloca);
8599 AI->setSwiftError(IsSwiftError);
8600 Inst = AI;
8601 return AteExtraComma ? InstExtraComma : InstNormal;
8602}
8603
8604/// parseLoad
8605/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8606/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8607/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8608int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8609 Value *Val; LocTy Loc;
8610 MaybeAlign Alignment;
8611 bool AteExtraComma = false;
8612 bool isAtomic = false;
8615
8616 if (Lex.getKind() == lltok::kw_atomic) {
8617 isAtomic = true;
8618 Lex.Lex();
8619 }
8620
8621 bool isVolatile = false;
8622 if (Lex.getKind() == lltok::kw_volatile) {
8623 isVolatile = true;
8624 Lex.Lex();
8625 }
8626
8627 Type *Ty;
8628 LocTy ExplicitTypeLoc = Lex.getLoc();
8629 if (parseType(Ty) ||
8630 parseToken(lltok::comma, "expected comma after load's type") ||
8631 parseTypeAndValue(Val, Loc, PFS) ||
8632 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8633 parseOptionalCommaAlign(Alignment, AteExtraComma))
8634 return true;
8635
8636 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8637 return error(Loc, "load operand must be a pointer to a first class type");
8638 if (isAtomic && !Alignment)
8639 return error(Loc, "atomic load must have explicit non-zero alignment");
8640 if (Ordering == AtomicOrdering::Release ||
8642 return error(Loc, "atomic load cannot use Release ordering");
8643
8644 SmallPtrSet<Type *, 4> Visited;
8645 if (!Alignment && !Ty->isSized(&Visited))
8646 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8647 if (!Alignment)
8648 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8649 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8650 return AteExtraComma ? InstExtraComma : InstNormal;
8651}
8652
8653/// parseStore
8654
8655/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8656/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8657/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8658int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8659 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8660 MaybeAlign Alignment;
8661 bool AteExtraComma = false;
8662 bool isAtomic = false;
8665
8666 if (Lex.getKind() == lltok::kw_atomic) {
8667 isAtomic = true;
8668 Lex.Lex();
8669 }
8670
8671 bool isVolatile = false;
8672 if (Lex.getKind() == lltok::kw_volatile) {
8673 isVolatile = true;
8674 Lex.Lex();
8675 }
8676
8677 if (parseTypeAndValue(Val, Loc, PFS) ||
8678 parseToken(lltok::comma, "expected ',' after store operand") ||
8679 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8680 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8681 parseOptionalCommaAlign(Alignment, AteExtraComma))
8682 return true;
8683
8684 if (!Ptr->getType()->isPointerTy())
8685 return error(PtrLoc, "store operand must be a pointer");
8686 if (!Val->getType()->isFirstClassType())
8687 return error(Loc, "store operand must be a first class value");
8688 if (isAtomic && !Alignment)
8689 return error(Loc, "atomic store must have explicit non-zero alignment");
8690 if (Ordering == AtomicOrdering::Acquire ||
8692 return error(Loc, "atomic store cannot use Acquire ordering");
8693 SmallPtrSet<Type *, 4> Visited;
8694 if (!Alignment && !Val->getType()->isSized(&Visited))
8695 return error(Loc, "storing unsized types is not allowed");
8696 if (!Alignment)
8697 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8698
8699 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8700 return AteExtraComma ? InstExtraComma : InstNormal;
8701}
8702
8703/// parseCmpXchg
8704/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8705/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8706/// 'Align'?
8707int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8708 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8709 bool AteExtraComma = false;
8710 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8711 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8713 bool isVolatile = false;
8714 bool isWeak = false;
8715 MaybeAlign Alignment;
8716
8717 if (EatIfPresent(lltok::kw_weak))
8718 isWeak = true;
8719
8720 if (EatIfPresent(lltok::kw_volatile))
8721 isVolatile = true;
8722
8723 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8724 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8725 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8726 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8727 parseTypeAndValue(New, NewLoc, PFS) ||
8728 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8729 parseOrdering(FailureOrdering) ||
8730 parseOptionalCommaAlign(Alignment, AteExtraComma))
8731 return true;
8732
8733 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8734 return tokError("invalid cmpxchg success ordering");
8735 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8736 return tokError("invalid cmpxchg failure ordering");
8737 if (!Ptr->getType()->isPointerTy())
8738 return error(PtrLoc, "cmpxchg operand must be a pointer");
8739 if (Cmp->getType() != New->getType())
8740 return error(NewLoc, "compare value and new value type do not match");
8741 if (!New->getType()->isFirstClassType())
8742 return error(NewLoc, "cmpxchg operand must be a first class value");
8743
8744 const Align DefaultAlignment(
8745 PFS.getFunction().getDataLayout().getTypeStoreSize(
8746 Cmp->getType()));
8747
8748 AtomicCmpXchgInst *CXI =
8749 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8750 SuccessOrdering, FailureOrdering, SSID);
8751 CXI->setVolatile(isVolatile);
8752 CXI->setWeak(isWeak);
8753
8754 Inst = CXI;
8755 return AteExtraComma ? InstExtraComma : InstNormal;
8756}
8757
8758/// parseAtomicRMW
8759/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8760/// 'singlethread'? AtomicOrdering
8761int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8762 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8763 bool AteExtraComma = false;
8766 bool isVolatile = false;
8767 bool IsFP = false;
8769 MaybeAlign Alignment;
8770
8771 if (EatIfPresent(lltok::kw_volatile))
8772 isVolatile = true;
8773
8774 switch (Lex.getKind()) {
8775 default:
8776 return tokError("expected binary operation in atomicrmw");
8790 break;
8793 break;
8796 break;
8797 case lltok::kw_usub_sat:
8799 break;
8800 case lltok::kw_fadd:
8802 IsFP = true;
8803 break;
8804 case lltok::kw_fsub:
8806 IsFP = true;
8807 break;
8808 case lltok::kw_fmax:
8810 IsFP = true;
8811 break;
8812 case lltok::kw_fmin:
8814 IsFP = true;
8815 break;
8816 case lltok::kw_fmaximum:
8818 IsFP = true;
8819 break;
8820 case lltok::kw_fminimum:
8822 IsFP = true;
8823 break;
8824 }
8825 Lex.Lex(); // Eat the operation.
8826
8827 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8828 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8829 parseTypeAndValue(Val, ValLoc, PFS) ||
8830 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8831 parseOptionalCommaAlign(Alignment, AteExtraComma))
8832 return true;
8833
8834 if (Ordering == AtomicOrdering::Unordered)
8835 return tokError("atomicrmw cannot be unordered");
8836 if (!Ptr->getType()->isPointerTy())
8837 return error(PtrLoc, "atomicrmw operand must be a pointer");
8838 if (Val->getType()->isScalableTy())
8839 return error(ValLoc, "atomicrmw operand may not be scalable");
8840
8842 if (!Val->getType()->isIntegerTy() &&
8843 !Val->getType()->isFloatingPointTy() &&
8844 !Val->getType()->isPointerTy()) {
8845 return error(
8846 ValLoc,
8848 " operand must be an integer, floating point, or pointer type");
8849 }
8850 } else if (IsFP) {
8851 if (!Val->getType()->isFPOrFPVectorTy()) {
8852 return error(ValLoc, "atomicrmw " +
8854 " operand must be a floating point type");
8855 }
8856 } else {
8857 if (!Val->getType()->isIntegerTy()) {
8858 return error(ValLoc, "atomicrmw " +
8860 " operand must be an integer");
8861 }
8862 }
8863
8864 unsigned Size =
8865 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8866 Val->getType());
8867 if (Size < 8 || (Size & (Size - 1)))
8868 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8869 " integer");
8870 const Align DefaultAlignment(
8871 PFS.getFunction().getDataLayout().getTypeStoreSize(
8872 Val->getType()));
8873 AtomicRMWInst *RMWI =
8874 new AtomicRMWInst(Operation, Ptr, Val,
8875 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8876 RMWI->setVolatile(isVolatile);
8877 Inst = RMWI;
8878 return AteExtraComma ? InstExtraComma : InstNormal;
8879}
8880
8881/// parseFence
8882/// ::= 'fence' 'singlethread'? AtomicOrdering
8883int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8886 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8887 return true;
8888
8889 if (Ordering == AtomicOrdering::Unordered)
8890 return tokError("fence cannot be unordered");
8891 if (Ordering == AtomicOrdering::Monotonic)
8892 return tokError("fence cannot be monotonic");
8893
8894 Inst = new FenceInst(Context, Ordering, SSID);
8895 return InstNormal;
8896}
8897
8898/// parseGetElementPtr
8899/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8900int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8901 Value *Ptr = nullptr;
8902 Value *Val = nullptr;
8903 LocTy Loc, EltLoc;
8904 GEPNoWrapFlags NW;
8905
8906 while (true) {
8907 if (EatIfPresent(lltok::kw_inbounds))
8909 else if (EatIfPresent(lltok::kw_nusw))
8911 else if (EatIfPresent(lltok::kw_nuw))
8913 else
8914 break;
8915 }
8916
8917 Type *Ty = nullptr;
8918 if (parseType(Ty) ||
8919 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8920 parseTypeAndValue(Ptr, Loc, PFS))
8921 return true;
8922
8923 Type *BaseType = Ptr->getType();
8924 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8925 if (!BasePointerType)
8926 return error(Loc, "base of getelementptr must be a pointer");
8927
8928 SmallVector<Value*, 16> Indices;
8929 bool AteExtraComma = false;
8930 // GEP returns a vector of pointers if at least one of parameters is a vector.
8931 // All vector parameters should have the same vector width.
8932 ElementCount GEPWidth = BaseType->isVectorTy()
8933 ? cast<VectorType>(BaseType)->getElementCount()
8935
8936 while (EatIfPresent(lltok::comma)) {
8937 if (Lex.getKind() == lltok::MetadataVar) {
8938 AteExtraComma = true;
8939 break;
8940 }
8941 if (parseTypeAndValue(Val, EltLoc, PFS))
8942 return true;
8943 if (!Val->getType()->isIntOrIntVectorTy())
8944 return error(EltLoc, "getelementptr index must be an integer");
8945
8946 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8947 ElementCount ValNumEl = ValVTy->getElementCount();
8948 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8949 return error(
8950 EltLoc,
8951 "getelementptr vector index has a wrong number of elements");
8952 GEPWidth = ValNumEl;
8953 }
8954 Indices.push_back(Val);
8955 }
8956
8957 SmallPtrSet<Type*, 4> Visited;
8958 if (!Indices.empty() && !Ty->isSized(&Visited))
8959 return error(Loc, "base element of getelementptr must be sized");
8960
8961 auto *STy = dyn_cast<StructType>(Ty);
8962 if (STy && STy->isScalableTy())
8963 return error(Loc, "getelementptr cannot target structure that contains "
8964 "scalable vector type");
8965
8966 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8967 return error(Loc, "invalid getelementptr indices");
8968 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8969 Inst = GEP;
8970 GEP->setNoWrapFlags(NW);
8971 return AteExtraComma ? InstExtraComma : InstNormal;
8972}
8973
8974/// parseExtractValue
8975/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8976int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8977 Value *Val; LocTy Loc;
8978 SmallVector<unsigned, 4> Indices;
8979 bool AteExtraComma;
8980 if (parseTypeAndValue(Val, Loc, PFS) ||
8981 parseIndexList(Indices, AteExtraComma))
8982 return true;
8983
8984 if (!Val->getType()->isAggregateType())
8985 return error(Loc, "extractvalue operand must be aggregate type");
8986
8987 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8988 return error(Loc, "invalid indices for extractvalue");
8989 Inst = ExtractValueInst::Create(Val, Indices);
8990 return AteExtraComma ? InstExtraComma : InstNormal;
8991}
8992
8993/// parseInsertValue
8994/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8995int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8996 Value *Val0, *Val1; LocTy Loc0, Loc1;
8997 SmallVector<unsigned, 4> Indices;
8998 bool AteExtraComma;
8999 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9000 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9001 parseTypeAndValue(Val1, Loc1, PFS) ||
9002 parseIndexList(Indices, AteExtraComma))
9003 return true;
9004
9005 if (!Val0->getType()->isAggregateType())
9006 return error(Loc0, "insertvalue operand must be aggregate type");
9007
9008 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9009 if (!IndexedType)
9010 return error(Loc0, "invalid indices for insertvalue");
9011 if (IndexedType != Val1->getType())
9012 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9013 getTypeString(Val1->getType()) + "' instead of '" +
9014 getTypeString(IndexedType) + "'");
9015 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9016 return AteExtraComma ? InstExtraComma : InstNormal;
9017}
9018
9019//===----------------------------------------------------------------------===//
9020// Embedded metadata.
9021//===----------------------------------------------------------------------===//
9022
9023/// parseMDNodeVector
9024/// ::= { Element (',' Element)* }
9025/// Element
9026/// ::= 'null' | Metadata
9027bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9028 if (parseToken(lltok::lbrace, "expected '{' here"))
9029 return true;
9030
9031 // Check for an empty list.
9032 if (EatIfPresent(lltok::rbrace))
9033 return false;
9034
9035 do {
9036 if (EatIfPresent(lltok::kw_null)) {
9037 Elts.push_back(nullptr);
9038 continue;
9039 }
9040
9041 Metadata *MD;
9042 if (parseMetadata(MD, nullptr))
9043 return true;
9044 Elts.push_back(MD);
9045 } while (EatIfPresent(lltok::comma));
9046
9047 return parseToken(lltok::rbrace, "expected end of metadata node");
9048}
9049
9050//===----------------------------------------------------------------------===//
9051// Use-list order directives.
9052//===----------------------------------------------------------------------===//
9053bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9054 SMLoc Loc) {
9055 if (!V->hasUseList())
9056 return false;
9057 if (V->use_empty())
9058 return error(Loc, "value has no uses");
9059
9060 unsigned NumUses = 0;
9061 SmallDenseMap<const Use *, unsigned, 16> Order;
9062 for (const Use &U : V->uses()) {
9063 if (++NumUses > Indexes.size())
9064 break;
9065 Order[&U] = Indexes[NumUses - 1];
9066 }
9067 if (NumUses < 2)
9068 return error(Loc, "value only has one use");
9069 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9070 return error(Loc,
9071 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9072
9073 V->sortUseList([&](const Use &L, const Use &R) {
9074 return Order.lookup(&L) < Order.lookup(&R);
9075 });
9076 return false;
9077}
9078
9079/// parseUseListOrderIndexes
9080/// ::= '{' uint32 (',' uint32)+ '}'
9081bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9082 SMLoc Loc = Lex.getLoc();
9083 if (parseToken(lltok::lbrace, "expected '{' here"))
9084 return true;
9085 if (Lex.getKind() == lltok::rbrace)
9086 return tokError("expected non-empty list of uselistorder indexes");
9087
9088 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9089 // indexes should be distinct numbers in the range [0, size-1], and should
9090 // not be in order.
9091 unsigned Offset = 0;
9092 unsigned Max = 0;
9093 bool IsOrdered = true;
9094 assert(Indexes.empty() && "Expected empty order vector");
9095 do {
9096 unsigned Index;
9097 if (parseUInt32(Index))
9098 return true;
9099
9100 // Update consistency checks.
9101 Offset += Index - Indexes.size();
9102 Max = std::max(Max, Index);
9103 IsOrdered &= Index == Indexes.size();
9104
9105 Indexes.push_back(Index);
9106 } while (EatIfPresent(lltok::comma));
9107
9108 if (parseToken(lltok::rbrace, "expected '}' here"))
9109 return true;
9110
9111 if (Indexes.size() < 2)
9112 return error(Loc, "expected >= 2 uselistorder indexes");
9113 if (Offset != 0 || Max >= Indexes.size())
9114 return error(Loc,
9115 "expected distinct uselistorder indexes in range [0, size)");
9116 if (IsOrdered)
9117 return error(Loc, "expected uselistorder indexes to change the order");
9118
9119 return false;
9120}
9121
9122/// parseUseListOrder
9123/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9124bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9125 SMLoc Loc = Lex.getLoc();
9126 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9127 return true;
9128
9129 Value *V;
9130 SmallVector<unsigned, 16> Indexes;
9131 if (parseTypeAndValue(V, PFS) ||
9132 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9133 parseUseListOrderIndexes(Indexes))
9134 return true;
9135
9136 return sortUseListOrder(V, Indexes, Loc);
9137}
9138
9139/// parseUseListOrderBB
9140/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9141bool LLParser::parseUseListOrderBB() {
9142 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9143 SMLoc Loc = Lex.getLoc();
9144 Lex.Lex();
9145
9146 ValID Fn, Label;
9147 SmallVector<unsigned, 16> Indexes;
9148 if (parseValID(Fn, /*PFS=*/nullptr) ||
9149 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9150 parseValID(Label, /*PFS=*/nullptr) ||
9151 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9152 parseUseListOrderIndexes(Indexes))
9153 return true;
9154
9155 // Check the function.
9156 GlobalValue *GV;
9157 if (Fn.Kind == ValID::t_GlobalName)
9158 GV = M->getNamedValue(Fn.StrVal);
9159 else if (Fn.Kind == ValID::t_GlobalID)
9160 GV = NumberedVals.get(Fn.UIntVal);
9161 else
9162 return error(Fn.Loc, "expected function name in uselistorder_bb");
9163 if (!GV)
9164 return error(Fn.Loc,
9165 "invalid function forward reference in uselistorder_bb");
9166 auto *F = dyn_cast<Function>(GV);
9167 if (!F)
9168 return error(Fn.Loc, "expected function name in uselistorder_bb");
9169 if (F->isDeclaration())
9170 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9171
9172 // Check the basic block.
9173 if (Label.Kind == ValID::t_LocalID)
9174 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9175 if (Label.Kind != ValID::t_LocalName)
9176 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9177 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9178 if (!V)
9179 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9180 if (!isa<BasicBlock>(V))
9181 return error(Label.Loc, "expected basic block in uselistorder_bb");
9182
9183 return sortUseListOrder(V, Indexes, Loc);
9184}
9185
9186/// ModuleEntry
9187/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9188/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9189bool LLParser::parseModuleEntry(unsigned ID) {
9190 assert(Lex.getKind() == lltok::kw_module);
9191 Lex.Lex();
9192
9193 std::string Path;
9194 if (parseToken(lltok::colon, "expected ':' here") ||
9195 parseToken(lltok::lparen, "expected '(' here") ||
9196 parseToken(lltok::kw_path, "expected 'path' here") ||
9197 parseToken(lltok::colon, "expected ':' here") ||
9198 parseStringConstant(Path) ||
9199 parseToken(lltok::comma, "expected ',' here") ||
9200 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9201 parseToken(lltok::colon, "expected ':' here") ||
9202 parseToken(lltok::lparen, "expected '(' here"))
9203 return true;
9204
9205 ModuleHash Hash;
9206 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9207 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9208 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9209 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9210 parseUInt32(Hash[4]))
9211 return true;
9212
9213 if (parseToken(lltok::rparen, "expected ')' here") ||
9214 parseToken(lltok::rparen, "expected ')' here"))
9215 return true;
9216
9217 auto ModuleEntry = Index->addModule(Path, Hash);
9218 ModuleIdMap[ID] = ModuleEntry->first();
9219
9220 return false;
9221}
9222
9223/// TypeIdEntry
9224/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9225bool LLParser::parseTypeIdEntry(unsigned ID) {
9226 assert(Lex.getKind() == lltok::kw_typeid);
9227 Lex.Lex();
9228
9229 std::string Name;
9230 if (parseToken(lltok::colon, "expected ':' here") ||
9231 parseToken(lltok::lparen, "expected '(' here") ||
9232 parseToken(lltok::kw_name, "expected 'name' here") ||
9233 parseToken(lltok::colon, "expected ':' here") ||
9234 parseStringConstant(Name))
9235 return true;
9236
9237 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9238 if (parseToken(lltok::comma, "expected ',' here") ||
9239 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9240 return true;
9241
9242 // Check if this ID was forward referenced, and if so, update the
9243 // corresponding GUIDs.
9244 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9245 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9246 for (auto TIDRef : FwdRefTIDs->second) {
9247 assert(!*TIDRef.first &&
9248 "Forward referenced type id GUID expected to be 0");
9249 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9250 }
9251 ForwardRefTypeIds.erase(FwdRefTIDs);
9252 }
9253
9254 return false;
9255}
9256
9257/// TypeIdSummary
9258/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9259bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9260 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9261 parseToken(lltok::colon, "expected ':' here") ||
9262 parseToken(lltok::lparen, "expected '(' here") ||
9263 parseTypeTestResolution(TIS.TTRes))
9264 return true;
9265
9266 if (EatIfPresent(lltok::comma)) {
9267 // Expect optional wpdResolutions field
9268 if (parseOptionalWpdResolutions(TIS.WPDRes))
9269 return true;
9270 }
9271
9272 if (parseToken(lltok::rparen, "expected ')' here"))
9273 return true;
9274
9275 return false;
9276}
9277
9279 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9280
9281/// TypeIdCompatibleVtableEntry
9282/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9283/// TypeIdCompatibleVtableInfo
9284/// ')'
9285bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9287 Lex.Lex();
9288
9289 std::string Name;
9290 if (parseToken(lltok::colon, "expected ':' here") ||
9291 parseToken(lltok::lparen, "expected '(' here") ||
9292 parseToken(lltok::kw_name, "expected 'name' here") ||
9293 parseToken(lltok::colon, "expected ':' here") ||
9294 parseStringConstant(Name))
9295 return true;
9296
9298 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9299 if (parseToken(lltok::comma, "expected ',' here") ||
9300 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9301 parseToken(lltok::colon, "expected ':' here") ||
9302 parseToken(lltok::lparen, "expected '(' here"))
9303 return true;
9304
9305 IdToIndexMapType IdToIndexMap;
9306 // parse each call edge
9307 do {
9309 if (parseToken(lltok::lparen, "expected '(' here") ||
9310 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9311 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9312 parseToken(lltok::comma, "expected ',' here"))
9313 return true;
9314
9315 LocTy Loc = Lex.getLoc();
9316 unsigned GVId;
9317 ValueInfo VI;
9318 if (parseGVReference(VI, GVId))
9319 return true;
9320
9321 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9322 // forward reference. We will save the location of the ValueInfo needing an
9323 // update, but can only do so once the std::vector is finalized.
9324 if (VI == EmptyVI)
9325 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9326 TI.push_back({Offset, VI});
9327
9328 if (parseToken(lltok::rparen, "expected ')' in call"))
9329 return true;
9330 } while (EatIfPresent(lltok::comma));
9331
9332 // Now that the TI vector is finalized, it is safe to save the locations
9333 // of any forward GV references that need updating later.
9334 for (auto I : IdToIndexMap) {
9335 auto &Infos = ForwardRefValueInfos[I.first];
9336 for (auto P : I.second) {
9337 assert(TI[P.first].VTableVI == EmptyVI &&
9338 "Forward referenced ValueInfo expected to be empty");
9339 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9340 }
9341 }
9342
9343 if (parseToken(lltok::rparen, "expected ')' here") ||
9344 parseToken(lltok::rparen, "expected ')' here"))
9345 return true;
9346
9347 // Check if this ID was forward referenced, and if so, update the
9348 // corresponding GUIDs.
9349 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9350 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9351 for (auto TIDRef : FwdRefTIDs->second) {
9352 assert(!*TIDRef.first &&
9353 "Forward referenced type id GUID expected to be 0");
9354 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9355 }
9356 ForwardRefTypeIds.erase(FwdRefTIDs);
9357 }
9358
9359 return false;
9360}
9361
9362/// TypeTestResolution
9363/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9364/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9365/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9366/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9367/// [',' 'inlinesBits' ':' UInt64]? ')'
9368bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9369 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9370 parseToken(lltok::colon, "expected ':' here") ||
9371 parseToken(lltok::lparen, "expected '(' here") ||
9372 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9373 parseToken(lltok::colon, "expected ':' here"))
9374 return true;
9375
9376 switch (Lex.getKind()) {
9377 case lltok::kw_unknown:
9379 break;
9380 case lltok::kw_unsat:
9382 break;
9385 break;
9386 case lltok::kw_inline:
9388 break;
9389 case lltok::kw_single:
9391 break;
9392 case lltok::kw_allOnes:
9394 break;
9395 default:
9396 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9397 }
9398 Lex.Lex();
9399
9400 if (parseToken(lltok::comma, "expected ',' here") ||
9401 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9402 parseToken(lltok::colon, "expected ':' here") ||
9403 parseUInt32(TTRes.SizeM1BitWidth))
9404 return true;
9405
9406 // parse optional fields
9407 while (EatIfPresent(lltok::comma)) {
9408 switch (Lex.getKind()) {
9410 Lex.Lex();
9411 if (parseToken(lltok::colon, "expected ':'") ||
9412 parseUInt64(TTRes.AlignLog2))
9413 return true;
9414 break;
9415 case lltok::kw_sizeM1:
9416 Lex.Lex();
9417 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9418 return true;
9419 break;
9420 case lltok::kw_bitMask: {
9421 unsigned Val;
9422 Lex.Lex();
9423 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9424 return true;
9425 assert(Val <= 0xff);
9426 TTRes.BitMask = (uint8_t)Val;
9427 break;
9428 }
9430 Lex.Lex();
9431 if (parseToken(lltok::colon, "expected ':'") ||
9432 parseUInt64(TTRes.InlineBits))
9433 return true;
9434 break;
9435 default:
9436 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9437 }
9438 }
9439
9440 if (parseToken(lltok::rparen, "expected ')' here"))
9441 return true;
9442
9443 return false;
9444}
9445
9446/// OptionalWpdResolutions
9447/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9448/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9449bool LLParser::parseOptionalWpdResolutions(
9450 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9451 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9452 parseToken(lltok::colon, "expected ':' here") ||
9453 parseToken(lltok::lparen, "expected '(' here"))
9454 return true;
9455
9456 do {
9457 uint64_t Offset;
9458 WholeProgramDevirtResolution WPDRes;
9459 if (parseToken(lltok::lparen, "expected '(' here") ||
9460 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9461 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9462 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9463 parseToken(lltok::rparen, "expected ')' here"))
9464 return true;
9465 WPDResMap[Offset] = WPDRes;
9466 } while (EatIfPresent(lltok::comma));
9467
9468 if (parseToken(lltok::rparen, "expected ')' here"))
9469 return true;
9470
9471 return false;
9472}
9473
9474/// WpdRes
9475/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9476/// [',' OptionalResByArg]? ')'
9477/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9478/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9479/// [',' OptionalResByArg]? ')'
9480/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9481/// [',' OptionalResByArg]? ')'
9482bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9483 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9484 parseToken(lltok::colon, "expected ':' here") ||
9485 parseToken(lltok::lparen, "expected '(' here") ||
9486 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9487 parseToken(lltok::colon, "expected ':' here"))
9488 return true;
9489
9490 switch (Lex.getKind()) {
9491 case lltok::kw_indir:
9493 break;
9496 break;
9499 break;
9500 default:
9501 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9502 }
9503 Lex.Lex();
9504
9505 // parse optional fields
9506 while (EatIfPresent(lltok::comma)) {
9507 switch (Lex.getKind()) {
9509 Lex.Lex();
9510 if (parseToken(lltok::colon, "expected ':' here") ||
9511 parseStringConstant(WPDRes.SingleImplName))
9512 return true;
9513 break;
9514 case lltok::kw_resByArg:
9515 if (parseOptionalResByArg(WPDRes.ResByArg))
9516 return true;
9517 break;
9518 default:
9519 return error(Lex.getLoc(),
9520 "expected optional WholeProgramDevirtResolution field");
9521 }
9522 }
9523
9524 if (parseToken(lltok::rparen, "expected ')' here"))
9525 return true;
9526
9527 return false;
9528}
9529
9530/// OptionalResByArg
9531/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9532/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9533/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9534/// 'virtualConstProp' )
9535/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9536/// [',' 'bit' ':' UInt32]? ')'
9537bool LLParser::parseOptionalResByArg(
9538 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9539 &ResByArg) {
9540 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9541 parseToken(lltok::colon, "expected ':' here") ||
9542 parseToken(lltok::lparen, "expected '(' here"))
9543 return true;
9544
9545 do {
9546 std::vector<uint64_t> Args;
9547 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9548 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9549 parseToken(lltok::colon, "expected ':' here") ||
9550 parseToken(lltok::lparen, "expected '(' here") ||
9551 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9552 parseToken(lltok::colon, "expected ':' here"))
9553 return true;
9554
9555 WholeProgramDevirtResolution::ByArg ByArg;
9556 switch (Lex.getKind()) {
9557 case lltok::kw_indir:
9559 break;
9562 break;
9565 break;
9568 break;
9569 default:
9570 return error(Lex.getLoc(),
9571 "unexpected WholeProgramDevirtResolution::ByArg kind");
9572 }
9573 Lex.Lex();
9574
9575 // parse optional fields
9576 while (EatIfPresent(lltok::comma)) {
9577 switch (Lex.getKind()) {
9578 case lltok::kw_info:
9579 Lex.Lex();
9580 if (parseToken(lltok::colon, "expected ':' here") ||
9581 parseUInt64(ByArg.Info))
9582 return true;
9583 break;
9584 case lltok::kw_byte:
9585 Lex.Lex();
9586 if (parseToken(lltok::colon, "expected ':' here") ||
9587 parseUInt32(ByArg.Byte))
9588 return true;
9589 break;
9590 case lltok::kw_bit:
9591 Lex.Lex();
9592 if (parseToken(lltok::colon, "expected ':' here") ||
9593 parseUInt32(ByArg.Bit))
9594 return true;
9595 break;
9596 default:
9597 return error(Lex.getLoc(),
9598 "expected optional whole program devirt field");
9599 }
9600 }
9601
9602 if (parseToken(lltok::rparen, "expected ')' here"))
9603 return true;
9604
9605 ResByArg[Args] = ByArg;
9606 } while (EatIfPresent(lltok::comma));
9607
9608 if (parseToken(lltok::rparen, "expected ')' here"))
9609 return true;
9610
9611 return false;
9612}
9613
9614/// OptionalResByArg
9615/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9616bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9617 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9618 parseToken(lltok::colon, "expected ':' here") ||
9619 parseToken(lltok::lparen, "expected '(' here"))
9620 return true;
9621
9622 do {
9623 uint64_t Val;
9624 if (parseUInt64(Val))
9625 return true;
9626 Args.push_back(Val);
9627 } while (EatIfPresent(lltok::comma));
9628
9629 if (parseToken(lltok::rparen, "expected ')' here"))
9630 return true;
9631
9632 return false;
9633}
9634
9635static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9636
9637static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9638 bool ReadOnly = Fwd->isReadOnly();
9639 bool WriteOnly = Fwd->isWriteOnly();
9640 assert(!(ReadOnly && WriteOnly));
9641 *Fwd = Resolved;
9642 if (ReadOnly)
9643 Fwd->setReadOnly();
9644 if (WriteOnly)
9645 Fwd->setWriteOnly();
9646}
9647
9648/// Stores the given Name/GUID and associated summary into the Index.
9649/// Also updates any forward references to the associated entry ID.
9650bool LLParser::addGlobalValueToIndex(
9651 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9652 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9653 // First create the ValueInfo utilizing the Name or GUID.
9654 ValueInfo VI;
9655 if (GUID != 0) {
9656 assert(Name.empty());
9657 VI = Index->getOrInsertValueInfo(GUID);
9658 } else {
9659 assert(!Name.empty());
9660 if (M) {
9661 auto *GV = M->getNamedValue(Name);
9662 if (!GV)
9663 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9664
9665 VI = Index->getOrInsertValueInfo(GV);
9666 } else {
9667 assert(
9668 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9669 "Need a source_filename to compute GUID for local");
9671 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9672 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9673 }
9674 }
9675
9676 // Resolve forward references from calls/refs
9677 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9678 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9679 for (auto VIRef : FwdRefVIs->second) {
9680 assert(VIRef.first->getRef() == FwdVIRef &&
9681 "Forward referenced ValueInfo expected to be empty");
9682 resolveFwdRef(VIRef.first, VI);
9683 }
9684 ForwardRefValueInfos.erase(FwdRefVIs);
9685 }
9686
9687 // Resolve forward references from aliases
9688 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9689 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9690 for (auto AliaseeRef : FwdRefAliasees->second) {
9691 assert(!AliaseeRef.first->hasAliasee() &&
9692 "Forward referencing alias already has aliasee");
9693 assert(Summary && "Aliasee must be a definition");
9694 AliaseeRef.first->setAliasee(VI, Summary.get());
9695 }
9696 ForwardRefAliasees.erase(FwdRefAliasees);
9697 }
9698
9699 // Add the summary if one was provided.
9700 if (Summary)
9701 Index->addGlobalValueSummary(VI, std::move(Summary));
9702
9703 // Save the associated ValueInfo for use in later references by ID.
9704 if (ID == NumberedValueInfos.size())
9705 NumberedValueInfos.push_back(VI);
9706 else {
9707 // Handle non-continuous numbers (to make test simplification easier).
9708 if (ID > NumberedValueInfos.size())
9709 NumberedValueInfos.resize(ID + 1);
9710 NumberedValueInfos[ID] = VI;
9711 }
9712
9713 return false;
9714}
9715
9716/// parseSummaryIndexFlags
9717/// ::= 'flags' ':' UInt64
9718bool LLParser::parseSummaryIndexFlags() {
9719 assert(Lex.getKind() == lltok::kw_flags);
9720 Lex.Lex();
9721
9722 if (parseToken(lltok::colon, "expected ':' here"))
9723 return true;
9724 uint64_t Flags;
9725 if (parseUInt64(Flags))
9726 return true;
9727 if (Index)
9728 Index->setFlags(Flags);
9729 return false;
9730}
9731
9732/// parseBlockCount
9733/// ::= 'blockcount' ':' UInt64
9734bool LLParser::parseBlockCount() {
9735 assert(Lex.getKind() == lltok::kw_blockcount);
9736 Lex.Lex();
9737
9738 if (parseToken(lltok::colon, "expected ':' here"))
9739 return true;
9740 uint64_t BlockCount;
9741 if (parseUInt64(BlockCount))
9742 return true;
9743 if (Index)
9744 Index->setBlockCount(BlockCount);
9745 return false;
9746}
9747
9748/// parseGVEntry
9749/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9750/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9751/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9752bool LLParser::parseGVEntry(unsigned ID) {
9753 assert(Lex.getKind() == lltok::kw_gv);
9754 Lex.Lex();
9755
9756 if (parseToken(lltok::colon, "expected ':' here") ||
9757 parseToken(lltok::lparen, "expected '(' here"))
9758 return true;
9759
9760 LocTy Loc = Lex.getLoc();
9761 std::string Name;
9763 switch (Lex.getKind()) {
9764 case lltok::kw_name:
9765 Lex.Lex();
9766 if (parseToken(lltok::colon, "expected ':' here") ||
9767 parseStringConstant(Name))
9768 return true;
9769 // Can't create GUID/ValueInfo until we have the linkage.
9770 break;
9771 case lltok::kw_guid:
9772 Lex.Lex();
9773 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9774 return true;
9775 break;
9776 default:
9777 return error(Lex.getLoc(), "expected name or guid tag");
9778 }
9779
9780 if (!EatIfPresent(lltok::comma)) {
9781 // No summaries. Wrap up.
9782 if (parseToken(lltok::rparen, "expected ')' here"))
9783 return true;
9784 // This was created for a call to an external or indirect target.
9785 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9786 // created for indirect calls with VP. A Name with no GUID came from
9787 // an external definition. We pass ExternalLinkage since that is only
9788 // used when the GUID must be computed from Name, and in that case
9789 // the symbol must have external linkage.
9790 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9791 nullptr, Loc);
9792 }
9793
9794 // Have a list of summaries
9795 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9796 parseToken(lltok::colon, "expected ':' here") ||
9797 parseToken(lltok::lparen, "expected '(' here"))
9798 return true;
9799 do {
9800 switch (Lex.getKind()) {
9801 case lltok::kw_function:
9802 if (parseFunctionSummary(Name, GUID, ID))
9803 return true;
9804 break;
9805 case lltok::kw_variable:
9806 if (parseVariableSummary(Name, GUID, ID))
9807 return true;
9808 break;
9809 case lltok::kw_alias:
9810 if (parseAliasSummary(Name, GUID, ID))
9811 return true;
9812 break;
9813 default:
9814 return error(Lex.getLoc(), "expected summary type");
9815 }
9816 } while (EatIfPresent(lltok::comma));
9817
9818 if (parseToken(lltok::rparen, "expected ')' here") ||
9819 parseToken(lltok::rparen, "expected ')' here"))
9820 return true;
9821
9822 return false;
9823}
9824
9825/// FunctionSummary
9826/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9827/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9828/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9829/// [',' OptionalRefs]? ')'
9830bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9831 unsigned ID) {
9832 LocTy Loc = Lex.getLoc();
9833 assert(Lex.getKind() == lltok::kw_function);
9834 Lex.Lex();
9835
9836 StringRef ModulePath;
9837 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9839 /*NotEligibleToImport=*/false,
9840 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9842 unsigned InstCount;
9844 FunctionSummary::TypeIdInfo TypeIdInfo;
9845 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9847 std::vector<CallsiteInfo> Callsites;
9848 std::vector<AllocInfo> Allocs;
9849 // Default is all-zeros (conservative values).
9850 FunctionSummary::FFlags FFlags = {};
9851 if (parseToken(lltok::colon, "expected ':' here") ||
9852 parseToken(lltok::lparen, "expected '(' here") ||
9853 parseModuleReference(ModulePath) ||
9854 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9855 parseToken(lltok::comma, "expected ',' here") ||
9856 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9857 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9858 return true;
9859
9860 // parse optional fields
9861 while (EatIfPresent(lltok::comma)) {
9862 switch (Lex.getKind()) {
9864 if (parseOptionalFFlags(FFlags))
9865 return true;
9866 break;
9867 case lltok::kw_calls:
9868 if (parseOptionalCalls(Calls))
9869 return true;
9870 break;
9872 if (parseOptionalTypeIdInfo(TypeIdInfo))
9873 return true;
9874 break;
9875 case lltok::kw_refs:
9876 if (parseOptionalRefs(Refs))
9877 return true;
9878 break;
9879 case lltok::kw_params:
9880 if (parseOptionalParamAccesses(ParamAccesses))
9881 return true;
9882 break;
9883 case lltok::kw_allocs:
9884 if (parseOptionalAllocs(Allocs))
9885 return true;
9886 break;
9888 if (parseOptionalCallsites(Callsites))
9889 return true;
9890 break;
9891 default:
9892 return error(Lex.getLoc(), "expected optional function summary field");
9893 }
9894 }
9895
9896 if (parseToken(lltok::rparen, "expected ')' here"))
9897 return true;
9898
9899 auto FS = std::make_unique<FunctionSummary>(
9900 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9901 std::move(TypeIdInfo.TypeTests),
9902 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9903 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9904 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9905 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9906 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9907
9908 FS->setModulePath(ModulePath);
9909
9910 return addGlobalValueToIndex(Name, GUID,
9912 std::move(FS), Loc);
9913}
9914
9915/// VariableSummary
9916/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9917/// [',' OptionalRefs]? ')'
9918bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9919 unsigned ID) {
9920 LocTy Loc = Lex.getLoc();
9921 assert(Lex.getKind() == lltok::kw_variable);
9922 Lex.Lex();
9923
9924 StringRef ModulePath;
9925 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9927 /*NotEligibleToImport=*/false,
9928 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9930 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9931 /* WriteOnly */ false,
9932 /* Constant */ false,
9935 VTableFuncList VTableFuncs;
9936 if (parseToken(lltok::colon, "expected ':' here") ||
9937 parseToken(lltok::lparen, "expected '(' here") ||
9938 parseModuleReference(ModulePath) ||
9939 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9940 parseToken(lltok::comma, "expected ',' here") ||
9941 parseGVarFlags(GVarFlags))
9942 return true;
9943
9944 // parse optional fields
9945 while (EatIfPresent(lltok::comma)) {
9946 switch (Lex.getKind()) {
9948 if (parseOptionalVTableFuncs(VTableFuncs))
9949 return true;
9950 break;
9951 case lltok::kw_refs:
9952 if (parseOptionalRefs(Refs))
9953 return true;
9954 break;
9955 default:
9956 return error(Lex.getLoc(), "expected optional variable summary field");
9957 }
9958 }
9959
9960 if (parseToken(lltok::rparen, "expected ')' here"))
9961 return true;
9962
9963 auto GS =
9964 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9965
9966 GS->setModulePath(ModulePath);
9967 GS->setVTableFuncs(std::move(VTableFuncs));
9968
9969 return addGlobalValueToIndex(Name, GUID,
9971 std::move(GS), Loc);
9972}
9973
9974/// AliasSummary
9975/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9976/// 'aliasee' ':' GVReference ')'
9977bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9978 unsigned ID) {
9979 assert(Lex.getKind() == lltok::kw_alias);
9980 LocTy Loc = Lex.getLoc();
9981 Lex.Lex();
9982
9983 StringRef ModulePath;
9984 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9986 /*NotEligibleToImport=*/false,
9987 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9989 if (parseToken(lltok::colon, "expected ':' here") ||
9990 parseToken(lltok::lparen, "expected '(' here") ||
9991 parseModuleReference(ModulePath) ||
9992 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9993 parseToken(lltok::comma, "expected ',' here") ||
9994 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9995 parseToken(lltok::colon, "expected ':' here"))
9996 return true;
9997
9998 ValueInfo AliaseeVI;
9999 unsigned GVId;
10000 auto AS = std::make_unique<AliasSummary>(GVFlags);
10001 AS->setModulePath(ModulePath);
10002
10003 if (!EatIfPresent(lltok::kw_null)) {
10004 if (parseGVReference(AliaseeVI, GVId))
10005 return true;
10006
10007 // Record forward reference if the aliasee is not parsed yet.
10008 if (AliaseeVI.getRef() == FwdVIRef) {
10009 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10010 } else {
10011 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10012 assert(Summary && "Aliasee must be a definition");
10013 AS->setAliasee(AliaseeVI, Summary);
10014 }
10015 }
10016
10017 if (parseToken(lltok::rparen, "expected ')' here"))
10018 return true;
10019
10020 return addGlobalValueToIndex(Name, GUID,
10022 std::move(AS), Loc);
10023}
10024
10025/// Flag
10026/// ::= [0|1]
10027bool LLParser::parseFlag(unsigned &Val) {
10028 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10029 return tokError("expected integer");
10030 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10031 Lex.Lex();
10032 return false;
10033}
10034
10035/// OptionalFFlags
10036/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10037/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10038/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10039/// [',' 'noInline' ':' Flag]? ')'
10040/// [',' 'alwaysInline' ':' Flag]? ')'
10041/// [',' 'noUnwind' ':' Flag]? ')'
10042/// [',' 'mayThrow' ':' Flag]? ')'
10043/// [',' 'hasUnknownCall' ':' Flag]? ')'
10044/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10045
10046bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10047 assert(Lex.getKind() == lltok::kw_funcFlags);
10048 Lex.Lex();
10049
10050 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10051 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10052 return true;
10053
10054 do {
10055 unsigned Val = 0;
10056 switch (Lex.getKind()) {
10057 case lltok::kw_readNone:
10058 Lex.Lex();
10059 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10060 return true;
10061 FFlags.ReadNone = Val;
10062 break;
10063 case lltok::kw_readOnly:
10064 Lex.Lex();
10065 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10066 return true;
10067 FFlags.ReadOnly = Val;
10068 break;
10070 Lex.Lex();
10071 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10072 return true;
10073 FFlags.NoRecurse = Val;
10074 break;
10076 Lex.Lex();
10077 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10078 return true;
10079 FFlags.ReturnDoesNotAlias = Val;
10080 break;
10081 case lltok::kw_noInline:
10082 Lex.Lex();
10083 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10084 return true;
10085 FFlags.NoInline = Val;
10086 break;
10088 Lex.Lex();
10089 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10090 return true;
10091 FFlags.AlwaysInline = Val;
10092 break;
10093 case lltok::kw_noUnwind:
10094 Lex.Lex();
10095 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10096 return true;
10097 FFlags.NoUnwind = Val;
10098 break;
10099 case lltok::kw_mayThrow:
10100 Lex.Lex();
10101 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10102 return true;
10103 FFlags.MayThrow = Val;
10104 break;
10106 Lex.Lex();
10107 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10108 return true;
10109 FFlags.HasUnknownCall = Val;
10110 break;
10112 Lex.Lex();
10113 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10114 return true;
10115 FFlags.MustBeUnreachable = Val;
10116 break;
10117 default:
10118 return error(Lex.getLoc(), "expected function flag type");
10119 }
10120 } while (EatIfPresent(lltok::comma));
10121
10122 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10123 return true;
10124
10125 return false;
10126}
10127
10128/// OptionalCalls
10129/// := 'calls' ':' '(' Call [',' Call]* ')'
10130/// Call ::= '(' 'callee' ':' GVReference
10131/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10132/// [ ',' 'tail' ]? ')'
10133bool LLParser::parseOptionalCalls(
10134 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10135 assert(Lex.getKind() == lltok::kw_calls);
10136 Lex.Lex();
10137
10138 if (parseToken(lltok::colon, "expected ':' in calls") ||
10139 parseToken(lltok::lparen, "expected '(' in calls"))
10140 return true;
10141
10142 IdToIndexMapType IdToIndexMap;
10143 // parse each call edge
10144 do {
10145 ValueInfo VI;
10146 if (parseToken(lltok::lparen, "expected '(' in call") ||
10147 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10148 parseToken(lltok::colon, "expected ':'"))
10149 return true;
10150
10151 LocTy Loc = Lex.getLoc();
10152 unsigned GVId;
10153 if (parseGVReference(VI, GVId))
10154 return true;
10155
10157 unsigned RelBF = 0;
10158 unsigned HasTailCall = false;
10159
10160 // parse optional fields
10161 while (EatIfPresent(lltok::comma)) {
10162 switch (Lex.getKind()) {
10163 case lltok::kw_hotness:
10164 Lex.Lex();
10165 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10166 return true;
10167 break;
10168 case lltok::kw_relbf:
10169 Lex.Lex();
10170 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10171 return true;
10172 break;
10173 case lltok::kw_tail:
10174 Lex.Lex();
10175 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10176 return true;
10177 break;
10178 default:
10179 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10180 }
10181 }
10182 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
10183 return tokError("Expected only one of hotness or relbf");
10184 // Keep track of the Call array index needing a forward reference.
10185 // We will save the location of the ValueInfo needing an update, but
10186 // can only do so once the std::vector is finalized.
10187 if (VI.getRef() == FwdVIRef)
10188 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10189 Calls.push_back(
10190 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
10191
10192 if (parseToken(lltok::rparen, "expected ')' in call"))
10193 return true;
10194 } while (EatIfPresent(lltok::comma));
10195
10196 // Now that the Calls vector is finalized, it is safe to save the locations
10197 // of any forward GV references that need updating later.
10198 for (auto I : IdToIndexMap) {
10199 auto &Infos = ForwardRefValueInfos[I.first];
10200 for (auto P : I.second) {
10201 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10202 "Forward referenced ValueInfo expected to be empty");
10203 Infos.emplace_back(&Calls[P.first].first, P.second);
10204 }
10205 }
10206
10207 if (parseToken(lltok::rparen, "expected ')' in calls"))
10208 return true;
10209
10210 return false;
10211}
10212
10213/// Hotness
10214/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10215bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10216 switch (Lex.getKind()) {
10217 case lltok::kw_unknown:
10219 break;
10220 case lltok::kw_cold:
10222 break;
10223 case lltok::kw_none:
10225 break;
10226 case lltok::kw_hot:
10228 break;
10229 case lltok::kw_critical:
10231 break;
10232 default:
10233 return error(Lex.getLoc(), "invalid call edge hotness");
10234 }
10235 Lex.Lex();
10236 return false;
10237}
10238
10239/// OptionalVTableFuncs
10240/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10241/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10242bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10243 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10244 Lex.Lex();
10245
10246 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10247 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10248 return true;
10249
10250 IdToIndexMapType IdToIndexMap;
10251 // parse each virtual function pair
10252 do {
10253 ValueInfo VI;
10254 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10255 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10256 parseToken(lltok::colon, "expected ':'"))
10257 return true;
10258
10259 LocTy Loc = Lex.getLoc();
10260 unsigned GVId;
10261 if (parseGVReference(VI, GVId))
10262 return true;
10263
10264 uint64_t Offset;
10265 if (parseToken(lltok::comma, "expected comma") ||
10266 parseToken(lltok::kw_offset, "expected offset") ||
10267 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10268 return true;
10269
10270 // Keep track of the VTableFuncs array index needing a forward reference.
10271 // We will save the location of the ValueInfo needing an update, but
10272 // can only do so once the std::vector is finalized.
10273 if (VI == EmptyVI)
10274 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10275 VTableFuncs.push_back({VI, Offset});
10276
10277 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10278 return true;
10279 } while (EatIfPresent(lltok::comma));
10280
10281 // Now that the VTableFuncs vector is finalized, it is safe to save the
10282 // locations of any forward GV references that need updating later.
10283 for (auto I : IdToIndexMap) {
10284 auto &Infos = ForwardRefValueInfos[I.first];
10285 for (auto P : I.second) {
10286 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10287 "Forward referenced ValueInfo expected to be empty");
10288 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10289 }
10290 }
10291
10292 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10293 return true;
10294
10295 return false;
10296}
10297
10298/// ParamNo := 'param' ':' UInt64
10299bool LLParser::parseParamNo(uint64_t &ParamNo) {
10300 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10301 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10302 return true;
10303 return false;
10304}
10305
10306/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10307bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10308 APSInt Lower;
10309 APSInt Upper;
10310 auto ParseAPSInt = [&](APSInt &Val) {
10311 if (Lex.getKind() != lltok::APSInt)
10312 return tokError("expected integer");
10313 Val = Lex.getAPSIntVal();
10314 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10315 Val.setIsSigned(true);
10316 Lex.Lex();
10317 return false;
10318 };
10319 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10320 parseToken(lltok::colon, "expected ':' here") ||
10321 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10322 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10323 parseToken(lltok::rsquare, "expected ']' here"))
10324 return true;
10325
10326 ++Upper;
10327 Range =
10328 (Lower == Upper && !Lower.isMaxValue())
10329 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10330 : ConstantRange(Lower, Upper);
10331
10332 return false;
10333}
10334
10335/// ParamAccessCall
10336/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10337bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10338 IdLocListType &IdLocList) {
10339 if (parseToken(lltok::lparen, "expected '(' here") ||
10340 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10341 parseToken(lltok::colon, "expected ':' here"))
10342 return true;
10343
10344 unsigned GVId;
10345 ValueInfo VI;
10346 LocTy Loc = Lex.getLoc();
10347 if (parseGVReference(VI, GVId))
10348 return true;
10349
10350 Call.Callee = VI;
10351 IdLocList.emplace_back(GVId, Loc);
10352
10353 if (parseToken(lltok::comma, "expected ',' here") ||
10354 parseParamNo(Call.ParamNo) ||
10355 parseToken(lltok::comma, "expected ',' here") ||
10356 parseParamAccessOffset(Call.Offsets))
10357 return true;
10358
10359 if (parseToken(lltok::rparen, "expected ')' here"))
10360 return true;
10361
10362 return false;
10363}
10364
10365/// ParamAccess
10366/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10367/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10368bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10369 IdLocListType &IdLocList) {
10370 if (parseToken(lltok::lparen, "expected '(' here") ||
10371 parseParamNo(Param.ParamNo) ||
10372 parseToken(lltok::comma, "expected ',' here") ||
10373 parseParamAccessOffset(Param.Use))
10374 return true;
10375
10376 if (EatIfPresent(lltok::comma)) {
10377 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10378 parseToken(lltok::colon, "expected ':' here") ||
10379 parseToken(lltok::lparen, "expected '(' here"))
10380 return true;
10381 do {
10382 FunctionSummary::ParamAccess::Call Call;
10383 if (parseParamAccessCall(Call, IdLocList))
10384 return true;
10385 Param.Calls.push_back(Call);
10386 } while (EatIfPresent(lltok::comma));
10387
10388 if (parseToken(lltok::rparen, "expected ')' here"))
10389 return true;
10390 }
10391
10392 if (parseToken(lltok::rparen, "expected ')' here"))
10393 return true;
10394
10395 return false;
10396}
10397
10398/// OptionalParamAccesses
10399/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10400bool LLParser::parseOptionalParamAccesses(
10401 std::vector<FunctionSummary::ParamAccess> &Params) {
10402 assert(Lex.getKind() == lltok::kw_params);
10403 Lex.Lex();
10404
10405 if (parseToken(lltok::colon, "expected ':' here") ||
10406 parseToken(lltok::lparen, "expected '(' here"))
10407 return true;
10408
10409 IdLocListType VContexts;
10410 size_t CallsNum = 0;
10411 do {
10412 FunctionSummary::ParamAccess ParamAccess;
10413 if (parseParamAccess(ParamAccess, VContexts))
10414 return true;
10415 CallsNum += ParamAccess.Calls.size();
10416 assert(VContexts.size() == CallsNum);
10417 (void)CallsNum;
10418 Params.emplace_back(std::move(ParamAccess));
10419 } while (EatIfPresent(lltok::comma));
10420
10421 if (parseToken(lltok::rparen, "expected ')' here"))
10422 return true;
10423
10424 // Now that the Params is finalized, it is safe to save the locations
10425 // of any forward GV references that need updating later.
10426 IdLocListType::const_iterator ItContext = VContexts.begin();
10427 for (auto &PA : Params) {
10428 for (auto &C : PA.Calls) {
10429 if (C.Callee.getRef() == FwdVIRef)
10430 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10431 ItContext->second);
10432 ++ItContext;
10433 }
10434 }
10435 assert(ItContext == VContexts.end());
10436
10437 return false;
10438}
10439
10440/// OptionalRefs
10441/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10442bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10443 assert(Lex.getKind() == lltok::kw_refs);
10444 Lex.Lex();
10445
10446 if (parseToken(lltok::colon, "expected ':' in refs") ||
10447 parseToken(lltok::lparen, "expected '(' in refs"))
10448 return true;
10449
10450 struct ValueContext {
10451 ValueInfo VI;
10452 unsigned GVId;
10453 LocTy Loc;
10454 };
10455 std::vector<ValueContext> VContexts;
10456 // parse each ref edge
10457 do {
10458 ValueContext VC;
10459 VC.Loc = Lex.getLoc();
10460 if (parseGVReference(VC.VI, VC.GVId))
10461 return true;
10462 VContexts.push_back(VC);
10463 } while (EatIfPresent(lltok::comma));
10464
10465 // Sort value contexts so that ones with writeonly
10466 // and readonly ValueInfo are at the end of VContexts vector.
10467 // See FunctionSummary::specialRefCounts()
10468 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10469 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10470 });
10471
10472 IdToIndexMapType IdToIndexMap;
10473 for (auto &VC : VContexts) {
10474 // Keep track of the Refs array index needing a forward reference.
10475 // We will save the location of the ValueInfo needing an update, but
10476 // can only do so once the std::vector is finalized.
10477 if (VC.VI.getRef() == FwdVIRef)
10478 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10479 Refs.push_back(VC.VI);
10480 }
10481
10482 // Now that the Refs vector is finalized, it is safe to save the locations
10483 // of any forward GV references that need updating later.
10484 for (auto I : IdToIndexMap) {
10485 auto &Infos = ForwardRefValueInfos[I.first];
10486 for (auto P : I.second) {
10487 assert(Refs[P.first].getRef() == FwdVIRef &&
10488 "Forward referenced ValueInfo expected to be empty");
10489 Infos.emplace_back(&Refs[P.first], P.second);
10490 }
10491 }
10492
10493 if (parseToken(lltok::rparen, "expected ')' in refs"))
10494 return true;
10495
10496 return false;
10497}
10498
10499/// OptionalTypeIdInfo
10500/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10501/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10502/// [',' TypeCheckedLoadConstVCalls]? ')'
10503bool LLParser::parseOptionalTypeIdInfo(
10504 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10505 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10506 Lex.Lex();
10507
10508 if (parseToken(lltok::colon, "expected ':' here") ||
10509 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10510 return true;
10511
10512 do {
10513 switch (Lex.getKind()) {
10515 if (parseTypeTests(TypeIdInfo.TypeTests))
10516 return true;
10517 break;
10519 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10520 TypeIdInfo.TypeTestAssumeVCalls))
10521 return true;
10522 break;
10524 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10525 TypeIdInfo.TypeCheckedLoadVCalls))
10526 return true;
10527 break;
10529 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10530 TypeIdInfo.TypeTestAssumeConstVCalls))
10531 return true;
10532 break;
10534 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10535 TypeIdInfo.TypeCheckedLoadConstVCalls))
10536 return true;
10537 break;
10538 default:
10539 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10540 }
10541 } while (EatIfPresent(lltok::comma));
10542
10543 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10544 return true;
10545
10546 return false;
10547}
10548
10549/// TypeTests
10550/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10551/// [',' (SummaryID | UInt64)]* ')'
10552bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10553 assert(Lex.getKind() == lltok::kw_typeTests);
10554 Lex.Lex();
10555
10556 if (parseToken(lltok::colon, "expected ':' here") ||
10557 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10558 return true;
10559
10560 IdToIndexMapType IdToIndexMap;
10561 do {
10563 if (Lex.getKind() == lltok::SummaryID) {
10564 unsigned ID = Lex.getUIntVal();
10565 LocTy Loc = Lex.getLoc();
10566 // Keep track of the TypeTests array index needing a forward reference.
10567 // We will save the location of the GUID needing an update, but
10568 // can only do so once the std::vector is finalized.
10569 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10570 Lex.Lex();
10571 } else if (parseUInt64(GUID))
10572 return true;
10573 TypeTests.push_back(GUID);
10574 } while (EatIfPresent(lltok::comma));
10575
10576 // Now that the TypeTests vector is finalized, it is safe to save the
10577 // locations of any forward GV references that need updating later.
10578 for (auto I : IdToIndexMap) {
10579 auto &Ids = ForwardRefTypeIds[I.first];
10580 for (auto P : I.second) {
10581 assert(TypeTests[P.first] == 0 &&
10582 "Forward referenced type id GUID expected to be 0");
10583 Ids.emplace_back(&TypeTests[P.first], P.second);
10584 }
10585 }
10586
10587 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10588 return true;
10589
10590 return false;
10591}
10592
10593/// VFuncIdList
10594/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10595bool LLParser::parseVFuncIdList(
10596 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10597 assert(Lex.getKind() == Kind);
10598 Lex.Lex();
10599
10600 if (parseToken(lltok::colon, "expected ':' here") ||
10601 parseToken(lltok::lparen, "expected '(' here"))
10602 return true;
10603
10604 IdToIndexMapType IdToIndexMap;
10605 do {
10606 FunctionSummary::VFuncId VFuncId;
10607 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10608 return true;
10609 VFuncIdList.push_back(VFuncId);
10610 } while (EatIfPresent(lltok::comma));
10611
10612 if (parseToken(lltok::rparen, "expected ')' here"))
10613 return true;
10614
10615 // Now that the VFuncIdList vector is finalized, it is safe to save the
10616 // locations of any forward GV references that need updating later.
10617 for (auto I : IdToIndexMap) {
10618 auto &Ids = ForwardRefTypeIds[I.first];
10619 for (auto P : I.second) {
10620 assert(VFuncIdList[P.first].GUID == 0 &&
10621 "Forward referenced type id GUID expected to be 0");
10622 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10623 }
10624 }
10625
10626 return false;
10627}
10628
10629/// ConstVCallList
10630/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10631bool LLParser::parseConstVCallList(
10632 lltok::Kind Kind,
10633 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10634 assert(Lex.getKind() == Kind);
10635 Lex.Lex();
10636
10637 if (parseToken(lltok::colon, "expected ':' here") ||
10638 parseToken(lltok::lparen, "expected '(' here"))
10639 return true;
10640
10641 IdToIndexMapType IdToIndexMap;
10642 do {
10643 FunctionSummary::ConstVCall ConstVCall;
10644 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10645 return true;
10646 ConstVCallList.push_back(ConstVCall);
10647 } while (EatIfPresent(lltok::comma));
10648
10649 if (parseToken(lltok::rparen, "expected ')' here"))
10650 return true;
10651
10652 // Now that the ConstVCallList vector is finalized, it is safe to save the
10653 // locations of any forward GV references that need updating later.
10654 for (auto I : IdToIndexMap) {
10655 auto &Ids = ForwardRefTypeIds[I.first];
10656 for (auto P : I.second) {
10657 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10658 "Forward referenced type id GUID expected to be 0");
10659 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10660 }
10661 }
10662
10663 return false;
10664}
10665
10666/// ConstVCall
10667/// ::= '(' VFuncId ',' Args ')'
10668bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10669 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10670 if (parseToken(lltok::lparen, "expected '(' here") ||
10671 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10672 return true;
10673
10674 if (EatIfPresent(lltok::comma))
10675 if (parseArgs(ConstVCall.Args))
10676 return true;
10677
10678 if (parseToken(lltok::rparen, "expected ')' here"))
10679 return true;
10680
10681 return false;
10682}
10683
10684/// VFuncId
10685/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10686/// 'offset' ':' UInt64 ')'
10687bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10688 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10689 assert(Lex.getKind() == lltok::kw_vFuncId);
10690 Lex.Lex();
10691
10692 if (parseToken(lltok::colon, "expected ':' here") ||
10693 parseToken(lltok::lparen, "expected '(' here"))
10694 return true;
10695
10696 if (Lex.getKind() == lltok::SummaryID) {
10697 VFuncId.GUID = 0;
10698 unsigned ID = Lex.getUIntVal();
10699 LocTy Loc = Lex.getLoc();
10700 // Keep track of the array index needing a forward reference.
10701 // We will save the location of the GUID needing an update, but
10702 // can only do so once the caller's std::vector is finalized.
10703 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10704 Lex.Lex();
10705 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10706 parseToken(lltok::colon, "expected ':' here") ||
10707 parseUInt64(VFuncId.GUID))
10708 return true;
10709
10710 if (parseToken(lltok::comma, "expected ',' here") ||
10711 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10712 parseToken(lltok::colon, "expected ':' here") ||
10713 parseUInt64(VFuncId.Offset) ||
10714 parseToken(lltok::rparen, "expected ')' here"))
10715 return true;
10716
10717 return false;
10718}
10719
10720/// GVFlags
10721/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10722/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10723/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10724/// 'canAutoHide' ':' Flag ',' ')'
10725bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10726 assert(Lex.getKind() == lltok::kw_flags);
10727 Lex.Lex();
10728
10729 if (parseToken(lltok::colon, "expected ':' here") ||
10730 parseToken(lltok::lparen, "expected '(' here"))
10731 return true;
10732
10733 do {
10734 unsigned Flag = 0;
10735 switch (Lex.getKind()) {
10736 case lltok::kw_linkage:
10737 Lex.Lex();
10738 if (parseToken(lltok::colon, "expected ':'"))
10739 return true;
10740 bool HasLinkage;
10741 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10742 assert(HasLinkage && "Linkage not optional in summary entry");
10743 Lex.Lex();
10744 break;
10746 Lex.Lex();
10747 if (parseToken(lltok::colon, "expected ':'"))
10748 return true;
10749 parseOptionalVisibility(Flag);
10750 GVFlags.Visibility = Flag;
10751 break;
10753 Lex.Lex();
10754 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10755 return true;
10756 GVFlags.NotEligibleToImport = Flag;
10757 break;
10758 case lltok::kw_live:
10759 Lex.Lex();
10760 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10761 return true;
10762 GVFlags.Live = Flag;
10763 break;
10764 case lltok::kw_dsoLocal:
10765 Lex.Lex();
10766 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10767 return true;
10768 GVFlags.DSOLocal = Flag;
10769 break;
10771 Lex.Lex();
10772 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10773 return true;
10774 GVFlags.CanAutoHide = Flag;
10775 break;
10777 Lex.Lex();
10778 if (parseToken(lltok::colon, "expected ':'"))
10779 return true;
10781 if (parseOptionalImportType(Lex.getKind(), IK))
10782 return true;
10783 GVFlags.ImportType = static_cast<unsigned>(IK);
10784 Lex.Lex();
10785 break;
10786 default:
10787 return error(Lex.getLoc(), "expected gv flag type");
10788 }
10789 } while (EatIfPresent(lltok::comma));
10790
10791 if (parseToken(lltok::rparen, "expected ')' here"))
10792 return true;
10793
10794 return false;
10795}
10796
10797/// GVarFlags
10798/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10799/// ',' 'writeonly' ':' Flag
10800/// ',' 'constant' ':' Flag ')'
10801bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10802 assert(Lex.getKind() == lltok::kw_varFlags);
10803 Lex.Lex();
10804
10805 if (parseToken(lltok::colon, "expected ':' here") ||
10806 parseToken(lltok::lparen, "expected '(' here"))
10807 return true;
10808
10809 auto ParseRest = [this](unsigned int &Val) {
10810 Lex.Lex();
10811 if (parseToken(lltok::colon, "expected ':'"))
10812 return true;
10813 return parseFlag(Val);
10814 };
10815
10816 do {
10817 unsigned Flag = 0;
10818 switch (Lex.getKind()) {
10819 case lltok::kw_readonly:
10820 if (ParseRest(Flag))
10821 return true;
10822 GVarFlags.MaybeReadOnly = Flag;
10823 break;
10824 case lltok::kw_writeonly:
10825 if (ParseRest(Flag))
10826 return true;
10827 GVarFlags.MaybeWriteOnly = Flag;
10828 break;
10829 case lltok::kw_constant:
10830 if (ParseRest(Flag))
10831 return true;
10832 GVarFlags.Constant = Flag;
10833 break;
10835 if (ParseRest(Flag))
10836 return true;
10837 GVarFlags.VCallVisibility = Flag;
10838 break;
10839 default:
10840 return error(Lex.getLoc(), "expected gvar flag type");
10841 }
10842 } while (EatIfPresent(lltok::comma));
10843 return parseToken(lltok::rparen, "expected ')' here");
10844}
10845
10846/// ModuleReference
10847/// ::= 'module' ':' UInt
10848bool LLParser::parseModuleReference(StringRef &ModulePath) {
10849 // parse module id.
10850 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10851 parseToken(lltok::colon, "expected ':' here") ||
10852 parseToken(lltok::SummaryID, "expected module ID"))
10853 return true;
10854
10855 unsigned ModuleID = Lex.getUIntVal();
10856 auto I = ModuleIdMap.find(ModuleID);
10857 // We should have already parsed all module IDs
10858 assert(I != ModuleIdMap.end());
10859 ModulePath = I->second;
10860 return false;
10861}
10862
10863/// GVReference
10864/// ::= SummaryID
10865bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10866 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10867 if (!ReadOnly)
10868 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10869 if (parseToken(lltok::SummaryID, "expected GV ID"))
10870 return true;
10871
10872 GVId = Lex.getUIntVal();
10873 // Check if we already have a VI for this GV
10874 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10875 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10876 VI = NumberedValueInfos[GVId];
10877 } else
10878 // We will create a forward reference to the stored location.
10879 VI = ValueInfo(false, FwdVIRef);
10880
10881 if (ReadOnly)
10882 VI.setReadOnly();
10883 if (WriteOnly)
10884 VI.setWriteOnly();
10885 return false;
10886}
10887
10888/// OptionalAllocs
10889/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10890/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10891/// ',' MemProfs ')'
10892/// Version ::= UInt32
10893bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10894 assert(Lex.getKind() == lltok::kw_allocs);
10895 Lex.Lex();
10896
10897 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10898 parseToken(lltok::lparen, "expected '(' in allocs"))
10899 return true;
10900
10901 // parse each alloc
10902 do {
10903 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10904 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10905 parseToken(lltok::colon, "expected ':'") ||
10906 parseToken(lltok::lparen, "expected '(' in versions"))
10907 return true;
10908
10909 SmallVector<uint8_t> Versions;
10910 do {
10911 uint8_t V = 0;
10912 if (parseAllocType(V))
10913 return true;
10914 Versions.push_back(V);
10915 } while (EatIfPresent(lltok::comma));
10916
10917 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10918 parseToken(lltok::comma, "expected ',' in alloc"))
10919 return true;
10920
10921 std::vector<MIBInfo> MIBs;
10922 if (parseMemProfs(MIBs))
10923 return true;
10924
10925 Allocs.push_back({Versions, MIBs});
10926
10927 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10928 return true;
10929 } while (EatIfPresent(lltok::comma));
10930
10931 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10932 return true;
10933
10934 return false;
10935}
10936
10937/// MemProfs
10938/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10939/// MemProf ::= '(' 'type' ':' AllocType
10940/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10941/// StackId ::= UInt64
10942bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10943 assert(Lex.getKind() == lltok::kw_memProf);
10944 Lex.Lex();
10945
10946 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10947 parseToken(lltok::lparen, "expected '(' in memprof"))
10948 return true;
10949
10950 // parse each MIB
10951 do {
10952 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10953 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10954 parseToken(lltok::colon, "expected ':'"))
10955 return true;
10956
10957 uint8_t AllocType;
10958 if (parseAllocType(AllocType))
10959 return true;
10960
10961 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10962 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10963 parseToken(lltok::colon, "expected ':'") ||
10964 parseToken(lltok::lparen, "expected '(' in stackIds"))
10965 return true;
10966
10967 SmallVector<unsigned> StackIdIndices;
10968 // Combined index alloc records may not have a stack id list.
10969 if (Lex.getKind() != lltok::rparen) {
10970 do {
10971 uint64_t StackId = 0;
10972 if (parseUInt64(StackId))
10973 return true;
10974 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10975 } while (EatIfPresent(lltok::comma));
10976 }
10977
10978 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10979 return true;
10980
10981 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10982
10983 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10984 return true;
10985 } while (EatIfPresent(lltok::comma));
10986
10987 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10988 return true;
10989
10990 return false;
10991}
10992
10993/// AllocType
10994/// := ('none'|'notcold'|'cold'|'hot')
10995bool LLParser::parseAllocType(uint8_t &AllocType) {
10996 switch (Lex.getKind()) {
10997 case lltok::kw_none:
10999 break;
11000 case lltok::kw_notcold:
11002 break;
11003 case lltok::kw_cold:
11005 break;
11006 case lltok::kw_hot:
11007 AllocType = (uint8_t)AllocationType::Hot;
11008 break;
11009 default:
11010 return error(Lex.getLoc(), "invalid alloc type");
11011 }
11012 Lex.Lex();
11013 return false;
11014}
11015
11016/// OptionalCallsites
11017/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11018/// Callsite ::= '(' 'callee' ':' GVReference
11019/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11020/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11021/// Version ::= UInt32
11022/// StackId ::= UInt64
11023bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11024 assert(Lex.getKind() == lltok::kw_callsites);
11025 Lex.Lex();
11026
11027 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11028 parseToken(lltok::lparen, "expected '(' in callsites"))
11029 return true;
11030
11031 IdToIndexMapType IdToIndexMap;
11032 // parse each callsite
11033 do {
11034 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11035 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11036 parseToken(lltok::colon, "expected ':'"))
11037 return true;
11038
11039 ValueInfo VI;
11040 unsigned GVId = 0;
11041 LocTy Loc = Lex.getLoc();
11042 if (!EatIfPresent(lltok::kw_null)) {
11043 if (parseGVReference(VI, GVId))
11044 return true;
11045 }
11046
11047 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11048 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11049 parseToken(lltok::colon, "expected ':'") ||
11050 parseToken(lltok::lparen, "expected '(' in clones"))
11051 return true;
11052
11053 SmallVector<unsigned> Clones;
11054 do {
11055 unsigned V = 0;
11056 if (parseUInt32(V))
11057 return true;
11058 Clones.push_back(V);
11059 } while (EatIfPresent(lltok::comma));
11060
11061 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11062 parseToken(lltok::comma, "expected ',' in callsite") ||
11063 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11064 parseToken(lltok::colon, "expected ':'") ||
11065 parseToken(lltok::lparen, "expected '(' in stackIds"))
11066 return true;
11067
11068 SmallVector<unsigned> StackIdIndices;
11069 // Synthesized callsite records will not have a stack id list.
11070 if (Lex.getKind() != lltok::rparen) {
11071 do {
11072 uint64_t StackId = 0;
11073 if (parseUInt64(StackId))
11074 return true;
11075 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11076 } while (EatIfPresent(lltok::comma));
11077 }
11078
11079 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11080 return true;
11081
11082 // Keep track of the Callsites array index needing a forward reference.
11083 // We will save the location of the ValueInfo needing an update, but
11084 // can only do so once the SmallVector is finalized.
11085 if (VI.getRef() == FwdVIRef)
11086 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11087 Callsites.push_back({VI, Clones, StackIdIndices});
11088
11089 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11090 return true;
11091 } while (EatIfPresent(lltok::comma));
11092
11093 // Now that the Callsites vector is finalized, it is safe to save the
11094 // locations of any forward GV references that need updating later.
11095 for (auto I : IdToIndexMap) {
11096 auto &Infos = ForwardRefValueInfos[I.first];
11097 for (auto P : I.second) {
11098 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11099 "Forward referenced ValueInfo expected to be empty");
11100 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11101 }
11102 }
11103
11104 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11105 return true;
11106
11107 return false;
11108}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:244
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:151
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:67
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:296
static const fltSemantics & BFloat()
Definition APFloat.h:295
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1110
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1238
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
iterator begin() const
Definition ArrayRef.h:130
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:765
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:107
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
@ None
No attributes have been set.
Definition Attributes.h:90
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:372
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1397
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1284
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:136
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
unsigned size() const
Definition DenseMap.h:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:403
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:398
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:839
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:451
arg_iterator arg_begin()
Definition Function.h:866
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1038
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:598
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:655
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:245
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:93
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:251
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:228
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:524
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:566
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:68
lltok::Kind getKind() const
Definition LLLexer.h:72
LocTy getLoc() const
Definition LLLexer.h:71
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:123
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:215
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:107
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:94
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:75
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1078
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1577
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
A single uniqued string.
Definition Metadata.h:721
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1537
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1546
static MemoryEffectsBase readOnly()
Definition ModRef.h:130
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:198
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:140
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:146
static MemoryEffectsBase writeOnly()
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:163
static MemoryEffectsBase none()
Definition ModRef.h:125
static MemoryEffectsBase unknown()
Definition ModRef.h:120
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:183
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:875
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:413
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:619
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:703
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition Type.cpp:538
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:440
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:913
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:287
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:281
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:249
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:598
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:631
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:703
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:153
@ kw_riscv_vls_cc
Definition LLToken.h:189
@ kw_cxx_fast_tlscc
Definition LLToken.h:172
@ kw_extractvalue
Definition LLToken.h:366
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:501
@ kw_arm_apcscc
Definition LLToken.h:145
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:140
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:151
@ kw_provenance
Definition LLToken.h:222
@ kw_mustBeUnreachable
Definition LLToken.h:412
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:480
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:451
@ kw_canAutoHide
Definition LLToken.h:396
@ kw_alwaysInline
Definition LLToken.h:408
@ kw_insertelement
Definition LLToken.h:363
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:192
@ kw_inaccessiblememonly
Definition LLToken.h:215
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:360
@ kw_m68k_rtdcc
Definition LLToken.h:186
@ kw_preserve_nonecc
Definition LLToken.h:167
@ kw_x86_fastcallcc
Definition LLToken.h:141
@ kw_visibility
Definition LLToken.h:392
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:191
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:454
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:431
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:379
@ kw_blockcount
Definition LLToken.h:390
@ kw_notEligibleToImport
Definition LLToken.h:393
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:143
@ kw_ptx_device
Definition LLToken.h:157
@ kw_personality
Definition LLToken.h:335
@ DwarfEnumKind
Definition LLToken.h:514
@ kw_declaration
Definition LLToken.h:399
@ DwarfAttEncoding
Definition LLToken.h:500
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:158
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:411
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:330
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:498
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:190
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:380
@ NameTableKind
Definition LLToken.h:506
@ kw_inlineBits
Definition LLToken.h:449
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:214
@ kw_blockaddress
Definition LLToken.h:368
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:334
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:430
@ FixedPointKind
Definition LLToken.h:507
@ kw_target_mem1
Definition LLToken.h:210
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:362
@ kw_branchFunnel
Definition LLToken.h:455
@ kw_typeidCompatibleVTable
Definition LLToken.h:436
@ kw_vTableFuncs
Definition LLToken.h:422
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:429
@ kw_no_sanitize_address
Definition LLToken.h:477
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:216
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:483
@ DwarfSourceLangName
Definition LLToken.h:503
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:348
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:223
@ kw_cleanuppad
Definition LLToken.h:351
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:456
@ kw_target_mem0
Definition LLToken.h:209
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:428
@ kw_attributes
Definition LLToken.h:195
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:459
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:445
@ kw_nodeduplicate
Definition LLToken.h:252
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:250
@ kw_unreachable
Definition LLToken.h:346
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:406
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:397
@ kw_cleanupret
Definition LLToken.h:347
@ kw_shufflevector
Definition LLToken.h:364
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:398
@ kw_virtualConstProp
Definition LLToken.h:461
@ kw_vcall_visibility
Definition LLToken.h:450
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:208
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:438
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:426
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:369
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:513
@ kw_address_is_null
Definition LLToken.h:221
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:460
@ kw_insertvalue
Definition LLToken.h:367
@ kw_indirectbr
Definition LLToken.h:343
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:578
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:51
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:301
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:154
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:156
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:359
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:310
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ TargetMem0
Represents target specific state.
Definition ModRef.h:70
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:36
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1966
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1879
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:320
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.