LLVM 23.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/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Run: module ::= toplevelentity*
76bool LLParser::Run(bool UpgradeDebugInfo,
77 DataLayoutCallbackTy DataLayoutCallback) {
78 // Prime the lexer.
79 Lex.Lex();
80
81 if (Context.shouldDiscardValueNames())
82 return error(
83 Lex.getLoc(),
84 "Can't read textual IR with a Context that discards named Values");
85
86 if (M) {
87 if (parseTargetDefinitions(DataLayoutCallback))
88 return true;
89 }
90
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
92 validateEndOfIndex();
93}
94
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(Lex.getLoc(), "expected end of string");
105 return false;
106}
107
109 const SlotMapping *Slots) {
110 restoreParsingState(Slots);
111 Lex.Lex();
112
113 Read = 0;
114 SMLoc Start = Lex.getLoc();
115 Ty = nullptr;
116 if (parseType(Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
125 const SlotMapping *Slots) {
126 restoreParsingState(Slots);
127 Lex.Lex();
128
129 Read = 0;
130 SMLoc Start = Lex.getLoc();
131 Result = nullptr;
132 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
133 SMLoc End = Lex.getLoc();
134 Read = End.getPointer() - Start.getPointer();
135
136 return Status;
137}
138
139void LLParser::restoreParsingState(const SlotMapping *Slots) {
140 if (!Slots)
141 return;
142 NumberedVals = Slots->GlobalValues;
143 NumberedMetadata = Slots->MetadataNodes;
144 for (const auto &I : Slots->NamedTypes)
145 NamedTypes.insert(
146 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
150}
151
153 // White-list intrinsics that are safe to drop.
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(V))
161 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(MV);
164
165 if (!MVs.empty()) {
166 assert(II->use_empty() && "Cannot have uses");
167 II->eraseFromParent();
168
169 // Also remove no longer used MetadataAsValue wrappers.
170 for (MetadataAsValue *MV : MVs)
171 if (MV->use_empty())
172 delete MV;
173 }
174}
175
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
178 for (Function &F : *M) {
179 F.eraseMetadataIf(Pred);
180 for (Instruction &I : make_early_inc_range(instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(&I))
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 llvm::erase_if(PendingDbgRecords,
192 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
193 llvm::erase_if(PendingDbgInsts,
194 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
195
196 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
197 // Check whether there is only a single use left, which would be in our
198 // own NumberedMetadata.
199 if (Info.first->getNumTemporaryUses() == 1) {
200 NumberedMetadata.erase(ID);
201 ForwardRefMDNodes.erase(ID);
202 }
203 }
204}
205
206/// validateEndOfModule - Do final validity and basic correctness checks at the
207/// end of the module.
208bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
209 if (!M)
210 return false;
211
212 // We should have already returned an error if we observed both intrinsics and
213 // records in this IR.
214 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
215 "Mixed debug intrinsics/records seen without a parsing error?");
216
217 // Handle any function attribute group forward references.
218 for (const auto &RAG : ForwardRefAttrGroups) {
219 Value *V = RAG.first;
220 const std::vector<unsigned> &Attrs = RAG.second;
221 AttrBuilder B(Context);
222
223 for (const auto &Attr : Attrs) {
224 auto R = NumberedAttrBuilders.find(Attr);
225 if (R != NumberedAttrBuilders.end())
226 B.merge(R->second);
227 }
228
229 if (Function *Fn = dyn_cast<Function>(V)) {
230 AttributeList AS = Fn->getAttributes();
231 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
232 AS = AS.removeFnAttributes(Context);
233
234 FnAttrs.merge(B);
235
236 // If the alignment was parsed as an attribute, move to the alignment
237 // field.
238 if (MaybeAlign A = FnAttrs.getAlignment()) {
239 Fn->setAlignment(*A);
240 FnAttrs.removeAttribute(Attribute::Alignment);
241 }
242
243 AS = AS.addFnAttributes(Context, FnAttrs);
244 Fn->setAttributes(AS);
245 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
246 AttributeList AS = CI->getAttributes();
247 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
248 AS = AS.removeFnAttributes(Context);
249 FnAttrs.merge(B);
250 AS = AS.addFnAttributes(Context, FnAttrs);
251 CI->setAttributes(AS);
252 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
253 AttributeList AS = II->getAttributes();
254 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
255 AS = AS.removeFnAttributes(Context);
256 FnAttrs.merge(B);
257 AS = AS.addFnAttributes(Context, FnAttrs);
258 II->setAttributes(AS);
259 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
260 AttributeList AS = CBI->getAttributes();
261 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
262 AS = AS.removeFnAttributes(Context);
263 FnAttrs.merge(B);
264 AS = AS.addFnAttributes(Context, FnAttrs);
265 CBI->setAttributes(AS);
266 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
267 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
268 Attrs.merge(B);
269 GV->setAttributes(AttributeSet::get(Context,Attrs));
270 } else {
271 llvm_unreachable("invalid object with forward attribute group reference");
272 }
273 }
274
275 // If there are entries in ForwardRefBlockAddresses at this point, the
276 // function was never defined.
277 if (!ForwardRefBlockAddresses.empty())
278 return error(ForwardRefBlockAddresses.begin()->first.Loc,
279 "expected function name in blockaddress");
280
281 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
282 GlobalValue *FwdRef) {
283 GlobalValue *GV = nullptr;
284 if (GVRef.Kind == ValID::t_GlobalName) {
285 GV = M->getNamedValue(GVRef.StrVal);
286 } else {
287 GV = NumberedVals.get(GVRef.UIntVal);
288 }
289
290 if (!GV)
291 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
292 "' referenced by dso_local_equivalent");
293
294 if (!GV->getValueType()->isFunctionTy())
295 return error(GVRef.Loc,
296 "expected a function, alias to function, or ifunc "
297 "in dso_local_equivalent");
298
299 auto *Equiv = DSOLocalEquivalent::get(GV);
300 FwdRef->replaceAllUsesWith(Equiv);
301 FwdRef->eraseFromParent();
302 return false;
303 };
304
305 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
306 // point, they are references after the function was defined. Resolve those
307 // now.
308 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
309 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
310 return true;
311 }
312 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
313 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
314 return true;
315 }
316 ForwardRefDSOLocalEquivalentIDs.clear();
317 ForwardRefDSOLocalEquivalentNames.clear();
318
319 for (const auto &NT : NumberedTypes)
320 if (NT.second.second.isValid())
321 return error(NT.second.second,
322 "use of undefined type '%" + Twine(NT.first) + "'");
323
324 for (const auto &[Name, TypeInfo] : NamedTypes)
325 if (TypeInfo.second.isValid())
326 return error(TypeInfo.second,
327 "use of undefined type named '" + Name + "'");
328
329 if (!ForwardRefComdats.empty())
330 return error(ForwardRefComdats.begin()->second,
331 "use of undefined comdat '$" +
332 ForwardRefComdats.begin()->first + "'");
333
334 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
335 dropUnknownMetadataReferences();
336
337 if (!ForwardRefMDNodes.empty())
338 return error(ForwardRefMDNodes.begin()->second.second,
339 "use of undefined metadata '!" +
340 Twine(ForwardRefMDNodes.begin()->first) + "'");
341
342 // Set debug locations.
343 for (auto [Loc, DR, MD] : PendingDbgRecords) {
344 if (auto *DI = dyn_cast<DILocation>(MD))
345 DR->setDebugLoc(DebugLoc(DI));
346 else
347 return error(Loc, "invalid debug location");
348 }
349 PendingDbgRecords.clear();
350 for (auto [Loc, I, MD] : PendingDbgInsts) {
351 if (auto *DI = dyn_cast<DILocation>(MD))
352 I->setDebugLoc(DebugLoc(DI));
353 else
354 return error(Loc, "invalid !dbg metadata");
355 }
356 PendingDbgInsts.clear();
357
358 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
359 if (StringRef(Name).starts_with("llvm.")) {
361 // Automatically create declarations for intrinsics. Intrinsics can only
362 // be called directly, so the call function type directly determines the
363 // declaration function type.
364 //
365 // Additionally, automatically add the required mangling suffix to the
366 // intrinsic name. This means that we may replace a single forward
367 // declaration with multiple functions here.
368 for (Use &U : make_early_inc_range(Info.first->uses())) {
369 auto *CB = dyn_cast<CallBase>(U.getUser());
370 if (!CB || !CB->isCallee(&U))
371 return error(Info.second, "intrinsic can only be used as callee");
372
373 std::string ErrorMsg;
374 raw_string_ostream ErrorOS(ErrorMsg);
375
376 SmallVector<Type *> OverloadTys;
377 if (IID != Intrinsic::not_intrinsic &&
378 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
379 ErrorOS)) {
380 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
381 } else {
382 // Try to upgrade the intrinsic.
383 Function *TmpF = Function::Create(CB->getFunctionType(),
385 Function *NewF = nullptr;
386 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
387 if (IID == Intrinsic::not_intrinsic)
388 return error(Info.second, "unknown intrinsic '" + Name + "'");
389 return error(Info.second, ErrorMsg);
390 }
391
392 U.set(TmpF);
393 UpgradeIntrinsicCall(CB, NewF);
394 if (TmpF->use_empty())
395 TmpF->eraseFromParent();
396 }
397 }
398
399 Info.first->eraseFromParent();
400 ForwardRefVals.erase(Name);
401 continue;
402 }
403
404 // If incomplete IR is allowed, also add declarations for
405 // non-intrinsics.
407 continue;
408
409 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
410 FunctionType *FTy = nullptr;
411 for (Use &U : V->uses()) {
412 auto *CB = dyn_cast<CallBase>(U.getUser());
413 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
414 return nullptr;
415 FTy = CB->getFunctionType();
416 }
417 return FTy;
418 };
419
420 // First check whether this global is only used in calls with the same
421 // type, in which case we'll insert a function. Otherwise, fall back to
422 // using a dummy i8 type.
423 Type *Ty = GetCommonFunctionType(Info.first);
424 if (!Ty)
425 Ty = Type::getInt8Ty(Context);
426
427 GlobalValue *GV;
428 if (auto *FTy = dyn_cast<FunctionType>(Ty))
430 else
431 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
433 /*Initializer*/ nullptr, Name);
434 Info.first->replaceAllUsesWith(GV);
435 Info.first->eraseFromParent();
436 ForwardRefVals.erase(Name);
437 }
438
439 if (!ForwardRefVals.empty())
440 return error(ForwardRefVals.begin()->second.second,
441 "use of undefined value '@" + ForwardRefVals.begin()->first +
442 "'");
443
444 if (!ForwardRefValIDs.empty())
445 return error(ForwardRefValIDs.begin()->second.second,
446 "use of undefined value '@" +
447 Twine(ForwardRefValIDs.begin()->first) + "'");
448
449 // Resolve metadata cycles.
450 for (auto &N : NumberedMetadata) {
451 if (N.second && !N.second->isResolved())
452 N.second->resolveCycles();
453 }
454
456 NewDistinctSPs.clear();
457
458 for (auto *Inst : InstsWithTBAATag) {
459 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
460 // With incomplete IR, the tbaa metadata may have been dropped.
462 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
463 if (MD) {
464 auto *UpgradedMD = UpgradeTBAANode(*MD);
465 if (MD != UpgradedMD)
466 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
467 }
468 }
469
470 // Look for intrinsic functions and CallInst that need to be upgraded. We use
471 // make_early_inc_range here because we may remove some functions.
472 for (Function &F : llvm::make_early_inc_range(*M))
474
475 if (UpgradeDebugInfo)
477
483
484 if (!Slots)
485 return false;
486 // Initialize the slot mapping.
487 // Because by this point we've parsed and validated everything, we can "steal"
488 // the mapping from LLParser as it doesn't need it anymore.
489 Slots->GlobalValues = std::move(NumberedVals);
490 Slots->MetadataNodes = std::move(NumberedMetadata);
491 for (const auto &I : NamedTypes)
492 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
493 for (const auto &I : NumberedTypes)
494 Slots->Types.insert(std::make_pair(I.first, I.second.first));
495
496 return false;
497}
498
499/// Do final validity and basic correctness checks at the end of the index.
500bool LLParser::validateEndOfIndex() {
501 if (!Index)
502 return false;
503
504 if (!ForwardRefValueInfos.empty())
505 return error(ForwardRefValueInfos.begin()->second.front().second,
506 "use of undefined summary '^" +
507 Twine(ForwardRefValueInfos.begin()->first) + "'");
508
509 if (!ForwardRefAliasees.empty())
510 return error(ForwardRefAliasees.begin()->second.front().second,
511 "use of undefined summary '^" +
512 Twine(ForwardRefAliasees.begin()->first) + "'");
513
514 if (!ForwardRefTypeIds.empty())
515 return error(ForwardRefTypeIds.begin()->second.front().second,
516 "use of undefined type id summary '^" +
517 Twine(ForwardRefTypeIds.begin()->first) + "'");
518
519 return false;
520}
521
522//===----------------------------------------------------------------------===//
523// Top-Level Entities
524//===----------------------------------------------------------------------===//
525
526bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
527 // Delay parsing of the data layout string until the target triple is known.
528 // Then, pass both the the target triple and the tentative data layout string
529 // to DataLayoutCallback, allowing to override the DL string.
530 // This enables importing modules with invalid DL strings.
531 std::string TentativeDLStr = M->getDataLayoutStr();
532 LocTy DLStrLoc;
533
534 bool Done = false;
535 while (!Done) {
536 switch (Lex.getKind()) {
537 case lltok::kw_target:
538 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
539 return true;
540 break;
542 if (parseSourceFileName())
543 return true;
544 break;
545 default:
546 Done = true;
547 }
548 }
549 // Run the override callback to potentially change the data layout string, and
550 // parse the data layout string.
551 if (auto LayoutOverride =
552 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
553 TentativeDLStr = *LayoutOverride;
554 DLStrLoc = {};
555 }
556 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
557 if (!MaybeDL)
558 return error(DLStrLoc, toString(MaybeDL.takeError()));
559 M->setDataLayout(MaybeDL.get());
560 return false;
561}
562
563bool LLParser::parseTopLevelEntities() {
564 // If there is no Module, then parse just the summary index entries.
565 if (!M) {
566 while (true) {
567 switch (Lex.getKind()) {
568 case lltok::Eof:
569 return false;
570 case lltok::SummaryID:
571 if (parseSummaryEntry())
572 return true;
573 break;
575 if (parseSourceFileName())
576 return true;
577 break;
578 default:
579 // Skip everything else
580 Lex.Lex();
581 }
582 }
583 }
584 while (true) {
585 switch (Lex.getKind()) {
586 default:
587 return tokError("expected top-level entity");
588 case lltok::Eof: return false;
590 if (parseDeclare())
591 return true;
592 break;
593 case lltok::kw_define:
594 if (parseDefine())
595 return true;
596 break;
597 case lltok::kw_module:
598 if (parseModuleAsm())
599 return true;
600 break;
602 if (parseUnnamedType())
603 return true;
604 break;
605 case lltok::LocalVar:
606 if (parseNamedType())
607 return true;
608 break;
609 case lltok::GlobalID:
610 if (parseUnnamedGlobal())
611 return true;
612 break;
613 case lltok::GlobalVar:
614 if (parseNamedGlobal())
615 return true;
616 break;
617 case lltok::ComdatVar: if (parseComdat()) return true; break;
618 case lltok::exclaim:
619 if (parseStandaloneMetadata())
620 return true;
621 break;
622 case lltok::SummaryID:
623 if (parseSummaryEntry())
624 return true;
625 break;
627 if (parseNamedMetadata())
628 return true;
629 break;
631 if (parseUnnamedAttrGrp())
632 return true;
633 break;
635 if (parseUseListOrder())
636 return true;
637 break;
638 }
639 }
640}
641
642/// toplevelentity
643/// ::= 'module' 'asm' STRINGCONSTANT
644bool LLParser::parseModuleAsm() {
645 assert(Lex.getKind() == lltok::kw_module);
646 Lex.Lex();
647
648 std::string AsmStr;
649 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
650 parseStringConstant(AsmStr))
651 return true;
652
653 M->appendModuleInlineAsm(AsmStr);
654 return false;
655}
656
657/// toplevelentity
658/// ::= 'target' 'triple' '=' STRINGCONSTANT
659/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
660bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
661 LocTy &DLStrLoc) {
662 assert(Lex.getKind() == lltok::kw_target);
663 std::string Str;
664 switch (Lex.Lex()) {
665 default:
666 return tokError("unknown target property");
667 case lltok::kw_triple:
668 Lex.Lex();
669 if (parseToken(lltok::equal, "expected '=' after target triple") ||
670 parseStringConstant(Str))
671 return true;
672 M->setTargetTriple(Triple(std::move(Str)));
673 return false;
675 Lex.Lex();
676 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
677 return true;
678 DLStrLoc = Lex.getLoc();
679 if (parseStringConstant(TentativeDLStr))
680 return true;
681 return false;
682 }
683}
684
685/// toplevelentity
686/// ::= 'source_filename' '=' STRINGCONSTANT
687bool LLParser::parseSourceFileName() {
688 assert(Lex.getKind() == lltok::kw_source_filename);
689 Lex.Lex();
690 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
691 parseStringConstant(SourceFileName))
692 return true;
693 if (M)
694 M->setSourceFileName(SourceFileName);
695 return false;
696}
697
698/// parseUnnamedType:
699/// ::= LocalVarID '=' 'type' type
700bool LLParser::parseUnnamedType() {
701 LocTy TypeLoc = Lex.getLoc();
702 unsigned TypeID = Lex.getUIntVal();
703 Lex.Lex(); // eat LocalVarID;
704
705 if (parseToken(lltok::equal, "expected '=' after name") ||
706 parseToken(lltok::kw_type, "expected 'type' after '='"))
707 return true;
708
709 Type *Result = nullptr;
710 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
711 return true;
712
713 if (!isa<StructType>(Result)) {
714 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
715 if (Entry.first)
716 return error(TypeLoc, "non-struct types may not be recursive");
717 Entry.first = Result;
718 Entry.second = SMLoc();
719 }
720
721 return false;
722}
723
724/// toplevelentity
725/// ::= LocalVar '=' 'type' type
726bool LLParser::parseNamedType() {
727 std::string Name = Lex.getStrVal();
728 LocTy NameLoc = Lex.getLoc();
729 Lex.Lex(); // eat LocalVar.
730
731 if (parseToken(lltok::equal, "expected '=' after name") ||
732 parseToken(lltok::kw_type, "expected 'type' after name"))
733 return true;
734
735 Type *Result = nullptr;
736 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
737 return true;
738
739 if (!isa<StructType>(Result)) {
740 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
741 if (Entry.first)
742 return error(NameLoc, "non-struct types may not be recursive");
743 Entry.first = Result;
744 Entry.second = SMLoc();
745 }
746
747 return false;
748}
749
750/// toplevelentity
751/// ::= 'declare' FunctionHeader
752bool LLParser::parseDeclare() {
753 assert(Lex.getKind() == lltok::kw_declare);
754 Lex.Lex();
755
756 std::vector<std::pair<unsigned, MDNode *>> MDs;
757 while (Lex.getKind() == lltok::MetadataVar) {
758 unsigned MDK;
759 MDNode *N;
760 if (parseMetadataAttachment(MDK, N))
761 return true;
762 MDs.push_back({MDK, N});
763 }
764
765 Function *F;
766 unsigned FunctionNumber = -1;
767 SmallVector<unsigned> UnnamedArgNums;
768 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
769 return true;
770 for (auto &MD : MDs)
771 F->addMetadata(MD.first, *MD.second);
772 return false;
773}
774
775/// toplevelentity
776/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
777bool LLParser::parseDefine() {
778 assert(Lex.getKind() == lltok::kw_define);
779
780 FileLoc FunctionStart = getTokLineColumnPos();
781 Lex.Lex();
782
783 Function *F;
784 unsigned FunctionNumber = -1;
785 SmallVector<unsigned> UnnamedArgNums;
786 bool RetValue =
787 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
788 parseOptionalFunctionMetadata(*F) ||
789 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
790 if (ParserContext)
791 ParserContext->addFunctionLocation(
792 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
793
794 return RetValue;
795}
796
797/// parseGlobalType
798/// ::= 'constant'
799/// ::= 'global'
800bool LLParser::parseGlobalType(bool &IsConstant) {
801 if (Lex.getKind() == lltok::kw_constant)
802 IsConstant = true;
803 else if (Lex.getKind() == lltok::kw_global)
804 IsConstant = false;
805 else {
806 IsConstant = false;
807 return tokError("expected 'global' or 'constant'");
808 }
809 Lex.Lex();
810 return false;
811}
812
813bool LLParser::parseOptionalUnnamedAddr(
814 GlobalVariable::UnnamedAddr &UnnamedAddr) {
815 if (EatIfPresent(lltok::kw_unnamed_addr))
817 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
819 else
820 UnnamedAddr = GlobalValue::UnnamedAddr::None;
821 return false;
822}
823
824/// parseUnnamedGlobal:
825/// OptionalVisibility (ALIAS | IFUNC) ...
826/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
827/// OptionalDLLStorageClass
828/// ... -> global variable
829/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
830/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
831/// OptionalVisibility
832/// OptionalDLLStorageClass
833/// ... -> global variable
834bool LLParser::parseUnnamedGlobal() {
835 unsigned VarID;
836 std::string Name;
837 LocTy NameLoc = Lex.getLoc();
838
839 // Handle the GlobalID form.
840 if (Lex.getKind() == lltok::GlobalID) {
841 VarID = Lex.getUIntVal();
842 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
843 return true;
844
845 Lex.Lex(); // eat GlobalID;
846 if (parseToken(lltok::equal, "expected '=' after name"))
847 return true;
848 } else {
849 VarID = NumberedVals.getNext();
850 }
851
852 bool HasLinkage;
853 unsigned Linkage, Visibility, DLLStorageClass;
854 bool DSOLocal;
856 GlobalVariable::UnnamedAddr UnnamedAddr;
857 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
858 DSOLocal) ||
859 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
860 return true;
861
862 switch (Lex.getKind()) {
863 default:
864 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
865 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
866 case lltok::kw_alias:
867 case lltok::kw_ifunc:
868 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
869 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
870 }
871}
872
873/// parseNamedGlobal:
874/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
875/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
876/// OptionalVisibility OptionalDLLStorageClass
877/// ... -> global variable
878bool LLParser::parseNamedGlobal() {
879 assert(Lex.getKind() == lltok::GlobalVar);
880 LocTy NameLoc = Lex.getLoc();
881 std::string Name = Lex.getStrVal();
882 Lex.Lex();
883
884 bool HasLinkage;
885 unsigned Linkage, Visibility, DLLStorageClass;
886 bool DSOLocal;
888 GlobalVariable::UnnamedAddr UnnamedAddr;
889 if (parseToken(lltok::equal, "expected '=' in global variable") ||
890 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
891 DSOLocal) ||
892 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
893 return true;
894
895 switch (Lex.getKind()) {
896 default:
897 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
898 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
899 case lltok::kw_alias:
900 case lltok::kw_ifunc:
901 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
902 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
903 }
904}
905
906bool LLParser::parseComdat() {
907 assert(Lex.getKind() == lltok::ComdatVar);
908 std::string Name = Lex.getStrVal();
909 LocTy NameLoc = Lex.getLoc();
910 Lex.Lex();
911
912 if (parseToken(lltok::equal, "expected '=' here"))
913 return true;
914
915 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
916 return tokError("expected comdat type");
917
919 switch (Lex.getKind()) {
920 default:
921 return tokError("unknown selection kind");
922 case lltok::kw_any:
923 SK = Comdat::Any;
924 break;
927 break;
929 SK = Comdat::Largest;
930 break;
933 break;
935 SK = Comdat::SameSize;
936 break;
937 }
938 Lex.Lex();
939
940 // See if the comdat was forward referenced, if so, use the comdat.
941 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
942 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
943 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
944 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
945
946 Comdat *C;
947 if (I != ComdatSymTab.end())
948 C = &I->second;
949 else
950 C = M->getOrInsertComdat(Name);
951 C->setSelectionKind(SK);
952
953 return false;
954}
955
956// MDString:
957// ::= '!' STRINGCONSTANT
958bool LLParser::parseMDString(MDString *&Result) {
959 std::string Str;
960 if (parseStringConstant(Str))
961 return true;
962 Result = MDString::get(Context, Str);
963 return false;
964}
965
966// MDNode:
967// ::= '!' MDNodeNumber
968bool LLParser::parseMDNodeID(MDNode *&Result) {
969 // !{ ..., !42, ... }
970 LocTy IDLoc = Lex.getLoc();
971 unsigned MID = 0;
972 if (parseUInt32(MID))
973 return true;
974
975 // If not a forward reference, just return it now.
976 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
977 if (!Inserted) {
978 Result = It->second;
979 return false;
980 }
981
982 // Otherwise, create MDNode forward reference.
983 auto &FwdRef = ForwardRefMDNodes[MID];
984 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
985
986 Result = FwdRef.first.get();
987 It->second.reset(Result);
988 return false;
989}
990
991/// parseNamedMetadata:
992/// !foo = !{ !1, !2 }
993bool LLParser::parseNamedMetadata() {
994 assert(Lex.getKind() == lltok::MetadataVar);
995 std::string Name = Lex.getStrVal();
996 Lex.Lex();
997
998 if (parseToken(lltok::equal, "expected '=' here") ||
999 parseToken(lltok::exclaim, "Expected '!' here") ||
1000 parseToken(lltok::lbrace, "Expected '{' here"))
1001 return true;
1002
1003 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1004 if (Lex.getKind() != lltok::rbrace)
1005 do {
1006 MDNode *N = nullptr;
1007 // parse DIExpressions inline as a special case. They are still MDNodes,
1008 // so they can still appear in named metadata. Remove this logic if they
1009 // become plain Metadata.
1010 if (Lex.getKind() == lltok::MetadataVar &&
1011 Lex.getStrVal() == "DIExpression") {
1012 if (parseDIExpression(N, /*IsDistinct=*/false))
1013 return true;
1014 // DIArgLists should only appear inline in a function, as they may
1015 // contain LocalAsMetadata arguments which require a function context.
1016 } else if (Lex.getKind() == lltok::MetadataVar &&
1017 Lex.getStrVal() == "DIArgList") {
1018 return tokError("found DIArgList outside of function");
1019 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1020 parseMDNodeID(N)) {
1021 return true;
1022 }
1023 NMD->addOperand(N);
1024 } while (EatIfPresent(lltok::comma));
1025
1026 return parseToken(lltok::rbrace, "expected end of metadata node");
1027}
1028
1029/// parseStandaloneMetadata:
1030/// !42 = !{...}
1031bool LLParser::parseStandaloneMetadata() {
1032 assert(Lex.getKind() == lltok::exclaim);
1033 Lex.Lex();
1034 unsigned MetadataID = 0;
1035
1036 MDNode *Init;
1037 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1038 return true;
1039
1040 // Detect common error, from old metadata syntax.
1041 if (Lex.getKind() == lltok::Type)
1042 return tokError("unexpected type in metadata definition");
1043
1044 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1045 if (Lex.getKind() == lltok::MetadataVar) {
1046 if (parseSpecializedMDNode(Init, IsDistinct))
1047 return true;
1048 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1049 parseMDTuple(Init, IsDistinct))
1050 return true;
1051
1052 // See if this was forward referenced, if so, handle it.
1053 auto FI = ForwardRefMDNodes.find(MetadataID);
1054 if (FI != ForwardRefMDNodes.end()) {
1055 auto *ToReplace = FI->second.first.get();
1056 // DIAssignID has its own special forward-reference "replacement" for
1057 // attachments (the temporary attachments are never actually attached).
1058 if (isa<DIAssignID>(Init)) {
1059 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1060 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1061 "Inst unexpectedly already has DIAssignID attachment");
1062 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1063 }
1064 }
1065
1066 ToReplace->replaceAllUsesWith(Init);
1067 ForwardRefMDNodes.erase(FI);
1068
1069 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1070 } else {
1071 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1072 if (!Inserted)
1073 return tokError("Metadata id is already used");
1074 It->second.reset(Init);
1075 }
1076
1077 return false;
1078}
1079
1080// Skips a single module summary entry.
1081bool LLParser::skipModuleSummaryEntry() {
1082 // Each module summary entry consists of a tag for the entry
1083 // type, followed by a colon, then the fields which may be surrounded by
1084 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1085 // support is in place we will look for the tokens corresponding to the
1086 // expected tags.
1087 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1088 Lex.getKind() != lltok::kw_typeid &&
1089 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1090 Lex.getKind() != lltok::kw_flags && Lex.getKind() != lltok::kw_blockcount)
1091 return tokError("Expected 'gv', 'module', 'typeid', "
1092 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1093 "start of summary entry");
1094 if (Lex.getKind() == lltok::kw_flags)
1095 return parseSummaryIndexFlags();
1096 if (Lex.getKind() == lltok::kw_blockcount)
1097 return parseBlockCount();
1098 Lex.Lex();
1099 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1100 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1101 return true;
1102 // Now walk through the parenthesized entry, until the number of open
1103 // parentheses goes back down to 0 (the first '(' was parsed above).
1104 unsigned NumOpenParen = 1;
1105 do {
1106 switch (Lex.getKind()) {
1107 case lltok::lparen:
1108 NumOpenParen++;
1109 break;
1110 case lltok::rparen:
1111 NumOpenParen--;
1112 break;
1113 case lltok::Eof:
1114 return tokError("found end of file while parsing summary entry");
1115 default:
1116 // Skip everything in between parentheses.
1117 break;
1118 }
1119 Lex.Lex();
1120 } while (NumOpenParen > 0);
1121 return false;
1122}
1123
1124/// SummaryEntry
1125/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1126bool LLParser::parseSummaryEntry() {
1127 assert(Lex.getKind() == lltok::SummaryID);
1128 unsigned SummaryID = Lex.getUIntVal();
1129
1130 // For summary entries, colons should be treated as distinct tokens,
1131 // not an indication of the end of a label token.
1132 Lex.setIgnoreColonInIdentifiers(true);
1133
1134 Lex.Lex();
1135 if (parseToken(lltok::equal, "expected '=' here"))
1136 return true;
1137
1138 // If we don't have an index object, skip the summary entry.
1139 if (!Index)
1140 return skipModuleSummaryEntry();
1141
1142 bool result = false;
1143 switch (Lex.getKind()) {
1144 case lltok::kw_gv:
1145 result = parseGVEntry(SummaryID);
1146 break;
1147 case lltok::kw_module:
1148 result = parseModuleEntry(SummaryID);
1149 break;
1150 case lltok::kw_typeid:
1151 result = parseTypeIdEntry(SummaryID);
1152 break;
1154 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1155 break;
1156 case lltok::kw_flags:
1157 result = parseSummaryIndexFlags();
1158 break;
1160 result = parseBlockCount();
1161 break;
1162 default:
1163 result = error(Lex.getLoc(), "unexpected summary kind");
1164 break;
1165 }
1166 Lex.setIgnoreColonInIdentifiers(false);
1167 return result;
1168}
1169
1178
1179// If there was an explicit dso_local, update GV. In the absence of an explicit
1180// dso_local we keep the default value.
1181static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1182 if (DSOLocal)
1183 GV.setDSOLocal(true);
1184}
1185
1186/// parseAliasOrIFunc:
1187/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1188/// OptionalVisibility OptionalDLLStorageClass
1189/// OptionalThreadLocal OptionalUnnamedAddr
1190/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1191///
1192/// AliaseeOrResolver
1193/// ::= TypeAndValue
1194///
1195/// SymbolAttrs
1196/// ::= ',' 'partition' StringConstant
1197///
1198/// Everything through OptionalUnnamedAddr has already been parsed.
1199///
1200bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1201 LocTy NameLoc, unsigned L, unsigned Visibility,
1202 unsigned DLLStorageClass, bool DSOLocal,
1204 GlobalVariable::UnnamedAddr UnnamedAddr) {
1205 bool IsAlias;
1206 if (Lex.getKind() == lltok::kw_alias)
1207 IsAlias = true;
1208 else if (Lex.getKind() == lltok::kw_ifunc)
1209 IsAlias = false;
1210 else
1211 llvm_unreachable("Not an alias or ifunc!");
1212 Lex.Lex();
1213
1215
1216 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1217 return error(NameLoc, "invalid linkage type for alias");
1218
1219 if (!isValidVisibilityForLinkage(Visibility, L))
1220 return error(NameLoc,
1221 "symbol with local linkage must have default visibility");
1222
1223 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1224 return error(NameLoc,
1225 "symbol with local linkage cannot have a DLL storage class");
1226
1227 Type *Ty;
1228 LocTy ExplicitTypeLoc = Lex.getLoc();
1229 if (parseType(Ty) ||
1230 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1231 return true;
1232
1233 Constant *Aliasee;
1234 LocTy AliaseeLoc = Lex.getLoc();
1235 if (Lex.getKind() != lltok::kw_bitcast &&
1236 Lex.getKind() != lltok::kw_getelementptr &&
1237 Lex.getKind() != lltok::kw_addrspacecast &&
1238 Lex.getKind() != lltok::kw_inttoptr) {
1239 if (parseGlobalTypeAndValue(Aliasee))
1240 return true;
1241 } else {
1242 // The bitcast dest type is not present, it is implied by the dest type.
1243 ValID ID;
1244 if (parseValID(ID, /*PFS=*/nullptr))
1245 return true;
1246 if (ID.Kind != ValID::t_Constant)
1247 return error(AliaseeLoc, "invalid aliasee");
1248 Aliasee = ID.ConstantVal;
1249 }
1250
1251 Type *AliaseeType = Aliasee->getType();
1252 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1253 if (!PTy)
1254 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1255 unsigned AddrSpace = PTy->getAddressSpace();
1256
1257 GlobalValue *GVal = nullptr;
1258
1259 // See if the alias was forward referenced, if so, prepare to replace the
1260 // forward reference.
1261 if (!Name.empty()) {
1262 auto I = ForwardRefVals.find(Name);
1263 if (I != ForwardRefVals.end()) {
1264 GVal = I->second.first;
1265 ForwardRefVals.erase(Name);
1266 } else if (M->getNamedValue(Name)) {
1267 return error(NameLoc, "redefinition of global '@" + Name + "'");
1268 }
1269 } else {
1270 auto I = ForwardRefValIDs.find(NameID);
1271 if (I != ForwardRefValIDs.end()) {
1272 GVal = I->second.first;
1273 ForwardRefValIDs.erase(I);
1274 }
1275 }
1276
1277 // Okay, create the alias/ifunc but do not insert it into the module yet.
1278 std::unique_ptr<GlobalAlias> GA;
1279 std::unique_ptr<GlobalIFunc> GI;
1280 GlobalValue *GV;
1281 if (IsAlias) {
1282 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1283 /*Parent=*/nullptr));
1284 GV = GA.get();
1285 } else {
1286 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1287 /*Parent=*/nullptr));
1288 GV = GI.get();
1289 }
1290 GV->setThreadLocalMode(TLM);
1293 GV->setUnnamedAddr(UnnamedAddr);
1294 maybeSetDSOLocal(DSOLocal, *GV);
1295
1296 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1297 // Now parse them if there are any.
1298 while (Lex.getKind() == lltok::comma) {
1299 Lex.Lex();
1300
1301 if (Lex.getKind() == lltok::kw_partition) {
1302 Lex.Lex();
1303 GV->setPartition(Lex.getStrVal());
1304 if (parseToken(lltok::StringConstant, "expected partition string"))
1305 return true;
1306 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1307 if (parseGlobalObjectMetadataAttachment(*GI))
1308 return true;
1309 } else {
1310 return tokError("unknown alias or ifunc property!");
1311 }
1312 }
1313
1314 if (Name.empty())
1315 NumberedVals.add(NameID, GV);
1316
1317 if (GVal) {
1318 // Verify that types agree.
1319 if (GVal->getType() != GV->getType())
1320 return error(
1321 ExplicitTypeLoc,
1322 "forward reference and definition of alias have different types");
1323
1324 // If they agree, just RAUW the old value with the alias and remove the
1325 // forward ref info.
1326 GVal->replaceAllUsesWith(GV);
1327 GVal->eraseFromParent();
1328 }
1329
1330 // Insert into the module, we know its name won't collide now.
1331 if (IsAlias)
1332 M->insertAlias(GA.release());
1333 else
1334 M->insertIFunc(GI.release());
1335 assert(GV->getName() == Name && "Should not be a name conflict!");
1336
1337 return false;
1338}
1339
1340static bool isSanitizer(lltok::Kind Kind) {
1341 switch (Kind) {
1344 case lltok::kw_sanitize_memtag:
1346 return true;
1347 default:
1348 return false;
1349 }
1350}
1351
1352bool LLParser::parseSanitizer(GlobalVariable *GV) {
1353 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1355 if (GV->hasSanitizerMetadata())
1356 Meta = GV->getSanitizerMetadata();
1357
1358 switch (Lex.getKind()) {
1360 Meta.NoAddress = true;
1361 break;
1363 Meta.NoHWAddress = true;
1364 break;
1365 case lltok::kw_sanitize_memtag:
1366 Meta.Memtag = true;
1367 break;
1369 Meta.IsDynInit = true;
1370 break;
1371 default:
1372 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1373 }
1374 GV->setSanitizerMetadata(Meta);
1375 Lex.Lex();
1376 return false;
1377}
1378
1379/// parseGlobal
1380/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1381/// OptionalVisibility OptionalDLLStorageClass
1382/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1383/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1384/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1385/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1386/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1387/// Const OptionalAttrs
1388///
1389/// Everything up to and including OptionalUnnamedAddr has been parsed
1390/// already.
1391///
1392bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1393 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1394 unsigned Visibility, unsigned DLLStorageClass,
1395 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1396 GlobalVariable::UnnamedAddr UnnamedAddr) {
1397 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1398 return error(NameLoc,
1399 "symbol with local linkage must have default visibility");
1400
1401 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1402 return error(NameLoc,
1403 "symbol with local linkage cannot have a DLL storage class");
1404
1405 unsigned AddrSpace;
1406 bool IsConstant, IsExternallyInitialized;
1407 LocTy IsExternallyInitializedLoc;
1408 LocTy TyLoc;
1409
1410 Type *Ty = nullptr;
1411 if (parseOptionalAddrSpace(AddrSpace) ||
1412 parseOptionalToken(lltok::kw_externally_initialized,
1413 IsExternallyInitialized,
1414 &IsExternallyInitializedLoc) ||
1415 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1416 return true;
1417
1418 // If the linkage is specified and is external, then no initializer is
1419 // present.
1420 Constant *Init = nullptr;
1421 if (!HasLinkage ||
1424 if (parseGlobalValue(Ty, Init))
1425 return true;
1426 }
1427
1429 return error(TyLoc, "invalid type for global variable");
1430
1431 GlobalValue *GVal = nullptr;
1432
1433 // See if the global was forward referenced, if so, use the global.
1434 if (!Name.empty()) {
1435 auto I = ForwardRefVals.find(Name);
1436 if (I != ForwardRefVals.end()) {
1437 GVal = I->second.first;
1438 ForwardRefVals.erase(I);
1439 } else if (M->getNamedValue(Name)) {
1440 return error(NameLoc, "redefinition of global '@" + Name + "'");
1441 }
1442 } else {
1443 // Handle @"", where a name is syntactically specified, but semantically
1444 // missing.
1445 if (NameID == (unsigned)-1)
1446 NameID = NumberedVals.getNext();
1447
1448 auto I = ForwardRefValIDs.find(NameID);
1449 if (I != ForwardRefValIDs.end()) {
1450 GVal = I->second.first;
1451 ForwardRefValIDs.erase(I);
1452 }
1453 }
1454
1455 GlobalVariable *GV = new GlobalVariable(
1456 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1458
1459 if (Name.empty())
1460 NumberedVals.add(NameID, GV);
1461
1462 // Set the parsed properties on the global.
1463 if (Init)
1464 GV->setInitializer(Init);
1465 GV->setConstant(IsConstant);
1467 maybeSetDSOLocal(DSOLocal, *GV);
1470 GV->setExternallyInitialized(IsExternallyInitialized);
1471 GV->setThreadLocalMode(TLM);
1472 GV->setUnnamedAddr(UnnamedAddr);
1473
1474 if (GVal) {
1475 if (GVal->getAddressSpace() != AddrSpace)
1476 return error(
1477 TyLoc,
1478 "forward reference and definition of global have different types");
1479
1480 GVal->replaceAllUsesWith(GV);
1481 GVal->eraseFromParent();
1482 }
1483
1484 // parse attributes on the global.
1485 while (Lex.getKind() == lltok::comma) {
1486 Lex.Lex();
1487
1488 if (Lex.getKind() == lltok::kw_section) {
1489 Lex.Lex();
1490 GV->setSection(Lex.getStrVal());
1491 if (parseToken(lltok::StringConstant, "expected global section string"))
1492 return true;
1493 } else if (Lex.getKind() == lltok::kw_partition) {
1494 Lex.Lex();
1495 GV->setPartition(Lex.getStrVal());
1496 if (parseToken(lltok::StringConstant, "expected partition string"))
1497 return true;
1498 } else if (Lex.getKind() == lltok::kw_align) {
1499 MaybeAlign Alignment;
1500 if (parseOptionalAlignment(Alignment))
1501 return true;
1502 if (Alignment)
1503 GV->setAlignment(*Alignment);
1504 } else if (Lex.getKind() == lltok::kw_code_model) {
1506 if (parseOptionalCodeModel(CodeModel))
1507 return true;
1508 GV->setCodeModel(CodeModel);
1509 } else if (Lex.getKind() == lltok::MetadataVar) {
1510 if (parseGlobalObjectMetadataAttachment(*GV))
1511 return true;
1512 } else if (isSanitizer(Lex.getKind())) {
1513 if (parseSanitizer(GV))
1514 return true;
1515 } else {
1516 Comdat *C;
1517 if (parseOptionalComdat(Name, C))
1518 return true;
1519 if (C)
1520 GV->setComdat(C);
1521 else
1522 return tokError("unknown global variable property!");
1523 }
1524 }
1525
1526 AttrBuilder Attrs(M->getContext());
1527 LocTy BuiltinLoc;
1528 std::vector<unsigned> FwdRefAttrGrps;
1529 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1530 return true;
1531 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1532 GV->setAttributes(AttributeSet::get(Context, Attrs));
1533 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1534 }
1535
1536 return false;
1537}
1538
1539/// parseUnnamedAttrGrp
1540/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1541bool LLParser::parseUnnamedAttrGrp() {
1542 assert(Lex.getKind() == lltok::kw_attributes);
1543 LocTy AttrGrpLoc = Lex.getLoc();
1544 Lex.Lex();
1545
1546 if (Lex.getKind() != lltok::AttrGrpID)
1547 return tokError("expected attribute group id");
1548
1549 unsigned VarID = Lex.getUIntVal();
1550 std::vector<unsigned> unused;
1551 LocTy BuiltinLoc;
1552 Lex.Lex();
1553
1554 if (parseToken(lltok::equal, "expected '=' here") ||
1555 parseToken(lltok::lbrace, "expected '{' here"))
1556 return true;
1557
1558 auto R = NumberedAttrBuilders.find(VarID);
1559 if (R == NumberedAttrBuilders.end())
1560 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1561
1562 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1563 parseToken(lltok::rbrace, "expected end of attribute group"))
1564 return true;
1565
1566 if (!R->second.hasAttributes())
1567 return error(AttrGrpLoc, "attribute group has no attributes");
1568
1569 return false;
1570}
1571
1573 switch (Kind) {
1574#define GET_ATTR_NAMES
1575#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1576 case lltok::kw_##DISPLAY_NAME: \
1577 return Attribute::ENUM_NAME;
1578#include "llvm/IR/Attributes.inc"
1579 default:
1580 return Attribute::None;
1581 }
1582}
1583
1584bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1585 bool InAttrGroup) {
1586 if (Attribute::isTypeAttrKind(Attr))
1587 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1588
1589 switch (Attr) {
1590 case Attribute::Alignment: {
1591 MaybeAlign Alignment;
1592 if (InAttrGroup) {
1593 uint32_t Value = 0;
1594 Lex.Lex();
1595 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1596 return true;
1597 Alignment = Align(Value);
1598 } else {
1599 if (parseOptionalAlignment(Alignment, true))
1600 return true;
1601 }
1602 B.addAlignmentAttr(Alignment);
1603 return false;
1604 }
1605 case Attribute::StackAlignment: {
1606 unsigned Alignment;
1607 if (InAttrGroup) {
1608 Lex.Lex();
1609 if (parseToken(lltok::equal, "expected '=' here") ||
1610 parseUInt32(Alignment))
1611 return true;
1612 } else {
1613 if (parseOptionalStackAlignment(Alignment))
1614 return true;
1615 }
1616 B.addStackAlignmentAttr(Alignment);
1617 return false;
1618 }
1619 case Attribute::AllocSize: {
1620 unsigned ElemSizeArg;
1621 std::optional<unsigned> NumElemsArg;
1622 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1623 return true;
1624 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1625 return false;
1626 }
1627 case Attribute::VScaleRange: {
1628 unsigned MinValue, MaxValue;
1629 if (parseVScaleRangeArguments(MinValue, MaxValue))
1630 return true;
1631 B.addVScaleRangeAttr(MinValue,
1632 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1633 return false;
1634 }
1635 case Attribute::Dereferenceable: {
1636 std::optional<uint64_t> Bytes;
1637 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1638 return true;
1639 assert(Bytes.has_value());
1640 B.addDereferenceableAttr(Bytes.value());
1641 return false;
1642 }
1643 case Attribute::DeadOnReturn: {
1644 std::optional<uint64_t> Bytes;
1645 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1646 /*ErrorNoBytes=*/false))
1647 return true;
1648 if (Bytes.has_value()) {
1649 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1650 } else {
1651 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1652 }
1653 return false;
1654 }
1655 case Attribute::DereferenceableOrNull: {
1656 std::optional<uint64_t> Bytes;
1657 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1658 return true;
1659 assert(Bytes.has_value());
1660 B.addDereferenceableOrNullAttr(Bytes.value());
1661 return false;
1662 }
1663 case Attribute::UWTable: {
1665 if (parseOptionalUWTableKind(Kind))
1666 return true;
1667 B.addUWTableAttr(Kind);
1668 return false;
1669 }
1670 case Attribute::AllocKind: {
1672 if (parseAllocKind(Kind))
1673 return true;
1674 B.addAllocKindAttr(Kind);
1675 return false;
1676 }
1677 case Attribute::Memory: {
1678 std::optional<MemoryEffects> ME = parseMemoryAttr();
1679 if (!ME)
1680 return true;
1681 B.addMemoryAttr(*ME);
1682 return false;
1683 }
1684 case Attribute::DenormalFPEnv: {
1685 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1686 if (!Mode)
1687 return true;
1688
1689 B.addDenormalFPEnvAttr(*Mode);
1690 return false;
1691 }
1692 case Attribute::NoFPClass: {
1693 if (FPClassTest NoFPClass =
1694 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1695 B.addNoFPClassAttr(NoFPClass);
1696 return false;
1697 }
1698
1699 return true;
1700 }
1701 case Attribute::Range:
1702 return parseRangeAttr(B);
1703 case Attribute::Initializes:
1704 return parseInitializesAttr(B);
1705 case Attribute::Captures:
1706 return parseCapturesAttr(B);
1707 default:
1708 B.addAttribute(Attr);
1709 Lex.Lex();
1710 return false;
1711 }
1712}
1713
1715 switch (Kind) {
1716 case lltok::kw_readnone:
1717 ME &= MemoryEffects::none();
1718 return true;
1719 case lltok::kw_readonly:
1721 return true;
1722 case lltok::kw_writeonly:
1724 return true;
1727 return true;
1730 return true;
1733 return true;
1734 default:
1735 return false;
1736 }
1737}
1738
1739/// parseFnAttributeValuePairs
1740/// ::= <attr> | <attr> '=' <value>
1741bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1742 std::vector<unsigned> &FwdRefAttrGrps,
1743 bool InAttrGrp, LocTy &BuiltinLoc) {
1744 bool HaveError = false;
1745
1746 B.clear();
1747
1749 while (true) {
1750 lltok::Kind Token = Lex.getKind();
1751 if (Token == lltok::rbrace)
1752 break; // Finished.
1753
1754 if (Token == lltok::StringConstant) {
1755 if (parseStringAttribute(B))
1756 return true;
1757 continue;
1758 }
1759
1760 if (Token == lltok::AttrGrpID) {
1761 // Allow a function to reference an attribute group:
1762 //
1763 // define void @foo() #1 { ... }
1764 if (InAttrGrp) {
1765 HaveError |= error(
1766 Lex.getLoc(),
1767 "cannot have an attribute group reference in an attribute group");
1768 } else {
1769 // Save the reference to the attribute group. We'll fill it in later.
1770 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1771 }
1772 Lex.Lex();
1773 continue;
1774 }
1775
1776 SMLoc Loc = Lex.getLoc();
1777 if (Token == lltok::kw_builtin)
1778 BuiltinLoc = Loc;
1779
1780 if (upgradeMemoryAttr(ME, Token)) {
1781 Lex.Lex();
1782 continue;
1783 }
1784
1786 if (Attr == Attribute::None) {
1787 if (!InAttrGrp)
1788 break;
1789 return error(Lex.getLoc(), "unterminated attribute group");
1790 }
1791
1792 if (parseEnumAttribute(Attr, B, InAttrGrp))
1793 return true;
1794
1795 // As a hack, we allow function alignment to be initially parsed as an
1796 // attribute on a function declaration/definition or added to an attribute
1797 // group and later moved to the alignment field.
1798 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1799 HaveError |= error(Loc, "this attribute does not apply to functions");
1800 }
1801
1802 if (ME != MemoryEffects::unknown())
1803 B.addMemoryAttr(ME);
1804 return HaveError;
1805}
1806
1807//===----------------------------------------------------------------------===//
1808// GlobalValue Reference/Resolution Routines.
1809//===----------------------------------------------------------------------===//
1810
1812 // The used global type does not matter. We will later RAUW it with a
1813 // global/function of the correct type.
1814 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1817 PTy->getAddressSpace());
1818}
1819
1820Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1821 Value *Val) {
1822 Type *ValTy = Val->getType();
1823 if (ValTy == Ty)
1824 return Val;
1825 if (Ty->isLabelTy())
1826 error(Loc, "'" + Name + "' is not a basic block");
1827 else
1828 error(Loc, "'" + Name + "' defined with type '" +
1829 getTypeString(Val->getType()) + "' but expected '" +
1830 getTypeString(Ty) + "'");
1831 return nullptr;
1832}
1833
1834/// getGlobalVal - Get a value with the specified name or ID, creating a
1835/// forward reference record if needed. This can return null if the value
1836/// exists but does not have the right type.
1837GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1838 LocTy Loc) {
1840 if (!PTy) {
1841 error(Loc, "global variable reference must have pointer type");
1842 return nullptr;
1843 }
1844
1845 // Look this name up in the normal function symbol table.
1846 GlobalValue *Val =
1847 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1848
1849 // If this is a forward reference for the value, see if we already created a
1850 // forward ref record.
1851 if (!Val) {
1852 auto I = ForwardRefVals.find(Name);
1853 if (I != ForwardRefVals.end())
1854 Val = I->second.first;
1855 }
1856
1857 // If we have the value in the symbol table or fwd-ref table, return it.
1858 if (Val)
1860 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1861
1862 // Otherwise, create a new forward reference for this value and remember it.
1863 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1864 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1865 return FwdVal;
1866}
1867
1868GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1870 if (!PTy) {
1871 error(Loc, "global variable reference must have pointer type");
1872 return nullptr;
1873 }
1874
1875 GlobalValue *Val = NumberedVals.get(ID);
1876
1877 // If this is a forward reference for the value, see if we already created a
1878 // forward ref record.
1879 if (!Val) {
1880 auto I = ForwardRefValIDs.find(ID);
1881 if (I != ForwardRefValIDs.end())
1882 Val = I->second.first;
1883 }
1884
1885 // If we have the value in the symbol table or fwd-ref table, return it.
1886 if (Val)
1888 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1889
1890 // Otherwise, create a new forward reference for this value and remember it.
1891 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1892 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1893 return FwdVal;
1894}
1895
1896//===----------------------------------------------------------------------===//
1897// Comdat Reference/Resolution Routines.
1898//===----------------------------------------------------------------------===//
1899
1900Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1901 // Look this name up in the comdat symbol table.
1902 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1903 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1904 if (I != ComdatSymTab.end())
1905 return &I->second;
1906
1907 // Otherwise, create a new forward reference for this value and remember it.
1908 Comdat *C = M->getOrInsertComdat(Name);
1909 ForwardRefComdats[Name] = Loc;
1910 return C;
1911}
1912
1913//===----------------------------------------------------------------------===//
1914// Helper Routines.
1915//===----------------------------------------------------------------------===//
1916
1917/// parseToken - If the current token has the specified kind, eat it and return
1918/// success. Otherwise, emit the specified error and return failure.
1919bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1920 if (Lex.getKind() != T)
1921 return tokError(ErrMsg);
1922 Lex.Lex();
1923 return false;
1924}
1925
1926/// parseStringConstant
1927/// ::= StringConstant
1928bool LLParser::parseStringConstant(std::string &Result) {
1929 if (Lex.getKind() != lltok::StringConstant)
1930 return tokError("expected string constant");
1931 Result = Lex.getStrVal();
1932 Lex.Lex();
1933 return false;
1934}
1935
1936/// parseUInt32
1937/// ::= uint32
1938bool LLParser::parseUInt32(uint32_t &Val) {
1939 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1940 return tokError("expected integer");
1941 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1942 if (Val64 != unsigned(Val64))
1943 return tokError("expected 32-bit integer (too large)");
1944 Val = Val64;
1945 Lex.Lex();
1946 return false;
1947}
1948
1949/// parseUInt64
1950/// ::= uint64
1951bool LLParser::parseUInt64(uint64_t &Val) {
1952 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1953 return tokError("expected integer");
1954 Val = Lex.getAPSIntVal().getLimitedValue();
1955 Lex.Lex();
1956 return false;
1957}
1958
1959/// parseTLSModel
1960/// := 'localdynamic'
1961/// := 'initialexec'
1962/// := 'localexec'
1963bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1964 switch (Lex.getKind()) {
1965 default:
1966 return tokError("expected localdynamic, initialexec or localexec");
1969 break;
1972 break;
1975 break;
1976 }
1977
1978 Lex.Lex();
1979 return false;
1980}
1981
1982/// parseOptionalThreadLocal
1983/// := /*empty*/
1984/// := 'thread_local'
1985/// := 'thread_local' '(' tlsmodel ')'
1986bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1988 if (!EatIfPresent(lltok::kw_thread_local))
1989 return false;
1990
1992 if (Lex.getKind() == lltok::lparen) {
1993 Lex.Lex();
1994 return parseTLSModel(TLM) ||
1995 parseToken(lltok::rparen, "expected ')' after thread local model");
1996 }
1997 return false;
1998}
1999
2000/// parseOptionalAddrSpace
2001/// := /*empty*/
2002/// := 'addrspace' '(' uint32 ')'
2003bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
2004 AddrSpace = DefaultAS;
2005 if (!EatIfPresent(lltok::kw_addrspace))
2006 return false;
2007
2008 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
2009 if (Lex.getKind() == lltok::StringConstant) {
2010 const std::string &AddrSpaceStr = Lex.getStrVal();
2011 if (AddrSpaceStr == "A") {
2012 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2013 } else if (AddrSpaceStr == "G") {
2014 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2015 } else if (AddrSpaceStr == "P") {
2016 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2017 } else if (std::optional<unsigned> AS =
2018 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2019 AddrSpace = *AS;
2020 } else {
2021 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2022 }
2023 Lex.Lex();
2024 return false;
2025 }
2026 if (Lex.getKind() != lltok::APSInt)
2027 return tokError("expected integer or string constant");
2028 SMLoc Loc = Lex.getLoc();
2029 if (parseUInt32(AddrSpace))
2030 return true;
2031 if (!isUInt<24>(AddrSpace))
2032 return error(Loc, "invalid address space, must be a 24-bit integer");
2033 return false;
2034 };
2035
2036 return parseToken(lltok::lparen, "expected '(' in address space") ||
2037 ParseAddrspaceValue(AddrSpace) ||
2038 parseToken(lltok::rparen, "expected ')' in address space");
2039}
2040
2041/// parseStringAttribute
2042/// := StringConstant
2043/// := StringConstant '=' StringConstant
2044bool LLParser::parseStringAttribute(AttrBuilder &B) {
2045 std::string Attr = Lex.getStrVal();
2046 Lex.Lex();
2047 std::string Val;
2048 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2049 return true;
2050 B.addAttribute(Attr, Val);
2051 return false;
2052}
2053
2054/// Parse a potentially empty list of parameter or return attributes.
2055bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2056 bool HaveError = false;
2057
2058 B.clear();
2059
2060 while (true) {
2061 lltok::Kind Token = Lex.getKind();
2062 if (Token == lltok::StringConstant) {
2063 if (parseStringAttribute(B))
2064 return true;
2065 continue;
2066 }
2067
2068 if (Token == lltok::kw_nocapture) {
2069 Lex.Lex();
2070 B.addCapturesAttr(CaptureInfo::none());
2071 continue;
2072 }
2073
2074 SMLoc Loc = Lex.getLoc();
2076 if (Attr == Attribute::None)
2077 return HaveError;
2078
2079 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2080 return true;
2081
2082 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2083 HaveError |= error(Loc, "this attribute does not apply to parameters");
2084 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2085 HaveError |= error(Loc, "this attribute does not apply to return values");
2086 }
2087}
2088
2089static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2090 HasLinkage = true;
2091 switch (Kind) {
2092 default:
2093 HasLinkage = false;
2095 case lltok::kw_private:
2097 case lltok::kw_internal:
2099 case lltok::kw_weak:
2101 case lltok::kw_weak_odr:
2103 case lltok::kw_linkonce:
2111 case lltok::kw_common:
2115 case lltok::kw_external:
2117 }
2118}
2119
2120/// parseOptionalLinkage
2121/// ::= /*empty*/
2122/// ::= 'private'
2123/// ::= 'internal'
2124/// ::= 'weak'
2125/// ::= 'weak_odr'
2126/// ::= 'linkonce'
2127/// ::= 'linkonce_odr'
2128/// ::= 'available_externally'
2129/// ::= 'appending'
2130/// ::= 'common'
2131/// ::= 'extern_weak'
2132/// ::= 'external'
2133bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2134 unsigned &Visibility,
2135 unsigned &DLLStorageClass, bool &DSOLocal) {
2136 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2137 if (HasLinkage)
2138 Lex.Lex();
2139 parseOptionalDSOLocal(DSOLocal);
2140 parseOptionalVisibility(Visibility);
2141 parseOptionalDLLStorageClass(DLLStorageClass);
2142
2143 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2144 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2145 }
2146
2147 return false;
2148}
2149
2150void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2151 switch (Lex.getKind()) {
2152 default:
2153 DSOLocal = false;
2154 break;
2156 DSOLocal = true;
2157 Lex.Lex();
2158 break;
2160 DSOLocal = false;
2161 Lex.Lex();
2162 break;
2163 }
2164}
2165
2166/// parseOptionalVisibility
2167/// ::= /*empty*/
2168/// ::= 'default'
2169/// ::= 'hidden'
2170/// ::= 'protected'
2171///
2172void LLParser::parseOptionalVisibility(unsigned &Res) {
2173 switch (Lex.getKind()) {
2174 default:
2176 return;
2177 case lltok::kw_default:
2179 break;
2180 case lltok::kw_hidden:
2182 break;
2185 break;
2186 }
2187 Lex.Lex();
2188}
2189
2190bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2192 switch (Kind) {
2193 default:
2194 return tokError("unknown import kind. Expect definition or declaration.");
2197 return false;
2200 return false;
2201 }
2202}
2203
2204/// parseOptionalDLLStorageClass
2205/// ::= /*empty*/
2206/// ::= 'dllimport'
2207/// ::= 'dllexport'
2208///
2209void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2210 switch (Lex.getKind()) {
2211 default:
2213 return;
2216 break;
2219 break;
2220 }
2221 Lex.Lex();
2222}
2223
2224/// parseOptionalCallingConv
2225/// ::= /*empty*/
2226/// ::= 'ccc'
2227/// ::= 'fastcc'
2228/// ::= 'intel_ocl_bicc'
2229/// ::= 'coldcc'
2230/// ::= 'cfguard_checkcc'
2231/// ::= 'x86_stdcallcc'
2232/// ::= 'x86_fastcallcc'
2233/// ::= 'x86_thiscallcc'
2234/// ::= 'x86_vectorcallcc'
2235/// ::= 'arm_apcscc'
2236/// ::= 'arm_aapcscc'
2237/// ::= 'arm_aapcs_vfpcc'
2238/// ::= 'aarch64_vector_pcs'
2239/// ::= 'aarch64_sve_vector_pcs'
2240/// ::= 'aarch64_sme_preservemost_from_x0'
2241/// ::= 'aarch64_sme_preservemost_from_x1'
2242/// ::= 'aarch64_sme_preservemost_from_x2'
2243/// ::= 'msp430_intrcc'
2244/// ::= 'avr_intrcc'
2245/// ::= 'avr_signalcc'
2246/// ::= 'ptx_kernel'
2247/// ::= 'ptx_device'
2248/// ::= 'spir_func'
2249/// ::= 'spir_kernel'
2250/// ::= 'x86_64_sysvcc'
2251/// ::= 'win64cc'
2252/// ::= 'anyregcc'
2253/// ::= 'preserve_mostcc'
2254/// ::= 'preserve_allcc'
2255/// ::= 'preserve_nonecc'
2256/// ::= 'ghccc'
2257/// ::= 'swiftcc'
2258/// ::= 'swifttailcc'
2259/// ::= 'x86_intrcc'
2260/// ::= 'hhvmcc'
2261/// ::= 'hhvm_ccc'
2262/// ::= 'cxx_fast_tlscc'
2263/// ::= 'amdgpu_vs'
2264/// ::= 'amdgpu_ls'
2265/// ::= 'amdgpu_hs'
2266/// ::= 'amdgpu_es'
2267/// ::= 'amdgpu_gs'
2268/// ::= 'amdgpu_ps'
2269/// ::= 'amdgpu_cs'
2270/// ::= 'amdgpu_cs_chain'
2271/// ::= 'amdgpu_cs_chain_preserve'
2272/// ::= 'amdgpu_kernel'
2273/// ::= 'tailcc'
2274/// ::= 'm68k_rtdcc'
2275/// ::= 'graalcc'
2276/// ::= 'riscv_vector_cc'
2277/// ::= 'riscv_vls_cc'
2278/// ::= 'cc' UINT
2279///
2280bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2281 switch (Lex.getKind()) {
2282 default: CC = CallingConv::C; return false;
2283 case lltok::kw_ccc: CC = CallingConv::C; break;
2284 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2285 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2298 break;
2301 break;
2304 break;
2307 break;
2317 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2318 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2322 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2323 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2326 case lltok::kw_hhvmcc:
2328 break;
2329 case lltok::kw_hhvm_ccc:
2331 break;
2343 break;
2346 break;
2350 break;
2351 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2353 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2356 break;
2358 // Default ABI_VLEN
2360 Lex.Lex();
2361 if (!EatIfPresent(lltok::lparen))
2362 break;
2363 uint32_t ABIVlen;
2364 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2365 return true;
2366 switch (ABIVlen) {
2367 default:
2368 return tokError("unknown RISC-V ABI VLEN");
2369#define CC_VLS_CASE(ABIVlen) \
2370 case ABIVlen: \
2371 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2372 break;
2373 CC_VLS_CASE(32)
2374 CC_VLS_CASE(64)
2375 CC_VLS_CASE(128)
2376 CC_VLS_CASE(256)
2377 CC_VLS_CASE(512)
2378 CC_VLS_CASE(1024)
2379 CC_VLS_CASE(2048)
2380 CC_VLS_CASE(4096)
2381 CC_VLS_CASE(8192)
2382 CC_VLS_CASE(16384)
2383 CC_VLS_CASE(32768)
2384 CC_VLS_CASE(65536)
2385#undef CC_VLS_CASE
2386 }
2387 return false;
2390 break;
2393 break;
2396 break;
2397 case lltok::kw_cc: {
2398 Lex.Lex();
2399 return parseUInt32(CC);
2400 }
2401 }
2402
2403 Lex.Lex();
2404 return false;
2405}
2406
2407/// parseMetadataAttachment
2408/// ::= !dbg !42
2409bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2410 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2411
2412 std::string Name = Lex.getStrVal();
2413 Kind = M->getMDKindID(Name);
2414 Lex.Lex();
2415
2416 return parseMDNode(MD);
2417}
2418
2419/// parseInstructionMetadata
2420/// ::= !dbg !42 (',' !dbg !57)*
2421bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2422 do {
2423 if (Lex.getKind() != lltok::MetadataVar)
2424 return tokError("expected metadata after comma");
2425
2426 unsigned MDK;
2427 MDNode *N;
2428 auto Loc = Lex.getLoc();
2429 if (parseMetadataAttachment(MDK, N))
2430 return true;
2431
2432 if (MDK == LLVMContext::MD_DIAssignID)
2433 TempDIAssignIDAttachments[N].push_back(&Inst);
2434 else if (MDK == LLVMContext::MD_dbg)
2435 PendingDbgInsts.emplace_back(Loc, &Inst, N);
2436 else
2437 Inst.setMetadata(MDK, N);
2438
2439 if (MDK == LLVMContext::MD_tbaa)
2440 InstsWithTBAATag.push_back(&Inst);
2441
2442 // If this is the end of the list, we're done.
2443 } while (EatIfPresent(lltok::comma));
2444 return false;
2445}
2446
2447/// parseGlobalObjectMetadataAttachment
2448/// ::= !dbg !57
2449bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2450 unsigned MDK;
2451 MDNode *N;
2452 if (parseMetadataAttachment(MDK, N))
2453 return true;
2454
2455 GO.addMetadata(MDK, *N);
2456 return false;
2457}
2458
2459/// parseOptionalFunctionMetadata
2460/// ::= (!dbg !57)*
2461bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2462 while (Lex.getKind() == lltok::MetadataVar)
2463 if (parseGlobalObjectMetadataAttachment(F))
2464 return true;
2465 return false;
2466}
2467
2468/// parseOptionalAlignment
2469/// ::= /* empty */
2470/// ::= 'align' 4
2471bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2472 Alignment = std::nullopt;
2473 if (!EatIfPresent(lltok::kw_align))
2474 return false;
2475 LocTy AlignLoc = Lex.getLoc();
2476 uint64_t Value = 0;
2477
2478 LocTy ParenLoc = Lex.getLoc();
2479 bool HaveParens = false;
2480 if (AllowParens) {
2481 if (EatIfPresent(lltok::lparen))
2482 HaveParens = true;
2483 }
2484
2485 if (parseUInt64(Value))
2486 return true;
2487
2488 if (HaveParens && !EatIfPresent(lltok::rparen))
2489 return error(ParenLoc, "expected ')'");
2490
2491 if (!isPowerOf2_64(Value))
2492 return error(AlignLoc, "alignment is not a power of two");
2494 return error(AlignLoc, "huge alignments are not supported yet");
2495 Alignment = Align(Value);
2496 return false;
2497}
2498
2499/// parseOptionalPrefAlignment
2500/// ::= /* empty */
2501/// ::= 'prefalign' '(' 4 ')'
2502bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2503 Alignment = std::nullopt;
2504 if (!EatIfPresent(lltok::kw_prefalign))
2505 return false;
2506 LocTy AlignLoc = Lex.getLoc();
2507 uint64_t Value = 0;
2508
2509 LocTy ParenLoc = Lex.getLoc();
2510 if (!EatIfPresent(lltok::lparen))
2511 return error(ParenLoc, "expected '('");
2512
2513 if (parseUInt64(Value))
2514 return true;
2515
2516 ParenLoc = Lex.getLoc();
2517 if (!EatIfPresent(lltok::rparen))
2518 return error(ParenLoc, "expected ')'");
2519
2520 if (!isPowerOf2_64(Value))
2521 return error(AlignLoc, "alignment is not a power of two");
2523 return error(AlignLoc, "huge alignments are not supported yet");
2524 Alignment = Align(Value);
2525 return false;
2526}
2527
2528/// parseOptionalCodeModel
2529/// ::= /* empty */
2530/// ::= 'code_model' "large"
2531bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2532 Lex.Lex();
2533 auto StrVal = Lex.getStrVal();
2534 auto ErrMsg = "expected global code model string";
2535 if (StrVal == "tiny")
2536 model = CodeModel::Tiny;
2537 else if (StrVal == "small")
2538 model = CodeModel::Small;
2539 else if (StrVal == "kernel")
2540 model = CodeModel::Kernel;
2541 else if (StrVal == "medium")
2542 model = CodeModel::Medium;
2543 else if (StrVal == "large")
2544 model = CodeModel::Large;
2545 else
2546 return tokError(ErrMsg);
2547 if (parseToken(lltok::StringConstant, ErrMsg))
2548 return true;
2549 return false;
2550}
2551
2552/// parseOptionalAttrBytes
2553/// ::= /* empty */
2554/// ::= AttrKind '(' 4 ')'
2555///
2556/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2557/// 'dead_on_return'
2558bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2559 std::optional<uint64_t> &Bytes,
2560 bool ErrorNoBytes) {
2561 assert((AttrKind == lltok::kw_dereferenceable ||
2562 AttrKind == lltok::kw_dereferenceable_or_null ||
2563 AttrKind == lltok::kw_dead_on_return) &&
2564 "contract!");
2565
2566 Bytes = 0;
2567 if (!EatIfPresent(AttrKind))
2568 return false;
2569 LocTy ParenLoc = Lex.getLoc();
2570 if (!EatIfPresent(lltok::lparen)) {
2571 if (ErrorNoBytes)
2572 return error(ParenLoc, "expected '('");
2573 Bytes = std::nullopt;
2574 return false;
2575 }
2576 LocTy DerefLoc = Lex.getLoc();
2577 if (parseUInt64(Bytes.value()))
2578 return true;
2579 ParenLoc = Lex.getLoc();
2580 if (!EatIfPresent(lltok::rparen))
2581 return error(ParenLoc, "expected ')'");
2582 if (!Bytes.value())
2583 return error(DerefLoc, "byte count specified must be non-zero");
2584 return false;
2585}
2586
2587bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2588 Lex.Lex();
2590 if (!EatIfPresent(lltok::lparen))
2591 return false;
2592 LocTy KindLoc = Lex.getLoc();
2593 if (Lex.getKind() == lltok::kw_sync)
2595 else if (Lex.getKind() == lltok::kw_async)
2597 else
2598 return error(KindLoc, "expected unwind table kind");
2599 Lex.Lex();
2600 return parseToken(lltok::rparen, "expected ')'");
2601}
2602
2603bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2604 Lex.Lex();
2605 LocTy ParenLoc = Lex.getLoc();
2606 if (!EatIfPresent(lltok::lparen))
2607 return error(ParenLoc, "expected '('");
2608 LocTy KindLoc = Lex.getLoc();
2609 std::string Arg;
2610 if (parseStringConstant(Arg))
2611 return error(KindLoc, "expected allockind value");
2612 for (StringRef A : llvm::split(Arg, ",")) {
2613 if (A == "alloc") {
2615 } else if (A == "realloc") {
2617 } else if (A == "free") {
2619 } else if (A == "uninitialized") {
2621 } else if (A == "zeroed") {
2623 } else if (A == "aligned") {
2625 } else {
2626 return error(KindLoc, Twine("unknown allockind ") + A);
2627 }
2628 }
2629 ParenLoc = Lex.getLoc();
2630 if (!EatIfPresent(lltok::rparen))
2631 return error(ParenLoc, "expected ')'");
2632 if (Kind == AllocFnKind::Unknown)
2633 return error(KindLoc, "expected allockind value");
2634 return false;
2635}
2636
2638 using Loc = IRMemLocation;
2639
2640 switch (Tok) {
2641 case lltok::kw_argmem:
2642 return {Loc::ArgMem};
2644 return {Loc::InaccessibleMem};
2645 case lltok::kw_errnomem:
2646 return {Loc::ErrnoMem};
2648 return {Loc::TargetMem0};
2650 return {Loc::TargetMem1};
2651 case lltok::kw_target_mem: {
2654 Targets.push_back(Loc);
2655 return Targets;
2656 }
2657 default:
2658 return {};
2659 }
2660}
2661
2662static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2663 switch (Tok) {
2664 case lltok::kw_none:
2665 return ModRefInfo::NoModRef;
2666 case lltok::kw_read:
2667 return ModRefInfo::Ref;
2668 case lltok::kw_write:
2669 return ModRefInfo::Mod;
2671 return ModRefInfo::ModRef;
2672 default:
2673 return std::nullopt;
2674 }
2675}
2676
2677static std::optional<DenormalMode::DenormalModeKind>
2679 switch (Tok) {
2680 case lltok::kw_ieee:
2681 return DenormalMode::IEEE;
2686 case lltok::kw_dynamic:
2687 return DenormalMode::Dynamic;
2688 default:
2689 return std::nullopt;
2690 }
2691}
2692
2693std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2695
2696 // We use syntax like memory(argmem: read), so the colon should not be
2697 // interpreted as a label terminator.
2698 Lex.setIgnoreColonInIdentifiers(true);
2699 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2700
2701 Lex.Lex();
2702 if (!EatIfPresent(lltok::lparen)) {
2703 tokError("expected '('");
2704 return std::nullopt;
2705 }
2706
2707 bool SeenLoc = false;
2708 bool SeenTargetLoc = false;
2709 do {
2710 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2711 if (!Locs.empty()) {
2712 Lex.Lex();
2713 if (!EatIfPresent(lltok::colon)) {
2714 tokError("expected ':' after location");
2715 return std::nullopt;
2716 }
2717 }
2718
2719 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2720 if (!MR) {
2721 if (Locs.empty())
2722 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2723 "or access kind (none, read, write, readwrite)");
2724 else
2725 tokError("expected access kind (none, read, write, readwrite)");
2726 return std::nullopt;
2727 }
2728
2729 Lex.Lex();
2730 if (!Locs.empty()) {
2731 SeenLoc = true;
2732 for (IRMemLocation Loc : Locs) {
2733 ME = ME.getWithModRef(Loc, *MR);
2734 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2735 SeenTargetLoc = true;
2736 }
2737 if (Locs.size() > 1 && SeenTargetLoc) {
2738 tokError("target memory default access kind must be specified first");
2739 return std::nullopt;
2740 }
2741
2742 } else {
2743 if (SeenLoc) {
2744 tokError("default access kind must be specified first");
2745 return std::nullopt;
2746 }
2747 ME = MemoryEffects(*MR);
2748 }
2749
2750 if (EatIfPresent(lltok::rparen))
2751 return ME;
2752 } while (EatIfPresent(lltok::comma));
2753
2754 tokError("unterminated memory attribute");
2755 return std::nullopt;
2756}
2757
2758std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2759 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2760 keywordToDenormalModeKind(Lex.getKind());
2761 if (!OutputMode) {
2762 tokError("expected denormal behavior kind (ieee, preservesign, "
2763 "positivezero, dynamic)");
2764 return {};
2765 }
2766
2767 Lex.Lex();
2768
2769 std::optional<DenormalMode::DenormalModeKind> InputMode;
2770 if (EatIfPresent(lltok::bar)) {
2771 InputMode = keywordToDenormalModeKind(Lex.getKind());
2772 if (!InputMode) {
2773 tokError("expected denormal behavior kind (ieee, preservesign, "
2774 "positivezero, dynamic)");
2775 return {};
2776 }
2777
2778 Lex.Lex();
2779 } else {
2780 // Single item, input == output mode
2781 InputMode = OutputMode;
2782 }
2783
2784 return DenormalMode(*OutputMode, *InputMode);
2785}
2786
2787std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2788 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2789 // not be interpreted as a label terminator.
2790 Lex.setIgnoreColonInIdentifiers(true);
2791 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2792
2793 Lex.Lex();
2794
2795 if (parseToken(lltok::lparen, "expected '('"))
2796 return {};
2797
2798 DenormalMode DefaultMode = DenormalMode::getIEEE();
2799 DenormalMode F32Mode = DenormalMode::getInvalid();
2800
2801 bool HasDefaultSection = false;
2802 if (Lex.getKind() != lltok::Type) {
2803 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2804 if (!ParsedDefaultMode)
2805 return {};
2806 DefaultMode = *ParsedDefaultMode;
2807 HasDefaultSection = true;
2808 }
2809
2810 bool HasComma = EatIfPresent(lltok::comma);
2811 if (Lex.getKind() == lltok::Type) {
2812 if (HasDefaultSection && !HasComma) {
2813 tokError("expected ',' before float:");
2814 return {};
2815 }
2816
2817 Type *Ty = nullptr;
2818 if (parseType(Ty) || !Ty->isFloatTy()) {
2819 tokError("expected float:");
2820 return {};
2821 }
2822
2823 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2824 return {};
2825
2826 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2827 if (!ParsedF32Mode)
2828 return {};
2829
2830 F32Mode = *ParsedF32Mode;
2831 }
2832
2833 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2834 return {};
2835
2836 return DenormalFPEnv(DefaultMode, F32Mode);
2837}
2838
2839static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2840 switch (Tok) {
2841 case lltok::kw_all:
2842 return fcAllFlags;
2843 case lltok::kw_nan:
2844 return fcNan;
2845 case lltok::kw_snan:
2846 return fcSNan;
2847 case lltok::kw_qnan:
2848 return fcQNan;
2849 case lltok::kw_inf:
2850 return fcInf;
2851 case lltok::kw_ninf:
2852 return fcNegInf;
2853 case lltok::kw_pinf:
2854 return fcPosInf;
2855 case lltok::kw_norm:
2856 return fcNormal;
2857 case lltok::kw_nnorm:
2858 return fcNegNormal;
2859 case lltok::kw_pnorm:
2860 return fcPosNormal;
2861 case lltok::kw_sub:
2862 return fcSubnormal;
2863 case lltok::kw_nsub:
2864 return fcNegSubnormal;
2865 case lltok::kw_psub:
2866 return fcPosSubnormal;
2867 case lltok::kw_zero:
2868 return fcZero;
2869 case lltok::kw_nzero:
2870 return fcNegZero;
2871 case lltok::kw_pzero:
2872 return fcPosZero;
2873 default:
2874 return 0;
2875 }
2876}
2877
2878unsigned LLParser::parseNoFPClassAttr() {
2879 unsigned Mask = fcNone;
2880
2881 Lex.Lex();
2882 if (!EatIfPresent(lltok::lparen)) {
2883 tokError("expected '('");
2884 return 0;
2885 }
2886
2887 do {
2888 uint64_t Value = 0;
2889 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2890 if (TestMask != 0) {
2891 Mask |= TestMask;
2892 // TODO: Disallow overlapping masks to avoid copy paste errors
2893 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2894 !parseUInt64(Value)) {
2895 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2896 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2897 return 0;
2898 }
2899
2900 if (!EatIfPresent(lltok::rparen)) {
2901 error(Lex.getLoc(), "expected ')'");
2902 return 0;
2903 }
2904
2905 return Value;
2906 } else {
2907 error(Lex.getLoc(), "expected nofpclass test mask");
2908 return 0;
2909 }
2910
2911 Lex.Lex();
2912 if (EatIfPresent(lltok::rparen))
2913 return Mask;
2914 } while (1);
2915
2916 llvm_unreachable("unterminated nofpclass attribute");
2917}
2918
2919/// parseOptionalCommaAlign
2920/// ::=
2921/// ::= ',' align 4
2922///
2923/// This returns with AteExtraComma set to true if it ate an excess comma at the
2924/// end.
2925bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2926 bool &AteExtraComma) {
2927 AteExtraComma = false;
2928 while (EatIfPresent(lltok::comma)) {
2929 // Metadata at the end is an early exit.
2930 if (Lex.getKind() == lltok::MetadataVar) {
2931 AteExtraComma = true;
2932 return false;
2933 }
2934
2935 if (Lex.getKind() != lltok::kw_align)
2936 return error(Lex.getLoc(), "expected metadata or 'align'");
2937
2938 if (parseOptionalAlignment(Alignment))
2939 return true;
2940 }
2941
2942 return false;
2943}
2944
2945/// parseOptionalCommaAddrSpace
2946/// ::=
2947/// ::= ',' addrspace(1)
2948///
2949/// This returns with AteExtraComma set to true if it ate an excess comma at the
2950/// end.
2951bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2952 bool &AteExtraComma) {
2953 AteExtraComma = false;
2954 while (EatIfPresent(lltok::comma)) {
2955 // Metadata at the end is an early exit.
2956 if (Lex.getKind() == lltok::MetadataVar) {
2957 AteExtraComma = true;
2958 return false;
2959 }
2960
2961 Loc = Lex.getLoc();
2962 if (Lex.getKind() != lltok::kw_addrspace)
2963 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2964
2965 if (parseOptionalAddrSpace(AddrSpace))
2966 return true;
2967 }
2968
2969 return false;
2970}
2971
2972bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2973 std::optional<unsigned> &HowManyArg) {
2974 Lex.Lex();
2975
2976 auto StartParen = Lex.getLoc();
2977 if (!EatIfPresent(lltok::lparen))
2978 return error(StartParen, "expected '('");
2979
2980 if (parseUInt32(BaseSizeArg))
2981 return true;
2982
2983 if (EatIfPresent(lltok::comma)) {
2984 auto HowManyAt = Lex.getLoc();
2985 unsigned HowMany;
2986 if (parseUInt32(HowMany))
2987 return true;
2988 if (HowMany == BaseSizeArg)
2989 return error(HowManyAt,
2990 "'allocsize' indices can't refer to the same parameter");
2991 HowManyArg = HowMany;
2992 } else
2993 HowManyArg = std::nullopt;
2994
2995 auto EndParen = Lex.getLoc();
2996 if (!EatIfPresent(lltok::rparen))
2997 return error(EndParen, "expected ')'");
2998 return false;
2999}
3000
3001bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
3002 unsigned &MaxValue) {
3003 Lex.Lex();
3004
3005 auto StartParen = Lex.getLoc();
3006 if (!EatIfPresent(lltok::lparen))
3007 return error(StartParen, "expected '('");
3008
3009 if (parseUInt32(MinValue))
3010 return true;
3011
3012 if (EatIfPresent(lltok::comma)) {
3013 if (parseUInt32(MaxValue))
3014 return true;
3015 } else
3016 MaxValue = MinValue;
3017
3018 auto EndParen = Lex.getLoc();
3019 if (!EatIfPresent(lltok::rparen))
3020 return error(EndParen, "expected ')'");
3021 return false;
3022}
3023
3024/// parseScopeAndOrdering
3025/// if isAtomic: ::= SyncScope? AtomicOrdering
3026/// else: ::=
3027///
3028/// This sets Scope and Ordering to the parsed values.
3029bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3030 AtomicOrdering &Ordering) {
3031 if (!IsAtomic)
3032 return false;
3033
3034 return parseScope(SSID) || parseOrdering(Ordering);
3035}
3036
3037/// parseScope
3038/// ::= syncscope("singlethread" | "<target scope>")?
3039///
3040/// This sets synchronization scope ID to the ID of the parsed value.
3041bool LLParser::parseScope(SyncScope::ID &SSID) {
3042 SSID = SyncScope::System;
3043 if (EatIfPresent(lltok::kw_syncscope)) {
3044 auto StartParenAt = Lex.getLoc();
3045 if (!EatIfPresent(lltok::lparen))
3046 return error(StartParenAt, "Expected '(' in syncscope");
3047
3048 std::string SSN;
3049 auto SSNAt = Lex.getLoc();
3050 if (parseStringConstant(SSN))
3051 return error(SSNAt, "Expected synchronization scope name");
3052
3053 auto EndParenAt = Lex.getLoc();
3054 if (!EatIfPresent(lltok::rparen))
3055 return error(EndParenAt, "Expected ')' in syncscope");
3056
3057 SSID = Context.getOrInsertSyncScopeID(SSN);
3058 }
3059
3060 return false;
3061}
3062
3063/// parseOrdering
3064/// ::= AtomicOrdering
3065///
3066/// This sets Ordering to the parsed value.
3067bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3068 switch (Lex.getKind()) {
3069 default:
3070 return tokError("Expected ordering on atomic instruction");
3073 // Not specified yet:
3074 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3078 case lltok::kw_seq_cst:
3080 break;
3081 }
3082 Lex.Lex();
3083 return false;
3084}
3085
3086/// parseOptionalStackAlignment
3087/// ::= /* empty */
3088/// ::= 'alignstack' '(' 4 ')'
3089bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3090 Alignment = 0;
3091 if (!EatIfPresent(lltok::kw_alignstack))
3092 return false;
3093 LocTy ParenLoc = Lex.getLoc();
3094 if (!EatIfPresent(lltok::lparen))
3095 return error(ParenLoc, "expected '('");
3096 LocTy AlignLoc = Lex.getLoc();
3097 if (parseUInt32(Alignment))
3098 return true;
3099 ParenLoc = Lex.getLoc();
3100 if (!EatIfPresent(lltok::rparen))
3101 return error(ParenLoc, "expected ')'");
3102 if (!isPowerOf2_32(Alignment))
3103 return error(AlignLoc, "stack alignment is not a power of two");
3104 return false;
3105}
3106
3107/// parseIndexList - This parses the index list for an insert/extractvalue
3108/// instruction. This sets AteExtraComma in the case where we eat an extra
3109/// comma at the end of the line and find that it is followed by metadata.
3110/// Clients that don't allow metadata can call the version of this function that
3111/// only takes one argument.
3112///
3113/// parseIndexList
3114/// ::= (',' uint32)+
3115///
3116bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3117 bool &AteExtraComma) {
3118 AteExtraComma = false;
3119
3120 if (Lex.getKind() != lltok::comma)
3121 return tokError("expected ',' as start of index list");
3122
3123 while (EatIfPresent(lltok::comma)) {
3124 if (Lex.getKind() == lltok::MetadataVar) {
3125 if (Indices.empty())
3126 return tokError("expected index");
3127 AteExtraComma = true;
3128 return false;
3129 }
3130 unsigned Idx = 0;
3131 if (parseUInt32(Idx))
3132 return true;
3133 Indices.push_back(Idx);
3134 }
3135
3136 return false;
3137}
3138
3139//===----------------------------------------------------------------------===//
3140// Type Parsing.
3141//===----------------------------------------------------------------------===//
3142
3143/// parseType - parse a type.
3144bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3145 SMLoc TypeLoc = Lex.getLoc();
3146 switch (Lex.getKind()) {
3147 default:
3148 return tokError(Msg);
3149 case lltok::Type:
3150 // Type ::= 'float' | 'void' (etc)
3151 Result = Lex.getTyVal();
3152 Lex.Lex();
3153
3154 // Handle "ptr" opaque pointer type.
3155 //
3156 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3157 if (Result->isPointerTy()) {
3158 unsigned AddrSpace;
3159 if (parseOptionalAddrSpace(AddrSpace))
3160 return true;
3161 Result = PointerType::get(getContext(), AddrSpace);
3162
3163 // Give a nice error for 'ptr*'.
3164 if (Lex.getKind() == lltok::star)
3165 return tokError("ptr* is invalid - use ptr instead");
3166
3167 // Fall through to parsing the type suffixes only if this 'ptr' is a
3168 // function return. Otherwise, return success, implicitly rejecting other
3169 // suffixes.
3170 if (Lex.getKind() != lltok::lparen)
3171 return false;
3172 }
3173 break;
3174 case lltok::kw_target: {
3175 // Type ::= TargetExtType
3176 if (parseTargetExtType(Result))
3177 return true;
3178 break;
3179 }
3180 case lltok::lbrace:
3181 // Type ::= StructType
3182 if (parseAnonStructType(Result, false))
3183 return true;
3184 break;
3185 case lltok::lsquare:
3186 // Type ::= '[' ... ']'
3187 Lex.Lex(); // eat the lsquare.
3188 if (parseArrayVectorType(Result, false))
3189 return true;
3190 break;
3191 case lltok::less: // Either vector or packed struct.
3192 // Type ::= '<' ... '>'
3193 Lex.Lex();
3194 if (Lex.getKind() == lltok::lbrace) {
3195 if (parseAnonStructType(Result, true) ||
3196 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3197 return true;
3198 } else if (parseArrayVectorType(Result, true))
3199 return true;
3200 break;
3201 case lltok::LocalVar: {
3202 // Type ::= %foo
3203 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3204
3205 // If the type hasn't been defined yet, create a forward definition and
3206 // remember where that forward def'n was seen (in case it never is defined).
3207 if (!Entry.first) {
3208 Entry.first = StructType::create(Context, Lex.getStrVal());
3209 Entry.second = Lex.getLoc();
3210 }
3211 Result = Entry.first;
3212 Lex.Lex();
3213 break;
3214 }
3215
3216 case lltok::LocalVarID: {
3217 // Type ::= %4
3218 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3219
3220 // If the type hasn't been defined yet, create a forward definition and
3221 // remember where that forward def'n was seen (in case it never is defined).
3222 if (!Entry.first) {
3223 Entry.first = StructType::create(Context);
3224 Entry.second = Lex.getLoc();
3225 }
3226 Result = Entry.first;
3227 Lex.Lex();
3228 break;
3229 }
3230 }
3231
3232 // parse the type suffixes.
3233 while (true) {
3234 switch (Lex.getKind()) {
3235 // End of type.
3236 default:
3237 if (!AllowVoid && Result->isVoidTy())
3238 return error(TypeLoc, "void type only allowed for function results");
3239 return false;
3240
3241 // Type ::= Type '*'
3242 case lltok::star:
3243 if (Result->isLabelTy())
3244 return tokError("basic block pointers are invalid");
3245 if (Result->isVoidTy())
3246 return tokError("pointers to void are invalid - use i8* instead");
3248 return tokError("pointer to this type is invalid");
3249 Result = PointerType::getUnqual(Context);
3250 Lex.Lex();
3251 break;
3252
3253 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3254 case lltok::kw_addrspace: {
3255 if (Result->isLabelTy())
3256 return tokError("basic block pointers are invalid");
3257 if (Result->isVoidTy())
3258 return tokError("pointers to void are invalid; use i8* instead");
3260 return tokError("pointer to this type is invalid");
3261 unsigned AddrSpace;
3262 if (parseOptionalAddrSpace(AddrSpace) ||
3263 parseToken(lltok::star, "expected '*' in address space"))
3264 return true;
3265
3266 Result = PointerType::get(Context, AddrSpace);
3267 break;
3268 }
3269
3270 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3271 case lltok::lparen:
3272 if (parseFunctionType(Result))
3273 return true;
3274 break;
3275 }
3276 }
3277}
3278
3279/// parseParameterList
3280/// ::= '(' ')'
3281/// ::= '(' Arg (',' Arg)* ')'
3282/// Arg
3283/// ::= Type OptionalAttributes Value OptionalAttributes
3284bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3285 PerFunctionState &PFS, bool IsMustTailCall,
3286 bool InVarArgsFunc) {
3287 if (parseToken(lltok::lparen, "expected '(' in call"))
3288 return true;
3289
3290 while (Lex.getKind() != lltok::rparen) {
3291 // If this isn't the first argument, we need a comma.
3292 if (!ArgList.empty() &&
3293 parseToken(lltok::comma, "expected ',' in argument list"))
3294 return true;
3295
3296 // parse an ellipsis if this is a musttail call in a variadic function.
3297 if (Lex.getKind() == lltok::dotdotdot) {
3298 const char *Msg = "unexpected ellipsis in argument list for ";
3299 if (!IsMustTailCall)
3300 return tokError(Twine(Msg) + "non-musttail call");
3301 if (!InVarArgsFunc)
3302 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3303 Lex.Lex(); // Lex the '...', it is purely for readability.
3304 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3305 }
3306
3307 // parse the argument.
3308 LocTy ArgLoc;
3309 Type *ArgTy = nullptr;
3310 Value *V;
3311 if (parseType(ArgTy, ArgLoc))
3312 return true;
3314 return error(ArgLoc, "invalid type for function argument");
3315
3316 AttrBuilder ArgAttrs(M->getContext());
3317
3318 if (ArgTy->isMetadataTy()) {
3319 if (parseMetadataAsValue(V, PFS))
3320 return true;
3321 } else {
3322 // Otherwise, handle normal operands.
3323 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3324 return true;
3325 }
3326 ArgList.push_back(ParamInfo(
3327 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3328 }
3329
3330 if (IsMustTailCall && InVarArgsFunc)
3331 return tokError("expected '...' at end of argument list for musttail call "
3332 "in varargs function");
3333
3334 Lex.Lex(); // Lex the ')'.
3335 return false;
3336}
3337
3338/// parseRequiredTypeAttr
3339/// ::= attrname(<ty>)
3340bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3341 Attribute::AttrKind AttrKind) {
3342 Type *Ty = nullptr;
3343 if (!EatIfPresent(AttrToken))
3344 return true;
3345 if (!EatIfPresent(lltok::lparen))
3346 return error(Lex.getLoc(), "expected '('");
3347 if (parseType(Ty))
3348 return true;
3349 if (!EatIfPresent(lltok::rparen))
3350 return error(Lex.getLoc(), "expected ')'");
3351
3352 B.addTypeAttr(AttrKind, Ty);
3353 return false;
3354}
3355
3356/// parseRangeAttr
3357/// ::= range(<ty> <n>,<n>)
3358bool LLParser::parseRangeAttr(AttrBuilder &B) {
3359 Lex.Lex();
3360
3361 APInt Lower;
3362 APInt Upper;
3363 Type *Ty = nullptr;
3364 LocTy TyLoc;
3365
3366 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3367 if (Lex.getKind() != lltok::APSInt)
3368 return tokError("expected integer");
3369 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3370 return tokError(
3371 "integer is too large for the bit width of specified type");
3372 Val = Lex.getAPSIntVal().extend(BitWidth);
3373 Lex.Lex();
3374 return false;
3375 };
3376
3377 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3378 return true;
3379 if (!Ty->isIntegerTy())
3380 return error(TyLoc, "the range must have integer type!");
3381
3382 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3383
3384 if (ParseAPSInt(BitWidth, Lower) ||
3385 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3386 return true;
3387 if (Lower == Upper && !Lower.isZero())
3388 return tokError("the range represent the empty set but limits aren't 0!");
3389
3390 if (parseToken(lltok::rparen, "expected ')'"))
3391 return true;
3392
3393 B.addRangeAttr(ConstantRange(Lower, Upper));
3394 return false;
3395}
3396
3397/// parseInitializesAttr
3398/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3399bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3400 Lex.Lex();
3401
3402 auto ParseAPSInt = [&](APInt &Val) {
3403 if (Lex.getKind() != lltok::APSInt)
3404 return tokError("expected integer");
3405 Val = Lex.getAPSIntVal().extend(64);
3406 Lex.Lex();
3407 return false;
3408 };
3409
3410 if (parseToken(lltok::lparen, "expected '('"))
3411 return true;
3412
3414 // Parse each constant range.
3415 do {
3416 APInt Lower, Upper;
3417 if (parseToken(lltok::lparen, "expected '('"))
3418 return true;
3419
3420 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3421 ParseAPSInt(Upper))
3422 return true;
3423
3424 if (Lower == Upper)
3425 return tokError("the range should not represent the full or empty set!");
3426
3427 if (parseToken(lltok::rparen, "expected ')'"))
3428 return true;
3429
3430 RangeList.push_back(ConstantRange(Lower, Upper));
3431 } while (EatIfPresent(lltok::comma));
3432
3433 if (parseToken(lltok::rparen, "expected ')'"))
3434 return true;
3435
3436 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3437 if (!CRLOrNull.has_value())
3438 return tokError("Invalid (unordered or overlapping) range list");
3439 B.addInitializesAttr(*CRLOrNull);
3440 return false;
3441}
3442
3443bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3445 std::optional<CaptureComponents> Ret;
3446
3447 // We use syntax like captures(ret: address, provenance), so the colon
3448 // should not be interpreted as a label terminator.
3449 Lex.setIgnoreColonInIdentifiers(true);
3450 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3451
3452 Lex.Lex();
3453 if (parseToken(lltok::lparen, "expected '('"))
3454 return true;
3455
3456 CaptureComponents *Current = &Other;
3457 bool SeenComponent = false;
3458 while (true) {
3459 if (EatIfPresent(lltok::kw_ret)) {
3460 if (parseToken(lltok::colon, "expected ':'"))
3461 return true;
3462 if (Ret)
3463 return tokError("duplicate 'ret' location");
3465 Current = &*Ret;
3466 SeenComponent = false;
3467 }
3468
3469 if (EatIfPresent(lltok::kw_none)) {
3470 if (SeenComponent)
3471 return tokError("cannot use 'none' with other component");
3472 *Current = CaptureComponents::None;
3473 } else {
3474 if (SeenComponent && capturesNothing(*Current))
3475 return tokError("cannot use 'none' with other component");
3476
3477 if (EatIfPresent(lltok::kw_address_is_null))
3479 else if (EatIfPresent(lltok::kw_address))
3480 *Current |= CaptureComponents::Address;
3481 else if (EatIfPresent(lltok::kw_provenance))
3483 else if (EatIfPresent(lltok::kw_read_provenance))
3485 else
3486 return tokError("expected one of 'none', 'address', 'address_is_null', "
3487 "'provenance' or 'read_provenance'");
3488 }
3489
3490 SeenComponent = true;
3491 if (EatIfPresent(lltok::rparen))
3492 break;
3493
3494 if (parseToken(lltok::comma, "expected ',' or ')'"))
3495 return true;
3496 }
3497
3498 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3499 return false;
3500}
3501
3502/// parseOptionalOperandBundles
3503/// ::= /*empty*/
3504/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3505///
3506/// OperandBundle
3507/// ::= bundle-tag '(' ')'
3508/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3509///
3510/// bundle-tag ::= String Constant
3511bool LLParser::parseOptionalOperandBundles(
3512 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3513 LocTy BeginLoc = Lex.getLoc();
3514 if (!EatIfPresent(lltok::lsquare))
3515 return false;
3516
3517 while (Lex.getKind() != lltok::rsquare) {
3518 // If this isn't the first operand bundle, we need a comma.
3519 if (!BundleList.empty() &&
3520 parseToken(lltok::comma, "expected ',' in input list"))
3521 return true;
3522
3523 std::string Tag;
3524 if (parseStringConstant(Tag))
3525 return true;
3526
3527 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3528 return true;
3529
3530 std::vector<Value *> Inputs;
3531 while (Lex.getKind() != lltok::rparen) {
3532 // If this isn't the first input, we need a comma.
3533 if (!Inputs.empty() &&
3534 parseToken(lltok::comma, "expected ',' in input list"))
3535 return true;
3536
3537 Type *Ty = nullptr;
3538 Value *Input = nullptr;
3539 if (parseType(Ty))
3540 return true;
3541 if (Ty->isMetadataTy()) {
3542 if (parseMetadataAsValue(Input, PFS))
3543 return true;
3544 } else if (parseValue(Ty, Input, PFS)) {
3545 return true;
3546 }
3547 Inputs.push_back(Input);
3548 }
3549
3550 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3551
3552 Lex.Lex(); // Lex the ')'.
3553 }
3554
3555 if (BundleList.empty())
3556 return error(BeginLoc, "operand bundle set must not be empty");
3557
3558 Lex.Lex(); // Lex the ']'.
3559 return false;
3560}
3561
3562bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3563 unsigned NextID, unsigned ID) {
3564 if (ID < NextID)
3565 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3566 Twine(NextID) + "' or greater");
3567
3568 return false;
3569}
3570
3571/// parseArgumentList - parse the argument list for a function type or function
3572/// prototype.
3573/// ::= '(' ArgTypeListI ')'
3574/// ArgTypeListI
3575/// ::= /*empty*/
3576/// ::= '...'
3577/// ::= ArgTypeList ',' '...'
3578/// ::= ArgType (',' ArgType)*
3579///
3580bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3581 SmallVectorImpl<unsigned> &UnnamedArgNums,
3582 bool &IsVarArg) {
3583 unsigned CurValID = 0;
3584 IsVarArg = false;
3585 assert(Lex.getKind() == lltok::lparen);
3586 Lex.Lex(); // eat the (.
3587
3588 if (Lex.getKind() != lltok::rparen) {
3589 do {
3590 // Handle ... at end of arg list.
3591 if (EatIfPresent(lltok::dotdotdot)) {
3592 IsVarArg = true;
3593 break;
3594 }
3595
3596 // Otherwise must be an argument type.
3597 LocTy TypeLoc = Lex.getLoc();
3598 Type *ArgTy = nullptr;
3599 AttrBuilder Attrs(M->getContext());
3600 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3601 return true;
3602
3603 if (ArgTy->isVoidTy())
3604 return error(TypeLoc, "argument can not have void type");
3605
3606 std::string Name;
3607 FileLoc IdentStart;
3608 FileLoc IdentEnd;
3609 bool Unnamed = false;
3610 if (Lex.getKind() == lltok::LocalVar) {
3611 Name = Lex.getStrVal();
3612 IdentStart = getTokLineColumnPos();
3613 Lex.Lex();
3614 IdentEnd = getPrevTokEndLineColumnPos();
3615 } else {
3616 unsigned ArgID;
3617 if (Lex.getKind() == lltok::LocalVarID) {
3618 ArgID = Lex.getUIntVal();
3619 IdentStart = getTokLineColumnPos();
3620 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3621 return true;
3622 Lex.Lex();
3623 IdentEnd = getPrevTokEndLineColumnPos();
3624 } else {
3625 ArgID = CurValID;
3626 Unnamed = true;
3627 }
3628 UnnamedArgNums.push_back(ArgID);
3629 CurValID = ArgID + 1;
3630 }
3631
3633 return error(TypeLoc, "invalid type for function argument");
3634
3635 ArgList.emplace_back(
3636 TypeLoc, ArgTy,
3637 Unnamed ? std::nullopt
3638 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3639 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3640 } while (EatIfPresent(lltok::comma));
3641 }
3642
3643 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3644}
3645
3646/// parseFunctionType
3647/// ::= Type ArgumentList OptionalAttrs
3648bool LLParser::parseFunctionType(Type *&Result) {
3649 assert(Lex.getKind() == lltok::lparen);
3650
3652 return tokError("invalid function return type");
3653
3655 bool IsVarArg;
3656 SmallVector<unsigned> UnnamedArgNums;
3657 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3658 return true;
3659
3660 // Reject names on the arguments lists.
3661 for (const ArgInfo &Arg : ArgList) {
3662 if (!Arg.Name.empty())
3663 return error(Arg.Loc, "argument name invalid in function type");
3664 if (Arg.Attrs.hasAttributes())
3665 return error(Arg.Loc, "argument attributes invalid in function type");
3666 }
3667
3668 SmallVector<Type*, 16> ArgListTy;
3669 for (const ArgInfo &Arg : ArgList)
3670 ArgListTy.push_back(Arg.Ty);
3671
3672 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3673 return false;
3674}
3675
3676/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3677/// other structs.
3678bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3680 if (parseStructBody(Elts))
3681 return true;
3682
3683 Result = StructType::get(Context, Elts, Packed);
3684 return false;
3685}
3686
3687/// parseStructDefinition - parse a struct in a 'type' definition.
3688bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3689 std::pair<Type *, LocTy> &Entry,
3690 Type *&ResultTy) {
3691 // If the type was already defined, diagnose the redefinition.
3692 if (Entry.first && !Entry.second.isValid())
3693 return error(TypeLoc, "redefinition of type");
3694
3695 // If we have opaque, just return without filling in the definition for the
3696 // struct. This counts as a definition as far as the .ll file goes.
3697 if (EatIfPresent(lltok::kw_opaque)) {
3698 // This type is being defined, so clear the location to indicate this.
3699 Entry.second = SMLoc();
3700
3701 // If this type number has never been uttered, create it.
3702 if (!Entry.first)
3703 Entry.first = StructType::create(Context, Name);
3704 ResultTy = Entry.first;
3705 return false;
3706 }
3707
3708 // If the type starts with '<', then it is either a packed struct or a vector.
3709 bool isPacked = EatIfPresent(lltok::less);
3710
3711 // If we don't have a struct, then we have a random type alias, which we
3712 // accept for compatibility with old files. These types are not allowed to be
3713 // forward referenced and not allowed to be recursive.
3714 if (Lex.getKind() != lltok::lbrace) {
3715 if (Entry.first)
3716 return error(TypeLoc, "forward references to non-struct type");
3717
3718 ResultTy = nullptr;
3719 if (isPacked)
3720 return parseArrayVectorType(ResultTy, true);
3721 return parseType(ResultTy);
3722 }
3723
3724 // This type is being defined, so clear the location to indicate this.
3725 Entry.second = SMLoc();
3726
3727 // If this type number has never been uttered, create it.
3728 if (!Entry.first)
3729 Entry.first = StructType::create(Context, Name);
3730
3731 StructType *STy = cast<StructType>(Entry.first);
3732
3734 if (parseStructBody(Body) ||
3735 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3736 return true;
3737
3738 if (auto E = STy->setBodyOrError(Body, isPacked))
3739 return tokError(toString(std::move(E)));
3740
3741 ResultTy = STy;
3742 return false;
3743}
3744
3745/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3746/// StructType
3747/// ::= '{' '}'
3748/// ::= '{' Type (',' Type)* '}'
3749/// ::= '<' '{' '}' '>'
3750/// ::= '<' '{' Type (',' Type)* '}' '>'
3751bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3752 assert(Lex.getKind() == lltok::lbrace);
3753 Lex.Lex(); // Consume the '{'
3754
3755 // Handle the empty struct.
3756 if (EatIfPresent(lltok::rbrace))
3757 return false;
3758
3759 LocTy EltTyLoc = Lex.getLoc();
3760 Type *Ty = nullptr;
3761 if (parseType(Ty))
3762 return true;
3763 Body.push_back(Ty);
3764
3766 return error(EltTyLoc, "invalid element type for struct");
3767
3768 while (EatIfPresent(lltok::comma)) {
3769 EltTyLoc = Lex.getLoc();
3770 if (parseType(Ty))
3771 return true;
3772
3774 return error(EltTyLoc, "invalid element type for struct");
3775
3776 Body.push_back(Ty);
3777 }
3778
3779 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3780}
3781
3782/// parseArrayVectorType - parse an array or vector type, assuming the first
3783/// token has already been consumed.
3784/// Type
3785/// ::= '[' APSINTVAL 'x' Types ']'
3786/// ::= '<' APSINTVAL 'x' Types '>'
3787/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3788bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3789 bool Scalable = false;
3790
3791 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3792 Lex.Lex(); // consume the 'vscale'
3793 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3794 return true;
3795
3796 Scalable = true;
3797 }
3798
3799 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3800 Lex.getAPSIntVal().getBitWidth() > 64)
3801 return tokError("expected number in address space");
3802
3803 LocTy SizeLoc = Lex.getLoc();
3804 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3805 Lex.Lex();
3806
3807 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3808 return true;
3809
3810 LocTy TypeLoc = Lex.getLoc();
3811 Type *EltTy = nullptr;
3812 if (parseType(EltTy))
3813 return true;
3814
3815 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3816 "expected end of sequential type"))
3817 return true;
3818
3819 if (IsVector) {
3820 if (Size == 0)
3821 return error(SizeLoc, "zero element vector is illegal");
3822 if ((unsigned)Size != Size)
3823 return error(SizeLoc, "size too large for vector");
3825 return error(TypeLoc, "invalid vector element type");
3826 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3827 } else {
3829 return error(TypeLoc, "invalid array element type");
3830 Result = ArrayType::get(EltTy, Size);
3831 }
3832 return false;
3833}
3834
3835/// parseTargetExtType - handle target extension type syntax
3836/// TargetExtType
3837/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3838///
3839/// TargetExtTypeParams
3840/// ::= /*empty*/
3841/// ::= ',' Type TargetExtTypeParams
3842///
3843/// TargetExtIntParams
3844/// ::= /*empty*/
3845/// ::= ',' uint32 TargetExtIntParams
3846bool LLParser::parseTargetExtType(Type *&Result) {
3847 Lex.Lex(); // Eat the 'target' keyword.
3848
3849 // Get the mandatory type name.
3850 std::string TypeName;
3851 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3852 parseStringConstant(TypeName))
3853 return true;
3854
3855 // Parse all of the integer and type parameters at the same time; the use of
3856 // SeenInt will allow us to catch cases where type parameters follow integer
3857 // parameters.
3858 SmallVector<Type *> TypeParams;
3859 SmallVector<unsigned> IntParams;
3860 bool SeenInt = false;
3861 while (Lex.getKind() == lltok::comma) {
3862 Lex.Lex(); // Eat the comma.
3863
3864 if (Lex.getKind() == lltok::APSInt) {
3865 SeenInt = true;
3866 unsigned IntVal;
3867 if (parseUInt32(IntVal))
3868 return true;
3869 IntParams.push_back(IntVal);
3870 } else if (SeenInt) {
3871 // The only other kind of parameter we support is type parameters, which
3872 // must precede the integer parameters. This is therefore an error.
3873 return tokError("expected uint32 param");
3874 } else {
3875 Type *TypeParam;
3876 if (parseType(TypeParam, /*AllowVoid=*/true))
3877 return true;
3878 TypeParams.push_back(TypeParam);
3879 }
3880 }
3881
3882 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3883 return true;
3884
3885 auto TTy =
3886 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3887 if (auto E = TTy.takeError())
3888 return tokError(toString(std::move(E)));
3889
3890 Result = *TTy;
3891 return false;
3892}
3893
3894//===----------------------------------------------------------------------===//
3895// Function Semantic Analysis.
3896//===----------------------------------------------------------------------===//
3897
3898LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3899 int functionNumber,
3900 ArrayRef<unsigned> UnnamedArgNums)
3901 : P(p), F(f), FunctionNumber(functionNumber) {
3902
3903 // Insert unnamed arguments into the NumberedVals list.
3904 auto It = UnnamedArgNums.begin();
3905 for (Argument &A : F.args()) {
3906 if (!A.hasName()) {
3907 unsigned ArgNum = *It++;
3908 NumberedVals.add(ArgNum, &A);
3909 }
3910 }
3911}
3912
3913LLParser::PerFunctionState::~PerFunctionState() {
3914 // If there were any forward referenced non-basicblock values, delete them.
3915
3916 for (const auto &P : ForwardRefVals) {
3917 if (isa<BasicBlock>(P.second.first))
3918 continue;
3919 P.second.first->replaceAllUsesWith(
3920 PoisonValue::get(P.second.first->getType()));
3921 P.second.first->deleteValue();
3922 }
3923
3924 for (const auto &P : ForwardRefValIDs) {
3925 if (isa<BasicBlock>(P.second.first))
3926 continue;
3927 P.second.first->replaceAllUsesWith(
3928 PoisonValue::get(P.second.first->getType()));
3929 P.second.first->deleteValue();
3930 }
3931}
3932
3933bool LLParser::PerFunctionState::finishFunction() {
3934 if (!ForwardRefVals.empty())
3935 return P.error(ForwardRefVals.begin()->second.second,
3936 "use of undefined value '%" + ForwardRefVals.begin()->first +
3937 "'");
3938 if (!ForwardRefValIDs.empty())
3939 return P.error(ForwardRefValIDs.begin()->second.second,
3940 "use of undefined value '%" +
3941 Twine(ForwardRefValIDs.begin()->first) + "'");
3942 return false;
3943}
3944
3945/// getVal - Get a value with the specified name or ID, creating a
3946/// forward reference record if needed. This can return null if the value
3947/// exists but does not have the right type.
3948Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3949 LocTy Loc) {
3950 // Look this name up in the normal function symbol table.
3951 Value *Val = F.getValueSymbolTable()->lookup(Name);
3952
3953 // If this is a forward reference for the value, see if we already created a
3954 // forward ref record.
3955 if (!Val) {
3956 auto I = ForwardRefVals.find(Name);
3957 if (I != ForwardRefVals.end())
3958 Val = I->second.first;
3959 }
3960
3961 // If we have the value in the symbol table or fwd-ref table, return it.
3962 if (Val)
3963 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3964
3965 // Don't make placeholders with invalid type.
3966 if (!Ty->isFirstClassType()) {
3967 P.error(Loc, "invalid use of a non-first-class type");
3968 return nullptr;
3969 }
3970
3971 // Otherwise, create a new forward reference for this value and remember it.
3972 Value *FwdVal;
3973 if (Ty->isLabelTy()) {
3974 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3975 } else {
3976 FwdVal = new Argument(Ty, Name);
3977 }
3978 if (FwdVal->getName() != Name) {
3979 P.error(Loc, "name is too long which can result in name collisions, "
3980 "consider making the name shorter or "
3981 "increasing -non-global-value-max-name-size");
3982 return nullptr;
3983 }
3984
3985 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3986 return FwdVal;
3987}
3988
3989Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3990 // Look this name up in the normal function symbol table.
3991 Value *Val = NumberedVals.get(ID);
3992
3993 // If this is a forward reference for the value, see if we already created a
3994 // forward ref record.
3995 if (!Val) {
3996 auto I = ForwardRefValIDs.find(ID);
3997 if (I != ForwardRefValIDs.end())
3998 Val = I->second.first;
3999 }
4000
4001 // If we have the value in the symbol table or fwd-ref table, return it.
4002 if (Val)
4003 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
4004
4005 if (!Ty->isFirstClassType()) {
4006 P.error(Loc, "invalid use of a non-first-class type");
4007 return nullptr;
4008 }
4009
4010 // Otherwise, create a new forward reference for this value and remember it.
4011 Value *FwdVal;
4012 if (Ty->isLabelTy()) {
4013 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
4014 } else {
4015 FwdVal = new Argument(Ty);
4016 }
4017
4018 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
4019 return FwdVal;
4020}
4021
4022/// setInstName - After an instruction is parsed and inserted into its
4023/// basic block, this installs its name.
4024bool LLParser::PerFunctionState::setInstName(int NameID,
4025 const std::string &NameStr,
4026 LocTy NameLoc, Instruction *Inst) {
4027 // If this instruction has void type, it cannot have a name or ID specified.
4028 if (Inst->getType()->isVoidTy()) {
4029 if (NameID != -1 || !NameStr.empty())
4030 return P.error(NameLoc, "instructions returning void cannot have a name");
4031 return false;
4032 }
4033
4034 // If this was a numbered instruction, verify that the instruction is the
4035 // expected value and resolve any forward references.
4036 if (NameStr.empty()) {
4037 // If neither a name nor an ID was specified, just use the next ID.
4038 if (NameID == -1)
4039 NameID = NumberedVals.getNext();
4040
4041 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4042 NameID))
4043 return true;
4044
4045 auto FI = ForwardRefValIDs.find(NameID);
4046 if (FI != ForwardRefValIDs.end()) {
4047 Value *Sentinel = FI->second.first;
4048 if (Sentinel->getType() != Inst->getType())
4049 return P.error(NameLoc, "instruction forward referenced with type '" +
4050 getTypeString(FI->second.first->getType()) +
4051 "'");
4052
4053 Sentinel->replaceAllUsesWith(Inst);
4054 Sentinel->deleteValue();
4055 ForwardRefValIDs.erase(FI);
4056 }
4057
4058 NumberedVals.add(NameID, Inst);
4059 return false;
4060 }
4061
4062 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4063 auto FI = ForwardRefVals.find(NameStr);
4064 if (FI != ForwardRefVals.end()) {
4065 Value *Sentinel = FI->second.first;
4066 if (Sentinel->getType() != Inst->getType())
4067 return P.error(NameLoc, "instruction forward referenced with type '" +
4068 getTypeString(FI->second.first->getType()) +
4069 "'");
4070
4071 Sentinel->replaceAllUsesWith(Inst);
4072 Sentinel->deleteValue();
4073 ForwardRefVals.erase(FI);
4074 }
4075
4076 // Set the name on the instruction.
4077 Inst->setName(NameStr);
4078
4079 if (Inst->getName() != NameStr)
4080 return P.error(NameLoc, "multiple definition of local value named '" +
4081 NameStr + "'");
4082 return false;
4083}
4084
4085/// getBB - Get a basic block with the specified name or ID, creating a
4086/// forward reference record if needed.
4087BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4088 LocTy Loc) {
4090 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4091}
4092
4093BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4095 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4096}
4097
4098/// defineBB - Define the specified basic block, which is either named or
4099/// unnamed. If there is an error, this returns null otherwise it returns
4100/// the block being defined.
4101BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4102 int NameID, LocTy Loc) {
4103 BasicBlock *BB;
4104 if (Name.empty()) {
4105 if (NameID != -1) {
4106 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4107 return nullptr;
4108 } else {
4109 NameID = NumberedVals.getNext();
4110 }
4111 BB = getBB(NameID, Loc);
4112 if (!BB) {
4113 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4114 return nullptr;
4115 }
4116 } else {
4117 BB = getBB(Name, Loc);
4118 if (!BB) {
4119 P.error(Loc, "unable to create block named '" + Name + "'");
4120 return nullptr;
4121 }
4122 }
4123
4124 // Move the block to the end of the function. Forward ref'd blocks are
4125 // inserted wherever they happen to be referenced.
4126 F.splice(F.end(), &F, BB->getIterator());
4127
4128 // Remove the block from forward ref sets.
4129 if (Name.empty()) {
4130 ForwardRefValIDs.erase(NameID);
4131 NumberedVals.add(NameID, BB);
4132 } else {
4133 // BB forward references are already in the function symbol table.
4134 ForwardRefVals.erase(Name);
4135 }
4136
4137 return BB;
4138}
4139
4140//===----------------------------------------------------------------------===//
4141// Constants.
4142//===----------------------------------------------------------------------===//
4143
4144/// parseValID - parse an abstract value that doesn't necessarily have a
4145/// type implied. For example, if we parse "4" we don't know what integer type
4146/// it has. The value will later be combined with its type and checked for
4147/// basic correctness. PFS is used to convert function-local operands of
4148/// metadata (since metadata operands are not just parsed here but also
4149/// converted to values). PFS can be null when we are not parsing metadata
4150/// values inside a function.
4151bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4152 ID.Loc = Lex.getLoc();
4153 switch (Lex.getKind()) {
4154 default:
4155 return tokError("expected value token");
4156 case lltok::GlobalID: // @42
4157 ID.UIntVal = Lex.getUIntVal();
4158 ID.Kind = ValID::t_GlobalID;
4159 break;
4160 case lltok::GlobalVar: // @foo
4161 ID.StrVal = Lex.getStrVal();
4162 ID.Kind = ValID::t_GlobalName;
4163 break;
4164 case lltok::LocalVarID: // %42
4165 ID.UIntVal = Lex.getUIntVal();
4166 ID.Kind = ValID::t_LocalID;
4167 break;
4168 case lltok::LocalVar: // %foo
4169 ID.StrVal = Lex.getStrVal();
4170 ID.Kind = ValID::t_LocalName;
4171 break;
4172 case lltok::APSInt:
4173 ID.APSIntVal = Lex.getAPSIntVal();
4174 ID.Kind = ValID::t_APSInt;
4175 break;
4176 case lltok::APFloat: {
4177 ID.APFloatVal = Lex.getAPFloatVal();
4178 ID.Kind = ValID::t_APFloat;
4179 break;
4180 }
4181 case lltok::FloatLiteral: {
4182 if (!ExpectedTy)
4183 return error(ID.Loc, "unexpected floating-point literal");
4184 if (!ExpectedTy->isFloatingPointTy())
4185 return error(ID.Loc, "floating-point constant invalid for type");
4186 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4187 APFloat::opStatus Except =
4188 cantFail(ID.APFloatVal.convertFromString(
4189 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4190 "Invalid float strings should be caught by the lexer");
4191 // Forbid overflowing and underflowing literals, but permit inexact
4192 // literals. Underflow is thrown when the result is denormal, so to allow
4193 // denormals, only reject underflowing literals that resulted in a zero.
4194 if (Except & APFloat::opOverflow)
4195 return error(ID.Loc, "floating-point constant overflowed type");
4196 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4197 return error(ID.Loc, "floating-point constant underflowed type");
4198 ID.Kind = ValID::t_APFloat;
4199 break;
4200 }
4202 if (!ExpectedTy)
4203 return error(ID.Loc, "unexpected floating-point literal");
4204 const auto &Semantics = ExpectedTy->getFltSemantics();
4205 const APInt &Bits = Lex.getAPSIntVal();
4206 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4207 return error(ID.Loc, "float hex literal has incorrect number of bits");
4208 ID.APFloatVal = APFloat(Semantics, Bits);
4209 ID.Kind = ValID::t_APFloat;
4210 break;
4211 }
4212 case lltok::kw_true:
4213 ID.ConstantVal = ConstantInt::getTrue(Context);
4214 ID.Kind = ValID::t_Constant;
4215 break;
4216 case lltok::kw_false:
4217 ID.ConstantVal = ConstantInt::getFalse(Context);
4218 ID.Kind = ValID::t_Constant;
4219 break;
4220 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4221 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4222 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4223 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4224 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4225
4226 case lltok::lbrace: {
4227 // ValID ::= '{' ConstVector '}'
4228 Lex.Lex();
4230 if (parseGlobalValueVector(Elts) ||
4231 parseToken(lltok::rbrace, "expected end of struct constant"))
4232 return true;
4233
4234 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4235 ID.UIntVal = Elts.size();
4236 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4237 Elts.size() * sizeof(Elts[0]));
4239 return false;
4240 }
4241 case lltok::less: {
4242 // ValID ::= '<' ConstVector '>' --> Vector.
4243 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4244 Lex.Lex();
4245 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4246
4248 LocTy FirstEltLoc = Lex.getLoc();
4249 if (parseGlobalValueVector(Elts) ||
4250 (isPackedStruct &&
4251 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4252 parseToken(lltok::greater, "expected end of constant"))
4253 return true;
4254
4255 if (isPackedStruct) {
4256 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4257 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4258 Elts.size() * sizeof(Elts[0]));
4259 ID.UIntVal = Elts.size();
4261 return false;
4262 }
4263
4264 if (Elts.empty())
4265 return error(ID.Loc, "constant vector must not be empty");
4266
4267 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4268 !Elts[0]->getType()->isFloatingPointTy() &&
4269 !Elts[0]->getType()->isPointerTy())
4270 return error(
4271 FirstEltLoc,
4272 "vector elements must have integer, byte, pointer or floating point "
4273 "type");
4274
4275 // Verify that all the vector elements have the same type.
4276 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4277 if (Elts[i]->getType() != Elts[0]->getType())
4278 return error(FirstEltLoc, "vector element #" + Twine(i) +
4279 " is not of type '" +
4280 getTypeString(Elts[0]->getType()));
4281
4282 ID.ConstantVal = ConstantVector::get(Elts);
4283 ID.Kind = ValID::t_Constant;
4284 return false;
4285 }
4286 case lltok::lsquare: { // Array Constant
4287 Lex.Lex();
4289 LocTy FirstEltLoc = Lex.getLoc();
4290 if (parseGlobalValueVector(Elts) ||
4291 parseToken(lltok::rsquare, "expected end of array constant"))
4292 return true;
4293
4294 // Handle empty element.
4295 if (Elts.empty()) {
4296 // Use undef instead of an array because it's inconvenient to determine
4297 // the element type at this point, there being no elements to examine.
4298 ID.Kind = ValID::t_EmptyArray;
4299 return false;
4300 }
4301
4302 if (!Elts[0]->getType()->isFirstClassType())
4303 return error(FirstEltLoc, "invalid array element type: " +
4304 getTypeString(Elts[0]->getType()));
4305
4306 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4307
4308 // Verify all elements are correct type!
4309 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4310 if (Elts[i]->getType() != Elts[0]->getType())
4311 return error(FirstEltLoc, "array element #" + Twine(i) +
4312 " is not of type '" +
4313 getTypeString(Elts[0]->getType()));
4314 }
4315
4316 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4317 ID.Kind = ValID::t_Constant;
4318 return false;
4319 }
4320 case lltok::kw_c: { // c "foo"
4321 Lex.Lex();
4322 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4323 ID.ConstantVal = ConstantDataArray::getString(
4324 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4325 if (parseToken(lltok::StringConstant, "expected string"))
4326 return true;
4327 ID.Kind = ValID::t_Constant;
4328 return false;
4329 }
4330 case lltok::kw_asm: {
4331 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4332 // STRINGCONSTANT
4333 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4334 Lex.Lex();
4335 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4336 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4337 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4338 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4339 parseStringConstant(ID.StrVal) ||
4340 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4341 parseToken(lltok::StringConstant, "expected constraint string"))
4342 return true;
4343 ID.StrVal2 = Lex.getStrVal();
4344 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4345 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4346 ID.Kind = ValID::t_InlineAsm;
4347 return false;
4348 }
4349
4351 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4352 Lex.Lex();
4353
4354 ValID Fn, Label;
4355
4356 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4357 parseValID(Fn, PFS) ||
4358 parseToken(lltok::comma,
4359 "expected comma in block address expression") ||
4360 parseValID(Label, PFS) ||
4361 parseToken(lltok::rparen, "expected ')' in block address expression"))
4362 return true;
4363
4365 return error(Fn.Loc, "expected function name in blockaddress");
4366 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4367 return error(Label.Loc, "expected basic block name in blockaddress");
4368
4369 // Try to find the function (but skip it if it's forward-referenced).
4370 GlobalValue *GV = nullptr;
4371 if (Fn.Kind == ValID::t_GlobalID) {
4372 GV = NumberedVals.get(Fn.UIntVal);
4373 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4374 GV = M->getNamedValue(Fn.StrVal);
4375 }
4376 Function *F = nullptr;
4377 if (GV) {
4378 // Confirm that it's actually a function with a definition.
4379 if (!isa<Function>(GV))
4380 return error(Fn.Loc, "expected function name in blockaddress");
4381 F = cast<Function>(GV);
4382 if (F->isDeclaration())
4383 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4384 }
4385
4386 if (!F) {
4387 // Make a global variable as a placeholder for this reference.
4388 GlobalValue *&FwdRef =
4389 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4390 if (!FwdRef) {
4391 unsigned FwdDeclAS;
4392 if (ExpectedTy) {
4393 // If we know the type that the blockaddress is being assigned to,
4394 // we can use the address space of that type.
4395 if (!ExpectedTy->isPointerTy())
4396 return error(ID.Loc,
4397 "type of blockaddress must be a pointer and not '" +
4398 getTypeString(ExpectedTy) + "'");
4399 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4400 } else if (PFS) {
4401 // Otherwise, we default the address space of the current function.
4402 FwdDeclAS = PFS->getFunction().getAddressSpace();
4403 } else {
4404 llvm_unreachable("Unknown address space for blockaddress");
4405 }
4406 FwdRef = new GlobalVariable(
4407 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4408 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4409 }
4410
4411 ID.ConstantVal = FwdRef;
4412 ID.Kind = ValID::t_Constant;
4413 return false;
4414 }
4415
4416 // We found the function; now find the basic block. Don't use PFS, since we
4417 // might be inside a constant expression.
4418 BasicBlock *BB;
4419 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4420 if (Label.Kind == ValID::t_LocalID)
4421 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4422 else
4423 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4424 if (!BB)
4425 return error(Label.Loc, "referenced value is not a basic block");
4426 } else {
4427 if (Label.Kind == ValID::t_LocalID)
4428 return error(Label.Loc, "cannot take address of numeric label after "
4429 "the function is defined");
4431 F->getValueSymbolTable()->lookup(Label.StrVal));
4432 if (!BB)
4433 return error(Label.Loc, "referenced value is not a basic block");
4434 }
4435
4436 ID.ConstantVal = BlockAddress::get(F, BB);
4437 ID.Kind = ValID::t_Constant;
4438 return false;
4439 }
4440
4442 // ValID ::= 'dso_local_equivalent' @foo
4443 Lex.Lex();
4444
4445 ValID Fn;
4446
4447 if (parseValID(Fn, PFS))
4448 return true;
4449
4451 return error(Fn.Loc,
4452 "expected global value name in dso_local_equivalent");
4453
4454 // Try to find the function (but skip it if it's forward-referenced).
4455 GlobalValue *GV = nullptr;
4456 if (Fn.Kind == ValID::t_GlobalID) {
4457 GV = NumberedVals.get(Fn.UIntVal);
4458 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4459 GV = M->getNamedValue(Fn.StrVal);
4460 }
4461
4462 if (!GV) {
4463 // Make a placeholder global variable as a placeholder for this reference.
4464 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4465 ? ForwardRefDSOLocalEquivalentIDs
4466 : ForwardRefDSOLocalEquivalentNames;
4467 GlobalValue *&FwdRef = FwdRefMap[Fn];
4468 if (!FwdRef) {
4469 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4470 GlobalValue::InternalLinkage, nullptr, "",
4472 }
4473
4474 ID.ConstantVal = FwdRef;
4475 ID.Kind = ValID::t_Constant;
4476 return false;
4477 }
4478
4479 if (!GV->getValueType()->isFunctionTy())
4480 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4481 "in dso_local_equivalent");
4482
4483 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4484 ID.Kind = ValID::t_Constant;
4485 return false;
4486 }
4487
4488 case lltok::kw_no_cfi: {
4489 // ValID ::= 'no_cfi' @foo
4490 Lex.Lex();
4491
4492 if (parseValID(ID, PFS))
4493 return true;
4494
4495 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4496 return error(ID.Loc, "expected global value name in no_cfi");
4497
4498 ID.NoCFI = true;
4499 return false;
4500 }
4501 case lltok::kw_ptrauth: {
4502 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4503 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4504 // )? )? ')'
4505 Lex.Lex();
4506
4507 Constant *Ptr, *Key;
4508 Constant *Disc = nullptr, *AddrDisc = nullptr,
4509 *DeactivationSymbol = nullptr;
4510
4511 if (parseToken(lltok::lparen,
4512 "expected '(' in constant ptrauth expression") ||
4513 parseGlobalTypeAndValue(Ptr) ||
4514 parseToken(lltok::comma,
4515 "expected comma in constant ptrauth expression") ||
4516 parseGlobalTypeAndValue(Key))
4517 return true;
4518 // If present, parse the optional disc/addrdisc/ds.
4519 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4520 return true;
4521 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4522 return true;
4523 if (EatIfPresent(lltok::comma) &&
4524 parseGlobalTypeAndValue(DeactivationSymbol))
4525 return true;
4526 if (parseToken(lltok::rparen,
4527 "expected ')' in constant ptrauth expression"))
4528 return true;
4529
4530 if (!Ptr->getType()->isPointerTy())
4531 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4532
4533 auto *KeyC = dyn_cast<ConstantInt>(Key);
4534 if (!KeyC || KeyC->getBitWidth() != 32)
4535 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4536
4537 ConstantInt *DiscC = nullptr;
4538 if (Disc) {
4539 DiscC = dyn_cast<ConstantInt>(Disc);
4540 if (!DiscC || DiscC->getBitWidth() != 64)
4541 return error(
4542 ID.Loc,
4543 "constant ptrauth integer discriminator must be i64 constant");
4544 } else {
4545 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4546 }
4547
4548 if (AddrDisc) {
4549 if (!AddrDisc->getType()->isPointerTy())
4550 return error(
4551 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4552 } else {
4553 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4554 }
4555
4556 if (!DeactivationSymbol)
4557 DeactivationSymbol =
4559 if (!DeactivationSymbol->getType()->isPointerTy())
4560 return error(ID.Loc,
4561 "constant ptrauth deactivation symbol must be a pointer");
4562
4563 ID.ConstantVal =
4564 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4565 ID.Kind = ValID::t_Constant;
4566 return false;
4567 }
4568
4569 case lltok::kw_trunc:
4570 case lltok::kw_bitcast:
4572 case lltok::kw_inttoptr:
4574 case lltok::kw_ptrtoint: {
4575 unsigned Opc = Lex.getUIntVal();
4576 Type *DestTy = nullptr;
4577 Constant *SrcVal;
4578 Lex.Lex();
4579 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4580 parseGlobalTypeAndValue(SrcVal) ||
4581 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4582 parseType(DestTy) ||
4583 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4584 return true;
4585 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4586 return error(ID.Loc, "invalid cast opcode for cast from '" +
4587 getTypeString(SrcVal->getType()) + "' to '" +
4588 getTypeString(DestTy) + "'");
4590 SrcVal, DestTy);
4591 ID.Kind = ValID::t_Constant;
4592 return false;
4593 }
4595 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4597 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4598 case lltok::kw_udiv:
4599 return error(ID.Loc, "udiv constexprs are no longer supported");
4600 case lltok::kw_sdiv:
4601 return error(ID.Loc, "sdiv constexprs are no longer supported");
4602 case lltok::kw_urem:
4603 return error(ID.Loc, "urem constexprs are no longer supported");
4604 case lltok::kw_srem:
4605 return error(ID.Loc, "srem constexprs are no longer supported");
4606 case lltok::kw_fadd:
4607 return error(ID.Loc, "fadd constexprs are no longer supported");
4608 case lltok::kw_fsub:
4609 return error(ID.Loc, "fsub constexprs are no longer supported");
4610 case lltok::kw_fmul:
4611 return error(ID.Loc, "fmul constexprs are no longer supported");
4612 case lltok::kw_fdiv:
4613 return error(ID.Loc, "fdiv constexprs are no longer supported");
4614 case lltok::kw_frem:
4615 return error(ID.Loc, "frem constexprs are no longer supported");
4616 case lltok::kw_and:
4617 return error(ID.Loc, "and constexprs are no longer supported");
4618 case lltok::kw_or:
4619 return error(ID.Loc, "or constexprs are no longer supported");
4620 case lltok::kw_lshr:
4621 return error(ID.Loc, "lshr constexprs are no longer supported");
4622 case lltok::kw_ashr:
4623 return error(ID.Loc, "ashr constexprs are no longer supported");
4624 case lltok::kw_shl:
4625 return error(ID.Loc, "shl constexprs are no longer supported");
4626 case lltok::kw_mul:
4627 return error(ID.Loc, "mul constexprs are no longer supported");
4628 case lltok::kw_fneg:
4629 return error(ID.Loc, "fneg constexprs are no longer supported");
4630 case lltok::kw_select:
4631 return error(ID.Loc, "select constexprs are no longer supported");
4632 case lltok::kw_zext:
4633 return error(ID.Loc, "zext constexprs are no longer supported");
4634 case lltok::kw_sext:
4635 return error(ID.Loc, "sext constexprs are no longer supported");
4636 case lltok::kw_fptrunc:
4637 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4638 case lltok::kw_fpext:
4639 return error(ID.Loc, "fpext constexprs are no longer supported");
4640 case lltok::kw_uitofp:
4641 return error(ID.Loc, "uitofp constexprs are no longer supported");
4642 case lltok::kw_sitofp:
4643 return error(ID.Loc, "sitofp constexprs are no longer supported");
4644 case lltok::kw_fptoui:
4645 return error(ID.Loc, "fptoui constexprs are no longer supported");
4646 case lltok::kw_fptosi:
4647 return error(ID.Loc, "fptosi constexprs are no longer supported");
4648 case lltok::kw_icmp:
4649 return error(ID.Loc, "icmp constexprs are no longer supported");
4650 case lltok::kw_fcmp:
4651 return error(ID.Loc, "fcmp constexprs are no longer supported");
4652
4653 // Binary Operators.
4654 case lltok::kw_add:
4655 case lltok::kw_sub:
4656 case lltok::kw_xor: {
4657 bool NUW = false;
4658 bool NSW = false;
4659 unsigned Opc = Lex.getUIntVal();
4660 Constant *Val0, *Val1;
4661 Lex.Lex();
4662 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4663 Opc == Instruction::Mul) {
4664 if (EatIfPresent(lltok::kw_nuw))
4665 NUW = true;
4666 if (EatIfPresent(lltok::kw_nsw)) {
4667 NSW = true;
4668 if (EatIfPresent(lltok::kw_nuw))
4669 NUW = true;
4670 }
4671 }
4672 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4673 parseGlobalTypeAndValue(Val0) ||
4674 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4675 parseGlobalTypeAndValue(Val1) ||
4676 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4677 return true;
4678 if (Val0->getType() != Val1->getType())
4679 return error(ID.Loc, "operands of constexpr must have same type");
4680 // Check that the type is valid for the operator.
4681 if (!Val0->getType()->isIntOrIntVectorTy())
4682 return error(ID.Loc,
4683 "constexpr requires integer or integer vector operands");
4684 unsigned Flags = 0;
4687 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4688 ID.Kind = ValID::t_Constant;
4689 return false;
4690 }
4691
4692 case lltok::kw_splat: {
4693 Lex.Lex();
4694 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4695 return true;
4696 Constant *C;
4697 if (parseGlobalTypeAndValue(C))
4698 return true;
4699 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4700 return true;
4701
4702 ID.ConstantVal = C;
4704 return false;
4705 }
4706
4711 unsigned Opc = Lex.getUIntVal();
4713 GEPNoWrapFlags NW;
4714 bool HasInRange = false;
4715 APSInt InRangeStart;
4716 APSInt InRangeEnd;
4717 Type *Ty;
4718 Lex.Lex();
4719
4720 if (Opc == Instruction::GetElementPtr) {
4721 while (true) {
4722 if (EatIfPresent(lltok::kw_inbounds))
4724 else if (EatIfPresent(lltok::kw_nusw))
4726 else if (EatIfPresent(lltok::kw_nuw))
4728 else
4729 break;
4730 }
4731
4732 if (EatIfPresent(lltok::kw_inrange)) {
4733 if (parseToken(lltok::lparen, "expected '('"))
4734 return true;
4735 if (Lex.getKind() != lltok::APSInt)
4736 return tokError("expected integer");
4737 InRangeStart = Lex.getAPSIntVal();
4738 Lex.Lex();
4739 if (parseToken(lltok::comma, "expected ','"))
4740 return true;
4741 if (Lex.getKind() != lltok::APSInt)
4742 return tokError("expected integer");
4743 InRangeEnd = Lex.getAPSIntVal();
4744 Lex.Lex();
4745 if (parseToken(lltok::rparen, "expected ')'"))
4746 return true;
4747 HasInRange = true;
4748 }
4749 }
4750
4751 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4752 return true;
4753
4754 if (Opc == Instruction::GetElementPtr) {
4755 if (parseType(Ty) ||
4756 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4757 return true;
4758 }
4759
4760 if (parseGlobalValueVector(Elts) ||
4761 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4762 return true;
4763
4764 if (Opc == Instruction::GetElementPtr) {
4765 if (Elts.size() == 0 ||
4766 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4767 return error(ID.Loc, "base of getelementptr must be a pointer");
4768
4769 Type *BaseType = Elts[0]->getType();
4770 std::optional<ConstantRange> InRange;
4771 if (HasInRange) {
4772 unsigned IndexWidth =
4773 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4774 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4775 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4776 if (InRangeStart.sge(InRangeEnd))
4777 return error(ID.Loc, "expected end to be larger than start");
4778 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4779 }
4780
4781 unsigned GEPWidth =
4782 BaseType->isVectorTy()
4783 ? cast<FixedVectorType>(BaseType)->getNumElements()
4784 : 0;
4785
4786 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4787 for (Constant *Val : Indices) {
4788 Type *ValTy = Val->getType();
4789 if (!ValTy->isIntOrIntVectorTy())
4790 return error(ID.Loc, "getelementptr index must be an integer");
4791 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4792 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4793 if (GEPWidth && (ValNumEl != GEPWidth))
4794 return error(
4795 ID.Loc,
4796 "getelementptr vector index has a wrong number of elements");
4797 // GEPWidth may have been unknown because the base is a scalar,
4798 // but it is known now.
4799 GEPWidth = ValNumEl;
4800 }
4801 }
4802
4803 SmallPtrSet<Type*, 4> Visited;
4804 if (!Indices.empty() && !Ty->isSized(&Visited))
4805 return error(ID.Loc, "base element of getelementptr must be sized");
4806
4808 return error(ID.Loc, "invalid base element for constant getelementptr");
4809
4810 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4811 return error(ID.Loc, "invalid getelementptr indices");
4812
4813 ID.ConstantVal =
4814 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4815 } else if (Opc == Instruction::ShuffleVector) {
4816 if (Elts.size() != 3)
4817 return error(ID.Loc, "expected three operands to shufflevector");
4818 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4819 return error(ID.Loc, "invalid operands to shufflevector");
4820 SmallVector<int, 16> Mask;
4822 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4823 } else if (Opc == Instruction::ExtractElement) {
4824 if (Elts.size() != 2)
4825 return error(ID.Loc, "expected two operands to extractelement");
4826 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4827 return error(ID.Loc, "invalid extractelement operands");
4828 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4829 } else {
4830 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4831 if (Elts.size() != 3)
4832 return error(ID.Loc, "expected three operands to insertelement");
4833 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4834 return error(ID.Loc, "invalid insertelement operands");
4835 ID.ConstantVal =
4836 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4837 }
4838
4839 ID.Kind = ValID::t_Constant;
4840 return false;
4841 }
4842 }
4843
4844 Lex.Lex();
4845 return false;
4846}
4847
4848/// parseGlobalValue - parse a global value with the specified type.
4849bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4850 C = nullptr;
4851 ValID ID;
4852 Value *V = nullptr;
4853 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4854 convertValIDToValue(Ty, ID, V, nullptr);
4855 if (V && !(C = dyn_cast<Constant>(V)))
4856 return error(ID.Loc, "global values must be constants");
4857 return Parsed;
4858}
4859
4860bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4861 Type *Ty = nullptr;
4862 return parseType(Ty) || parseGlobalValue(Ty, V);
4863}
4864
4865bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4866 C = nullptr;
4867
4868 LocTy KwLoc = Lex.getLoc();
4869 if (!EatIfPresent(lltok::kw_comdat))
4870 return false;
4871
4872 if (EatIfPresent(lltok::lparen)) {
4873 if (Lex.getKind() != lltok::ComdatVar)
4874 return tokError("expected comdat variable");
4875 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4876 Lex.Lex();
4877 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4878 return true;
4879 } else {
4880 if (GlobalName.empty())
4881 return tokError("comdat cannot be unnamed");
4882 C = getComdat(std::string(GlobalName), KwLoc);
4883 }
4884
4885 return false;
4886}
4887
4888/// parseGlobalValueVector
4889/// ::= /*empty*/
4890/// ::= TypeAndValue (',' TypeAndValue)*
4891bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4892 // Empty list.
4893 if (Lex.getKind() == lltok::rbrace ||
4894 Lex.getKind() == lltok::rsquare ||
4895 Lex.getKind() == lltok::greater ||
4896 Lex.getKind() == lltok::rparen)
4897 return false;
4898
4899 do {
4900 // Let the caller deal with inrange.
4901 if (Lex.getKind() == lltok::kw_inrange)
4902 return false;
4903
4904 Constant *C;
4905 if (parseGlobalTypeAndValue(C))
4906 return true;
4907 Elts.push_back(C);
4908 } while (EatIfPresent(lltok::comma));
4909
4910 return false;
4911}
4912
4913bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4915 if (parseMDNodeVector(Elts))
4916 return true;
4917
4918 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4919 return false;
4920}
4921
4922/// MDNode:
4923/// ::= !{ ... }
4924/// ::= !7
4925/// ::= !DILocation(...)
4926bool LLParser::parseMDNode(MDNode *&N) {
4927 if (Lex.getKind() == lltok::MetadataVar)
4928 return parseSpecializedMDNode(N);
4929
4930 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4931}
4932
4933bool LLParser::parseMDNodeTail(MDNode *&N) {
4934 // !{ ... }
4935 if (Lex.getKind() == lltok::lbrace)
4936 return parseMDTuple(N);
4937
4938 // !42
4939 return parseMDNodeID(N);
4940}
4941
4942namespace {
4943
4944/// Structure to represent an optional metadata field.
4945template <class FieldTy> struct MDFieldImpl {
4946 typedef MDFieldImpl ImplTy;
4947 FieldTy Val;
4948 bool Seen;
4949
4950 void assign(FieldTy Val) {
4951 Seen = true;
4952 this->Val = std::move(Val);
4953 }
4954
4955 explicit MDFieldImpl(FieldTy Default)
4956 : Val(std::move(Default)), Seen(false) {}
4957};
4958
4959/// Structure to represent an optional metadata field that
4960/// can be of either type (A or B) and encapsulates the
4961/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4962/// to reimplement the specifics for representing each Field.
4963template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4964 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4965 FieldTypeA A;
4966 FieldTypeB B;
4967 bool Seen;
4968
4969 enum {
4970 IsInvalid = 0,
4971 IsTypeA = 1,
4972 IsTypeB = 2
4973 } WhatIs;
4974
4975 void assign(FieldTypeA A) {
4976 Seen = true;
4977 this->A = std::move(A);
4978 WhatIs = IsTypeA;
4979 }
4980
4981 void assign(FieldTypeB B) {
4982 Seen = true;
4983 this->B = std::move(B);
4984 WhatIs = IsTypeB;
4985 }
4986
4987 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4988 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4989 WhatIs(IsInvalid) {}
4990};
4991
4992struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4993 uint64_t Max;
4994
4995 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4996 : ImplTy(Default), Max(Max) {}
4997};
4998
4999struct LineField : public MDUnsignedField {
5000 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5001};
5002
5003struct ColumnField : public MDUnsignedField {
5004 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5005};
5006
5007struct DwarfTagField : public MDUnsignedField {
5008 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
5009 DwarfTagField(dwarf::Tag DefaultTag)
5010 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
5011};
5012
5013struct DwarfMacinfoTypeField : public MDUnsignedField {
5014 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
5015 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
5016 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
5017};
5018
5019struct DwarfAttEncodingField : public MDUnsignedField {
5020 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5021};
5022
5023struct DwarfVirtualityField : public MDUnsignedField {
5024 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5025};
5026
5027struct DwarfLangField : public MDUnsignedField {
5028 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5029};
5030
5031struct DwarfSourceLangNameField : public MDUnsignedField {
5032 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5033};
5034
5035struct DwarfLangDialectField : public MDUnsignedField {
5036 DwarfLangDialectField()
5037 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5038};
5039
5040struct DwarfCCField : public MDUnsignedField {
5041 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5042};
5043
5044struct DwarfEnumKindField : public MDUnsignedField {
5045 DwarfEnumKindField()
5046 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5047 dwarf::DW_APPLE_ENUM_KIND_max) {}
5048};
5049
5050struct EmissionKindField : public MDUnsignedField {
5051 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5052};
5053
5054struct FixedPointKindField : public MDUnsignedField {
5055 FixedPointKindField()
5056 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5057};
5058
5059struct NameTableKindField : public MDUnsignedField {
5060 NameTableKindField()
5061 : MDUnsignedField(
5062 0, (unsigned)
5063 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5064};
5065
5066struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5067 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5068};
5069
5070struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5071 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5072};
5073
5074struct MDAPSIntField : public MDFieldImpl<APSInt> {
5075 MDAPSIntField() : ImplTy(APSInt()) {}
5076};
5077
5078struct MDSignedField : public MDFieldImpl<int64_t> {
5079 int64_t Min = INT64_MIN;
5080 int64_t Max = INT64_MAX;
5081
5082 MDSignedField(int64_t Default = 0)
5083 : ImplTy(Default) {}
5084 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5085 : ImplTy(Default), Min(Min), Max(Max) {}
5086};
5087
5088struct MDBoolField : public MDFieldImpl<bool> {
5089 MDBoolField(bool Default = false) : ImplTy(Default) {}
5090};
5091
5092struct MDField : public MDFieldImpl<Metadata *> {
5093 bool AllowNull;
5094
5095 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5096};
5097
5098struct MDStringField : public MDFieldImpl<MDString *> {
5099 enum class EmptyIs {
5100 Null, //< Allow empty input string, map to nullptr
5101 Empty, //< Allow empty input string, map to an empty MDString
5102 Error, //< Disallow empty string, map to an error
5103 } EmptyIs;
5104 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5105 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5106};
5107
5108struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5109 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5110};
5111
5112struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5113 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5114};
5115
5116struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5117 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5118 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5119
5120 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5121 bool AllowNull = true)
5122 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5123
5124 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5125 bool isMDField() const { return WhatIs == IsTypeB; }
5126 int64_t getMDSignedValue() const {
5127 assert(isMDSignedField() && "Wrong field type");
5128 return A.Val;
5129 }
5130 Metadata *getMDFieldValue() const {
5131 assert(isMDField() && "Wrong field type");
5132 return B.Val;
5133 }
5134};
5135
5136struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5137 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5138 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5139
5140 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5141 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5142
5143 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5144 bool isMDField() const { return WhatIs == IsTypeB; }
5145 uint64_t getMDUnsignedValue() const {
5146 assert(isMDUnsignedField() && "Wrong field type");
5147 return A.Val;
5148 }
5149 Metadata *getMDFieldValue() const {
5150 assert(isMDField() && "Wrong field type");
5151 return B.Val;
5152 }
5153
5154 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5155 if (isMDUnsignedField())
5157 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5158 if (isMDField())
5159 return getMDFieldValue();
5160 return nullptr;
5161 }
5162};
5163
5164} // end anonymous namespace
5165
5166namespace llvm {
5167
5168template <>
5169bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5170 if (Lex.getKind() != lltok::APSInt)
5171 return tokError("expected integer");
5172
5173 Result.assign(Lex.getAPSIntVal());
5174 Lex.Lex();
5175 return false;
5176}
5177
5178template <>
5179bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5180 MDUnsignedField &Result) {
5181 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5182 return tokError("expected unsigned integer");
5183
5184 auto &U = Lex.getAPSIntVal();
5185 if (U.ugt(Result.Max))
5186 return tokError("value for '" + Name + "' too large, limit is " +
5187 Twine(Result.Max));
5188 Result.assign(U.getZExtValue());
5189 assert(Result.Val <= Result.Max && "Expected value in range");
5190 Lex.Lex();
5191 return false;
5192}
5193
5194template <>
5195bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5196 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5197}
5198template <>
5199bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5200 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5201}
5202
5203template <>
5204bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5205 if (Lex.getKind() == lltok::APSInt)
5206 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5207
5208 if (Lex.getKind() != lltok::DwarfTag)
5209 return tokError("expected DWARF tag");
5210
5211 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5213 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5214 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5215
5216 Result.assign(Tag);
5217 Lex.Lex();
5218 return false;
5219}
5220
5221template <>
5222bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5223 DwarfMacinfoTypeField &Result) {
5224 if (Lex.getKind() == lltok::APSInt)
5225 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5226
5227 if (Lex.getKind() != lltok::DwarfMacinfo)
5228 return tokError("expected DWARF macinfo type");
5229
5230 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5231 if (Macinfo == dwarf::DW_MACINFO_invalid)
5232 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5233 Lex.getStrVal() + "'");
5234 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5235
5236 Result.assign(Macinfo);
5237 Lex.Lex();
5238 return false;
5239}
5240
5241template <>
5242bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5243 DwarfVirtualityField &Result) {
5244 if (Lex.getKind() == lltok::APSInt)
5245 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5246
5247 if (Lex.getKind() != lltok::DwarfVirtuality)
5248 return tokError("expected DWARF virtuality code");
5249
5250 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5251 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5252 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5253 Lex.getStrVal() + "'");
5254 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5255 Result.assign(Virtuality);
5256 Lex.Lex();
5257 return false;
5258}
5259
5260template <>
5261bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5262 DwarfEnumKindField &Result) {
5263 if (Lex.getKind() == lltok::APSInt)
5264 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5265
5266 if (Lex.getKind() != lltok::DwarfEnumKind)
5267 return tokError("expected DWARF enum kind code");
5268
5269 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5270 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5271 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5272 Lex.getStrVal() + "'");
5273 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5274 Result.assign(EnumKind);
5275 Lex.Lex();
5276 return false;
5277}
5278
5279template <>
5280bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5281 if (Lex.getKind() == lltok::APSInt)
5282 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5283
5284 if (Lex.getKind() != lltok::DwarfLang)
5285 return tokError("expected DWARF language");
5286
5287 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5288 if (!Lang)
5289 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5290 "'");
5291 assert(Lang <= Result.Max && "Expected valid DWARF language");
5292 Result.assign(Lang);
5293 Lex.Lex();
5294 return false;
5295}
5296
5297template <>
5298bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5299 DwarfSourceLangNameField &Result) {
5300 if (Lex.getKind() == lltok::APSInt)
5301 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5302
5303 if (Lex.getKind() != lltok::DwarfSourceLangName)
5304 return tokError("expected DWARF source language name");
5305
5306 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5307 if (!Lang)
5308 return tokError("invalid DWARF source language name" + Twine(" '") +
5309 Lex.getStrVal() + "'");
5310 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5311 Result.assign(Lang);
5312 Lex.Lex();
5313 return false;
5314}
5315
5316template <>
5317bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5318 DwarfLangDialectField &Result) {
5319 // Specifying the dialect field requires a recognized dialect: simt or
5320 // tile (numerically 1 or 2). Omitting the field is the only way to
5321 // express "no dialect specified".
5322 if (Lex.getKind() == lltok::APSInt) {
5323 if (Lex.getAPSIntVal() == 0)
5324 return tokError("value for 'dialect' must be a known DWARF language "
5325 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5326 "DW_LLVM_LANG_DIALECT_tile)");
5327 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5328 }
5329
5330 if (Lex.getKind() != lltok::DwarfLangDialect)
5331 return tokError("expected DWARF language dialect");
5332
5333 StringRef DialectString = Lex.getStrVal();
5334 // getLanguageDialect returns a sentinel above Result.Max for unknown
5335 // spellings; only simt and tile are registered, so any unrecognized
5336 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5337 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5338 if (Dialect > Result.Max)
5339 return tokError("invalid DWARF language dialect" + Twine(" '") +
5340 DialectString + "'");
5341 Result.assign(Dialect);
5342 Lex.Lex();
5343 return false;
5344}
5345
5346template <>
5347bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5348 if (Lex.getKind() == lltok::APSInt)
5349 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5350
5351 if (Lex.getKind() != lltok::DwarfCC)
5352 return tokError("expected DWARF calling convention");
5353
5354 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5355 if (!CC)
5356 return tokError("invalid DWARF calling convention" + Twine(" '") +
5357 Lex.getStrVal() + "'");
5358 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5359 Result.assign(CC);
5360 Lex.Lex();
5361 return false;
5362}
5363
5364template <>
5365bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5366 EmissionKindField &Result) {
5367 if (Lex.getKind() == lltok::APSInt)
5368 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5369
5370 if (Lex.getKind() != lltok::EmissionKind)
5371 return tokError("expected emission kind");
5372
5373 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5374 if (!Kind)
5375 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5376 "'");
5377 assert(*Kind <= Result.Max && "Expected valid emission kind");
5378 Result.assign(*Kind);
5379 Lex.Lex();
5380 return false;
5381}
5382
5383template <>
5384bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5385 FixedPointKindField &Result) {
5386 if (Lex.getKind() == lltok::APSInt)
5387 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5388
5389 if (Lex.getKind() != lltok::FixedPointKind)
5390 return tokError("expected fixed-point kind");
5391
5392 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5393 if (!Kind)
5394 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5395 "'");
5396 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5397 Result.assign(*Kind);
5398 Lex.Lex();
5399 return false;
5400}
5401
5402template <>
5403bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5404 NameTableKindField &Result) {
5405 if (Lex.getKind() == lltok::APSInt)
5406 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5407
5408 if (Lex.getKind() != lltok::NameTableKind)
5409 return tokError("expected nameTable kind");
5410
5411 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5412 if (!Kind)
5413 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5414 "'");
5415 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5416 Result.assign((unsigned)*Kind);
5417 Lex.Lex();
5418 return false;
5419}
5420
5421template <>
5422bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5423 DwarfAttEncodingField &Result) {
5424 if (Lex.getKind() == lltok::APSInt)
5425 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5426
5427 if (Lex.getKind() != lltok::DwarfAttEncoding)
5428 return tokError("expected DWARF type attribute encoding");
5429
5430 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5431 if (!Encoding)
5432 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5433 Lex.getStrVal() + "'");
5434 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5435 Result.assign(Encoding);
5436 Lex.Lex();
5437 return false;
5438}
5439
5440/// DIFlagField
5441/// ::= uint32
5442/// ::= DIFlagVector
5443/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5444template <>
5445bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5446
5447 // parser for a single flag.
5448 auto parseFlag = [&](DINode::DIFlags &Val) {
5449 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5450 uint32_t TempVal = static_cast<uint32_t>(Val);
5451 bool Res = parseUInt32(TempVal);
5452 Val = static_cast<DINode::DIFlags>(TempVal);
5453 return Res;
5454 }
5455
5456 if (Lex.getKind() != lltok::DIFlag)
5457 return tokError("expected debug info flag");
5458
5459 Val = DINode::getFlag(Lex.getStrVal());
5460 if (!Val)
5461 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5462 "'");
5463 Lex.Lex();
5464 return false;
5465 };
5466
5467 // parse the flags and combine them together.
5468 DINode::DIFlags Combined = DINode::FlagZero;
5469 do {
5470 DINode::DIFlags Val;
5471 if (parseFlag(Val))
5472 return true;
5473 Combined |= Val;
5474 } while (EatIfPresent(lltok::bar));
5475
5476 Result.assign(Combined);
5477 return false;
5478}
5479
5480/// DISPFlagField
5481/// ::= uint32
5482/// ::= DISPFlagVector
5483/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5484template <>
5485bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5486
5487 // parser for a single flag.
5488 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5489 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5490 uint32_t TempVal = static_cast<uint32_t>(Val);
5491 bool Res = parseUInt32(TempVal);
5492 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5493 return Res;
5494 }
5495
5496 if (Lex.getKind() != lltok::DISPFlag)
5497 return tokError("expected debug info flag");
5498
5499 Val = DISubprogram::getFlag(Lex.getStrVal());
5500 if (!Val)
5501 return tokError(Twine("invalid subprogram debug info flag '") +
5502 Lex.getStrVal() + "'");
5503 Lex.Lex();
5504 return false;
5505 };
5506
5507 // parse the flags and combine them together.
5508 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5509 do {
5511 if (parseFlag(Val))
5512 return true;
5513 Combined |= Val;
5514 } while (EatIfPresent(lltok::bar));
5515
5516 Result.assign(Combined);
5517 return false;
5518}
5519
5520template <>
5521bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5522 if (Lex.getKind() != lltok::APSInt)
5523 return tokError("expected signed integer");
5524
5525 auto &S = Lex.getAPSIntVal();
5526 if (S < Result.Min)
5527 return tokError("value for '" + Name + "' too small, limit is " +
5528 Twine(Result.Min));
5529 if (S > Result.Max)
5530 return tokError("value for '" + Name + "' too large, limit is " +
5531 Twine(Result.Max));
5532 Result.assign(S.getExtValue());
5533 assert(Result.Val >= Result.Min && "Expected value in range");
5534 assert(Result.Val <= Result.Max && "Expected value in range");
5535 Lex.Lex();
5536 return false;
5537}
5538
5539template <>
5540bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5541 switch (Lex.getKind()) {
5542 default:
5543 return tokError("expected 'true' or 'false'");
5544 case lltok::kw_true:
5545 Result.assign(true);
5546 break;
5547 case lltok::kw_false:
5548 Result.assign(false);
5549 break;
5550 }
5551 Lex.Lex();
5552 return false;
5553}
5554
5555template <>
5556bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5557 if (Lex.getKind() == lltok::kw_null) {
5558 if (!Result.AllowNull)
5559 return tokError("'" + Name + "' cannot be null");
5560 Lex.Lex();
5561 Result.assign(nullptr);
5562 return false;
5563 }
5564
5565 Metadata *MD;
5566 if (parseMetadata(MD, nullptr))
5567 return true;
5568
5569 Result.assign(MD);
5570 return false;
5571}
5572
5573template <>
5574bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5575 MDSignedOrMDField &Result) {
5576 // Try to parse a signed int.
5577 if (Lex.getKind() == lltok::APSInt) {
5578 MDSignedField Res = Result.A;
5579 if (!parseMDField(Loc, Name, Res)) {
5580 Result.assign(Res);
5581 return false;
5582 }
5583 return true;
5584 }
5585
5586 // Otherwise, try to parse as an MDField.
5587 MDField Res = Result.B;
5588 if (!parseMDField(Loc, Name, Res)) {
5589 Result.assign(Res);
5590 return false;
5591 }
5592
5593 return true;
5594}
5595
5596template <>
5597bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5598 MDUnsignedOrMDField &Result) {
5599 // Try to parse an unsigned int.
5600 if (Lex.getKind() == lltok::APSInt) {
5601 MDUnsignedField Res = Result.A;
5602 if (!parseMDField(Loc, Name, Res)) {
5603 Result.assign(Res);
5604 return false;
5605 }
5606 return true;
5607 }
5608
5609 // Otherwise, try to parse as an MDField.
5610 MDField Res = Result.B;
5611 if (!parseMDField(Loc, Name, Res)) {
5612 Result.assign(Res);
5613 return false;
5614 }
5615
5616 return true;
5617}
5618
5619template <>
5620bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5621 LocTy ValueLoc = Lex.getLoc();
5622 std::string S;
5623 if (parseStringConstant(S))
5624 return true;
5625
5626 if (S.empty()) {
5627 switch (Result.EmptyIs) {
5628 case MDStringField::EmptyIs::Null:
5629 Result.assign(nullptr);
5630 return false;
5631 case MDStringField::EmptyIs::Empty:
5632 break;
5633 case MDStringField::EmptyIs::Error:
5634 return error(ValueLoc, "'" + Name + "' cannot be empty");
5635 }
5636 }
5637
5638 Result.assign(MDString::get(Context, S));
5639 return false;
5640}
5641
5642template <>
5643bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5645 if (parseMDNodeVector(MDs))
5646 return true;
5647
5648 Result.assign(std::move(MDs));
5649 return false;
5650}
5651
5652template <>
5653bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5654 ChecksumKindField &Result) {
5655 std::optional<DIFile::ChecksumKind> CSKind =
5656 DIFile::getChecksumKind(Lex.getStrVal());
5657
5658 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5659 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5660 "'");
5661
5662 Result.assign(*CSKind);
5663 Lex.Lex();
5664 return false;
5665}
5666
5667} // end namespace llvm
5668
5669template <class ParserTy>
5670bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5671 do {
5672 if (Lex.getKind() != lltok::LabelStr)
5673 return tokError("expected field label here");
5674
5675 if (ParseField())
5676 return true;
5677 } while (EatIfPresent(lltok::comma));
5678
5679 return false;
5680}
5681
5682template <class ParserTy>
5683bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5684 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5685 Lex.Lex();
5686
5687 if (parseToken(lltok::lparen, "expected '(' here"))
5688 return true;
5689 if (Lex.getKind() != lltok::rparen)
5690 if (parseMDFieldsImplBody(ParseField))
5691 return true;
5692
5693 ClosingLoc = Lex.getLoc();
5694 return parseToken(lltok::rparen, "expected ')' here");
5695}
5696
5697template <class FieldTy>
5698bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5699 if (Result.Seen)
5700 return tokError("field '" + Name + "' cannot be specified more than once");
5701
5702 LocTy Loc = Lex.getLoc();
5703 Lex.Lex();
5704 return parseMDField(Loc, Name, Result);
5705}
5706
5707bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5708 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5709
5710#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5711 if (Lex.getStrVal() == #CLASS) \
5712 return parse##CLASS(N, IsDistinct);
5713#include "llvm/IR/Metadata.def"
5714
5715 return tokError("expected metadata type");
5716}
5717
5718#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5719#define NOP_FIELD(NAME, TYPE, INIT)
5720#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5721 if (!NAME.Seen) \
5722 return error(ClosingLoc, "missing required field '" #NAME "'");
5723#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5724 if (Lex.getStrVal() == #NAME) \
5725 return parseMDField(#NAME, NAME);
5726#define PARSE_MD_FIELDS() \
5727 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5728 do { \
5729 LocTy ClosingLoc; \
5730 if (parseMDFieldsImpl( \
5731 [&]() -> bool { \
5732 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5733 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5734 "'"); \
5735 }, \
5736 ClosingLoc)) \
5737 return true; \
5738 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5739 } while (false)
5740#define GET_OR_DISTINCT(CLASS, ARGS) \
5741 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5742
5743/// parseDILocationFields:
5744/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5745/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5746bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5747#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5748 OPTIONAL(line, LineField, ); \
5749 OPTIONAL(column, ColumnField, ); \
5750 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5751 OPTIONAL(inlinedAt, MDField, ); \
5752 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5753 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5754 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5756#undef VISIT_MD_FIELDS
5757
5758 Result = GET_OR_DISTINCT(
5759 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5760 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5761 return false;
5762}
5763
5764/// parseDIAssignID:
5765/// ::= distinct !DIAssignID()
5766bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5767 if (!IsDistinct)
5768 return tokError("missing 'distinct', required for !DIAssignID()");
5769
5770 Lex.Lex();
5771
5772 // Now eat the parens.
5773 if (parseToken(lltok::lparen, "expected '(' here"))
5774 return true;
5775 if (parseToken(lltok::rparen, "expected ')' here"))
5776 return true;
5777
5779 return false;
5780}
5781
5782/// parseGenericDINode:
5783/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5784bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5785#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5786 REQUIRED(tag, DwarfTagField, ); \
5787 OPTIONAL(header, MDStringField, ); \
5788 OPTIONAL(operands, MDFieldList, );
5790#undef VISIT_MD_FIELDS
5791
5792 Result = GET_OR_DISTINCT(GenericDINode,
5793 (Context, tag.Val, header.Val, operands.Val));
5794 return false;
5795}
5796
5797/// parseDISubrangeType:
5798/// ::= !DISubrangeType(name: "whatever", file: !0,
5799/// line: 7, scope: !1, baseType: !2, size: 32,
5800/// align: 32, flags: 0, lowerBound: !3
5801/// upperBound: !4, stride: !5, bias: !6)
5802bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5803#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5804 OPTIONAL(name, MDStringField, ); \
5805 OPTIONAL(file, MDField, ); \
5806 OPTIONAL(line, LineField, ); \
5807 OPTIONAL(scope, MDField, ); \
5808 OPTIONAL(baseType, MDField, ); \
5809 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5810 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5811 OPTIONAL(flags, DIFlagField, ); \
5812 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5813 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5814 OPTIONAL(stride, MDSignedOrMDField, ); \
5815 OPTIONAL(bias, MDSignedOrMDField, );
5817#undef VISIT_MD_FIELDS
5818
5819 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5820 if (Bound.isMDSignedField())
5822 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5823 if (Bound.isMDField())
5824 return Bound.getMDFieldValue();
5825 return nullptr;
5826 };
5827
5828 Metadata *LowerBound = convToMetadata(lowerBound);
5829 Metadata *UpperBound = convToMetadata(upperBound);
5830 Metadata *Stride = convToMetadata(stride);
5831 Metadata *Bias = convToMetadata(bias);
5832
5834 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5835 size.getValueAsMetadata(Context), align.Val, flags.Val,
5836 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5837
5838 return false;
5839}
5840
5841/// parseDISubrange:
5842/// ::= !DISubrange(count: 30, lowerBound: 2)
5843/// ::= !DISubrange(count: !node, lowerBound: 2)
5844/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5845bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5846#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5847 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5848 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5849 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5850 OPTIONAL(stride, MDSignedOrMDField, );
5852#undef VISIT_MD_FIELDS
5853
5854 Metadata *Count = nullptr;
5855 Metadata *LowerBound = nullptr;
5856 Metadata *UpperBound = nullptr;
5857 Metadata *Stride = nullptr;
5858
5859 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5860 if (Bound.isMDSignedField())
5862 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5863 if (Bound.isMDField())
5864 return Bound.getMDFieldValue();
5865 return nullptr;
5866 };
5867
5868 Count = convToMetadata(count);
5869 LowerBound = convToMetadata(lowerBound);
5870 UpperBound = convToMetadata(upperBound);
5871 Stride = convToMetadata(stride);
5872
5873 Result = GET_OR_DISTINCT(DISubrange,
5874 (Context, Count, LowerBound, UpperBound, Stride));
5875
5876 return false;
5877}
5878
5879/// parseDIGenericSubrange:
5880/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5881/// !node3)
5882bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5883#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5884 OPTIONAL(count, MDSignedOrMDField, ); \
5885 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5886 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5887 OPTIONAL(stride, MDSignedOrMDField, );
5889#undef VISIT_MD_FIELDS
5890
5891 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5892 if (Bound.isMDSignedField())
5893 return DIExpression::get(
5894 Context, {dwarf::DW_OP_consts,
5895 static_cast<uint64_t>(Bound.getMDSignedValue())});
5896 if (Bound.isMDField())
5897 return Bound.getMDFieldValue();
5898 return nullptr;
5899 };
5900
5901 Metadata *Count = ConvToMetadata(count);
5902 Metadata *LowerBound = ConvToMetadata(lowerBound);
5903 Metadata *UpperBound = ConvToMetadata(upperBound);
5904 Metadata *Stride = ConvToMetadata(stride);
5905
5906 Result = GET_OR_DISTINCT(DIGenericSubrange,
5907 (Context, Count, LowerBound, UpperBound, Stride));
5908
5909 return false;
5910}
5911
5912/// parseDIEnumerator:
5913/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5914bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5915#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5916 REQUIRED(name, MDStringField, ); \
5917 REQUIRED(value, MDAPSIntField, ); \
5918 OPTIONAL(isUnsigned, MDBoolField, (false));
5920#undef VISIT_MD_FIELDS
5921
5922 if (isUnsigned.Val && value.Val.isNegative())
5923 return tokError("unsigned enumerator with negative value");
5924
5925 APSInt Value(value.Val);
5926 // Add a leading zero so that unsigned values with the msb set are not
5927 // mistaken for negative values when used for signed enumerators.
5928 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5929 Value = Value.zext(Value.getBitWidth() + 1);
5930
5931 Result =
5932 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5933
5934 return false;
5935}
5936
5937/// parseDIBasicType:
5938/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5939/// encoding: DW_ATE_encoding, flags: 0)
5940bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5943 OPTIONAL(name, MDStringField, ); \
5944 OPTIONAL(file, MDField, ); \
5945 OPTIONAL(line, LineField, ); \
5946 OPTIONAL(scope, MDField, ); \
5947 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5948 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5949 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5950 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5951 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5952 OPTIONAL(flags, DIFlagField, );
5954#undef VISIT_MD_FIELDS
5955
5957 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5958 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5959 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5960 return false;
5961}
5962
5963/// parseDIFixedPointType:
5964/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5965/// align: 32, encoding: DW_ATE_signed_fixed,
5966/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5967/// denominator: 8)
5968bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5969#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5970 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5971 OPTIONAL(name, MDStringField, ); \
5972 OPTIONAL(file, MDField, ); \
5973 OPTIONAL(line, LineField, ); \
5974 OPTIONAL(scope, MDField, ); \
5975 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5976 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5977 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5978 OPTIONAL(flags, DIFlagField, ); \
5979 OPTIONAL(kind, FixedPointKindField, ); \
5980 OPTIONAL(factor, MDSignedField, ); \
5981 OPTIONAL(numerator, MDAPSIntField, ); \
5982 OPTIONAL(denominator, MDAPSIntField, );
5984#undef VISIT_MD_FIELDS
5985
5986 Result = GET_OR_DISTINCT(DIFixedPointType,
5987 (Context, tag.Val, name.Val, file.Val, line.Val,
5988 scope.Val, size.getValueAsMetadata(Context),
5989 align.Val, encoding.Val, flags.Val, kind.Val,
5990 factor.Val, numerator.Val, denominator.Val));
5991 return false;
5992}
5993
5994/// parseDIStringType:
5995/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5996bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5997#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5998 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5999 OPTIONAL(name, MDStringField, ); \
6000 OPTIONAL(stringLength, MDField, ); \
6001 OPTIONAL(stringLengthExpression, MDField, ); \
6002 OPTIONAL(stringLocationExpression, MDField, ); \
6003 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6004 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6005 OPTIONAL(encoding, DwarfAttEncodingField, );
6007#undef VISIT_MD_FIELDS
6008
6010 DIStringType,
6011 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
6012 stringLocationExpression.Val, size.getValueAsMetadata(Context),
6013 align.Val, encoding.Val));
6014 return false;
6015}
6016
6017/// parseDIDerivedType:
6018/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
6019/// line: 7, scope: !1, baseType: !2, size: 32,
6020/// align: 32, offset: 0, flags: 0, extraData: !3,
6021/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6022/// ptrAuthIsAddressDiscriminated: true,
6023/// ptrAuthExtraDiscriminator: 0x1234,
6024/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6025/// )
6026bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6027#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6028 REQUIRED(tag, DwarfTagField, ); \
6029 OPTIONAL(name, MDStringField, ); \
6030 OPTIONAL(file, MDField, ); \
6031 OPTIONAL(line, LineField, ); \
6032 OPTIONAL(scope, MDField, ); \
6033 REQUIRED(baseType, MDField, ); \
6034 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6035 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6036 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6037 OPTIONAL(flags, DIFlagField, ); \
6038 OPTIONAL(extraData, MDField, ); \
6039 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6040 OPTIONAL(annotations, MDField, ); \
6041 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6042 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6043 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6044 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6045 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6047#undef VISIT_MD_FIELDS
6048
6049 std::optional<unsigned> DWARFAddressSpace;
6050 if (dwarfAddressSpace.Val != UINT32_MAX)
6051 DWARFAddressSpace = dwarfAddressSpace.Val;
6052 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6053 if (ptrAuthKey.Val)
6054 PtrAuthData.emplace(
6055 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6056 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6057 ptrAuthAuthenticatesNullValues.Val);
6058
6060 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6061 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6062 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6063 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6064 return false;
6065}
6066
6067bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6068#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6069 REQUIRED(tag, DwarfTagField, ); \
6070 OPTIONAL(name, MDStringField, ); \
6071 OPTIONAL(file, MDField, ); \
6072 OPTIONAL(line, LineField, ); \
6073 OPTIONAL(scope, MDField, ); \
6074 OPTIONAL(baseType, MDField, ); \
6075 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6076 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6077 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6078 OPTIONAL(flags, DIFlagField, ); \
6079 OPTIONAL(elements, MDField, ); \
6080 OPTIONAL(runtimeLang, DwarfLangField, ); \
6081 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6082 OPTIONAL(vtableHolder, MDField, ); \
6083 OPTIONAL(templateParams, MDField, ); \
6084 OPTIONAL(identifier, MDStringField, ); \
6085 OPTIONAL(discriminator, MDField, ); \
6086 OPTIONAL(dataLocation, MDField, ); \
6087 OPTIONAL(associated, MDField, ); \
6088 OPTIONAL(allocated, MDField, ); \
6089 OPTIONAL(rank, MDSignedOrMDField, ); \
6090 OPTIONAL(annotations, MDField, ); \
6091 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6092 OPTIONAL(specification, MDField, ); \
6093 OPTIONAL(bitStride, MDField, );
6095#undef VISIT_MD_FIELDS
6096
6097 Metadata *Rank = nullptr;
6098 if (rank.isMDSignedField())
6100 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6101 else if (rank.isMDField())
6102 Rank = rank.getMDFieldValue();
6103
6104 std::optional<unsigned> EnumKind;
6105 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6106 EnumKind = enumKind.Val;
6107
6108 // If this has an identifier try to build an ODR type.
6109 if (identifier.Val)
6110 if (auto *CT = DICompositeType::buildODRType(
6111 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6112 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6113 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6114 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6115 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6116 dataLocation.Val, associated.Val, allocated.Val, Rank,
6117 annotations.Val, bitStride.Val)) {
6118 Result = CT;
6119 return false;
6120 }
6121
6122 // Create a new node, and save it in the context if it belongs in the type
6123 // map.
6125 DICompositeType,
6126 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6127 size.getValueAsMetadata(Context), align.Val,
6128 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6129 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6130 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6131 allocated.Val, Rank, annotations.Val, specification.Val,
6132 num_extra_inhabitants.Val, bitStride.Val));
6133 return false;
6134}
6135
6136bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6138 OPTIONAL(flags, DIFlagField, ); \
6139 OPTIONAL(cc, DwarfCCField, ); \
6140 REQUIRED(types, MDField, );
6142#undef VISIT_MD_FIELDS
6143
6144 Result = GET_OR_DISTINCT(DISubroutineType,
6145 (Context, flags.Val, cc.Val, types.Val));
6146 return false;
6147}
6148
6149/// parseDIFileType:
6150/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6151/// checksumkind: CSK_MD5,
6152/// checksum: "000102030405060708090a0b0c0d0e0f",
6153/// source: "source file contents")
6154bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6155 // The default constructed value for checksumkind is required, but will never
6156 // be used, as the parser checks if the field was actually Seen before using
6157 // the Val.
6158#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6159 REQUIRED(filename, MDStringField, ); \
6160 REQUIRED(directory, MDStringField, ); \
6161 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6162 OPTIONAL(checksum, MDStringField, ); \
6163 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6165#undef VISIT_MD_FIELDS
6166
6167 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6168 if (checksumkind.Seen && checksum.Seen)
6169 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6170 else if (checksumkind.Seen || checksum.Seen)
6171 return tokError("'checksumkind' and 'checksum' must be provided together");
6172
6173 MDString *Source = nullptr;
6174 if (source.Seen)
6175 Source = source.Val;
6177 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6178 return false;
6179}
6180
6181/// parseDICompileUnit:
6182/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6183/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6184/// splitDebugFilename: "abc.debug",
6185/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6186/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6187/// sysroot: "/", sdk: "MacOSX.sdk",
6188/// dialect: DW_LLVM_LANG_DIALECT_simt)
6189bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6190 if (!IsDistinct)
6191 return tokError("missing 'distinct', required for !DICompileUnit");
6192
6193 LocTy Loc = Lex.getLoc();
6194
6195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6196 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6197 OPTIONAL(language, DwarfLangField, ); \
6198 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6199 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6200 OPTIONAL(producer, MDStringField, ); \
6201 OPTIONAL(isOptimized, MDBoolField, ); \
6202 OPTIONAL(flags, MDStringField, ); \
6203 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6204 OPTIONAL(splitDebugFilename, MDStringField, ); \
6205 OPTIONAL(emissionKind, EmissionKindField, ); \
6206 OPTIONAL(enums, MDField, ); \
6207 OPTIONAL(retainedTypes, MDField, ); \
6208 OPTIONAL(globals, MDField, ); \
6209 OPTIONAL(imports, MDField, ); \
6210 OPTIONAL(macros, MDField, ); \
6211 OPTIONAL(dwoId, MDUnsignedField, ); \
6212 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6213 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6214 OPTIONAL(nameTableKind, NameTableKindField, ); \
6215 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6216 OPTIONAL(sysroot, MDStringField, ); \
6217 OPTIONAL(sdk, MDStringField, ); \
6218 OPTIONAL(dialect, DwarfLangDialectField, );
6220#undef VISIT_MD_FIELDS
6221
6222 if (!language.Seen && !sourceLanguageName.Seen)
6223 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6224 "required for !DICompileUnit");
6225
6226 if (language.Seen && sourceLanguageName.Seen)
6227 return error(Loc, "can only specify one of 'language' and "
6228 "'sourceLanguageName' on !DICompileUnit");
6229
6230 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6231 return error(Loc, "'sourceLanguageVersion' requires an associated "
6232 "'sourceLanguageName' on !DICompileUnit");
6233
6234 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6235 DISourceLanguageName SourceLanguage =
6236 language.Seen
6237 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6238 : DISourceLanguageName(
6239 static_cast<uint16_t>(sourceLanguageName.Val),
6240 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6241
6243 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6244 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6245 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6246 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6247 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6248 return false;
6249}
6250
6251/// parseDISubprogram:
6252/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6253/// file: !1, line: 7, type: !2, isLocal: false,
6254/// isDefinition: true, scopeLine: 8, containingType: !3,
6255/// virtuality: DW_VIRTUALTIY_pure_virtual,
6256/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6257/// spFlags: 10, isOptimized: false, templateParams: !4,
6258/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6259/// annotations: !8)
6260bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6261 auto Loc = Lex.getLoc();
6262#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6263 OPTIONAL(scope, MDField, ); \
6264 OPTIONAL(name, MDStringField, ); \
6265 OPTIONAL(linkageName, MDStringField, ); \
6266 OPTIONAL(file, MDField, ); \
6267 OPTIONAL(line, LineField, ); \
6268 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6269 OPTIONAL(isLocal, MDBoolField, ); \
6270 OPTIONAL(isDefinition, MDBoolField, (true)); \
6271 OPTIONAL(scopeLine, LineField, ); \
6272 OPTIONAL(containingType, MDField, ); \
6273 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6274 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6275 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6276 OPTIONAL(flags, DIFlagField, ); \
6277 OPTIONAL(spFlags, DISPFlagField, ); \
6278 OPTIONAL(isOptimized, MDBoolField, ); \
6279 OPTIONAL(unit, MDField, ); \
6280 OPTIONAL(templateParams, MDField, ); \
6281 OPTIONAL(declaration, MDField, ); \
6282 OPTIONAL(retainedNodes, MDField, ); \
6283 OPTIONAL(thrownTypes, MDField, ); \
6284 OPTIONAL(annotations, MDField, ); \
6285 OPTIONAL(targetFuncName, MDStringField, ); \
6286 OPTIONAL(keyInstructions, MDBoolField, );
6288#undef VISIT_MD_FIELDS
6289
6290 // An explicit spFlags field takes precedence over individual fields in
6291 // older IR versions.
6292 DISubprogram::DISPFlags SPFlags =
6293 spFlags.Seen ? spFlags.Val
6294 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6295 isOptimized.Val, virtuality.Val);
6296 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6297 return error(
6298 Loc,
6299 "missing 'distinct', required for !DISubprogram that is a Definition");
6301 DISubprogram,
6302 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6303 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6304 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6305 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6306 targetFuncName.Val, keyInstructions.Val));
6307
6308 if (IsDistinct)
6309 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6310
6311 return false;
6312}
6313
6314/// parseDILexicalBlock:
6315/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6316bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6317#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6318 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6319 OPTIONAL(file, MDField, ); \
6320 OPTIONAL(line, LineField, ); \
6321 OPTIONAL(column, ColumnField, );
6323#undef VISIT_MD_FIELDS
6324
6326 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6327 return false;
6328}
6329
6330/// parseDILexicalBlockFile:
6331/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6332bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6333#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6334 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6335 OPTIONAL(file, MDField, ); \
6336 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6338#undef VISIT_MD_FIELDS
6339
6340 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6341 (Context, scope.Val, file.Val, discriminator.Val));
6342 return false;
6343}
6344
6345/// parseDICommonBlock:
6346/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6347bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6348#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6349 REQUIRED(scope, MDField, ); \
6350 OPTIONAL(declaration, MDField, ); \
6351 OPTIONAL(name, MDStringField, ); \
6352 OPTIONAL(file, MDField, ); \
6353 OPTIONAL(line, LineField, );
6355#undef VISIT_MD_FIELDS
6356
6357 Result = GET_OR_DISTINCT(DICommonBlock,
6358 (Context, scope.Val, declaration.Val, name.Val,
6359 file.Val, line.Val));
6360 return false;
6361}
6362
6363/// parseDINamespace:
6364/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6365bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6366#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6367 REQUIRED(scope, MDField, ); \
6368 OPTIONAL(name, MDStringField, ); \
6369 OPTIONAL(exportSymbols, MDBoolField, );
6371#undef VISIT_MD_FIELDS
6372
6373 Result = GET_OR_DISTINCT(DINamespace,
6374 (Context, scope.Val, name.Val, exportSymbols.Val));
6375 return false;
6376}
6377
6378/// parseDIMacro:
6379/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6380/// "SomeValue")
6381bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6382#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6383 REQUIRED(type, DwarfMacinfoTypeField, ); \
6384 OPTIONAL(line, LineField, ); \
6385 REQUIRED(name, MDStringField, ); \
6386 OPTIONAL(value, MDStringField, );
6388#undef VISIT_MD_FIELDS
6389
6390 Result = GET_OR_DISTINCT(DIMacro,
6391 (Context, type.Val, line.Val, name.Val, value.Val));
6392 return false;
6393}
6394
6395/// parseDIMacroFile:
6396/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6397bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6398#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6399 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6400 OPTIONAL(line, LineField, ); \
6401 REQUIRED(file, MDField, ); \
6402 OPTIONAL(nodes, MDField, );
6404#undef VISIT_MD_FIELDS
6405
6406 Result = GET_OR_DISTINCT(DIMacroFile,
6407 (Context, type.Val, line.Val, file.Val, nodes.Val));
6408 return false;
6409}
6410
6411/// parseDIModule:
6412/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6413/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6414/// file: !1, line: 4, isDecl: false)
6415bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6416#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6417 REQUIRED(scope, MDField, ); \
6418 REQUIRED(name, MDStringField, ); \
6419 OPTIONAL(configMacros, MDStringField, ); \
6420 OPTIONAL(includePath, MDStringField, ); \
6421 OPTIONAL(apinotes, MDStringField, ); \
6422 OPTIONAL(file, MDField, ); \
6423 OPTIONAL(line, LineField, ); \
6424 OPTIONAL(isDecl, MDBoolField, );
6426#undef VISIT_MD_FIELDS
6427
6428 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6429 configMacros.Val, includePath.Val,
6430 apinotes.Val, line.Val, isDecl.Val));
6431 return false;
6432}
6433
6434/// parseDITemplateTypeParameter:
6435/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6436bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6437#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6438 OPTIONAL(name, MDStringField, ); \
6439 REQUIRED(type, MDField, ); \
6440 OPTIONAL(defaulted, MDBoolField, );
6442#undef VISIT_MD_FIELDS
6443
6444 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6445 (Context, name.Val, type.Val, defaulted.Val));
6446 return false;
6447}
6448
6449/// parseDITemplateValueParameter:
6450/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6451/// name: "V", type: !1, defaulted: false,
6452/// value: i32 7)
6453bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6454#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6455 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6456 OPTIONAL(name, MDStringField, ); \
6457 OPTIONAL(type, MDField, ); \
6458 OPTIONAL(defaulted, MDBoolField, ); \
6459 REQUIRED(value, MDField, );
6460
6462#undef VISIT_MD_FIELDS
6463
6465 DITemplateValueParameter,
6466 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6467 return false;
6468}
6469
6470/// parseDIGlobalVariable:
6471/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6472/// file: !1, line: 7, type: !2, isLocal: false,
6473/// isDefinition: true, templateParams: !3,
6474/// declaration: !4, align: 8)
6475bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6476#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6477 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6478 OPTIONAL(scope, MDField, ); \
6479 OPTIONAL(linkageName, MDStringField, ); \
6480 OPTIONAL(file, MDField, ); \
6481 OPTIONAL(line, LineField, ); \
6482 OPTIONAL(type, MDField, ); \
6483 OPTIONAL(isLocal, MDBoolField, ); \
6484 OPTIONAL(isDefinition, MDBoolField, (true)); \
6485 OPTIONAL(templateParams, MDField, ); \
6486 OPTIONAL(declaration, MDField, ); \
6487 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6488 OPTIONAL(annotations, MDField, );
6490#undef VISIT_MD_FIELDS
6491
6492 Result =
6493 GET_OR_DISTINCT(DIGlobalVariable,
6494 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6495 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6496 declaration.Val, templateParams.Val, align.Val,
6497 annotations.Val));
6498 return false;
6499}
6500
6501/// parseDILocalVariable:
6502/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6503/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6504/// align: 8)
6505/// ::= !DILocalVariable(scope: !0, name: "foo",
6506/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6507/// align: 8)
6508bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6510 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6511 OPTIONAL(name, MDStringField, ); \
6512 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6513 OPTIONAL(file, MDField, ); \
6514 OPTIONAL(line, LineField, ); \
6515 OPTIONAL(type, MDField, ); \
6516 OPTIONAL(flags, DIFlagField, ); \
6517 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6518 OPTIONAL(annotations, MDField, );
6520#undef VISIT_MD_FIELDS
6521
6522 Result = GET_OR_DISTINCT(DILocalVariable,
6523 (Context, scope.Val, name.Val, file.Val, line.Val,
6524 type.Val, arg.Val, flags.Val, align.Val,
6525 annotations.Val));
6526 return false;
6527}
6528
6529/// parseDILabel:
6530/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6531bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6532#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6533 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6534 REQUIRED(name, MDStringField, ); \
6535 REQUIRED(file, MDField, ); \
6536 REQUIRED(line, LineField, ); \
6537 OPTIONAL(column, ColumnField, ); \
6538 OPTIONAL(isArtificial, MDBoolField, ); \
6539 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6541#undef VISIT_MD_FIELDS
6542
6543 std::optional<unsigned> CoroSuspendIdx =
6544 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6545 : std::nullopt;
6546
6547 Result = GET_OR_DISTINCT(DILabel,
6548 (Context, scope.Val, name.Val, file.Val, line.Val,
6549 column.Val, isArtificial.Val, CoroSuspendIdx));
6550 return false;
6551}
6552
6553/// parseDIExpressionBody:
6554/// ::= (0, 7, -1)
6555bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6556 if (parseToken(lltok::lparen, "expected '(' here"))
6557 return true;
6558
6559 SmallVector<uint64_t, 8> Elements;
6560 if (Lex.getKind() != lltok::rparen)
6561 do {
6562 if (Lex.getKind() == lltok::DwarfOp) {
6563 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6564 Lex.Lex();
6565 Elements.push_back(Op);
6566 continue;
6567 }
6568 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6569 }
6570
6571 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6572 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6573 Lex.Lex();
6574 Elements.push_back(Op);
6575 continue;
6576 }
6577 return tokError(Twine("invalid DWARF attribute encoding '") +
6578 Lex.getStrVal() + "'");
6579 }
6580
6581 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6582 return tokError("expected unsigned integer");
6583
6584 auto &U = Lex.getAPSIntVal();
6585 if (U.ugt(UINT64_MAX))
6586 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6587 Elements.push_back(U.getZExtValue());
6588 Lex.Lex();
6589 } while (EatIfPresent(lltok::comma));
6590
6591 if (parseToken(lltok::rparen, "expected ')' here"))
6592 return true;
6593
6594 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6595 return false;
6596}
6597
6598/// parseDIExpression:
6599/// ::= !DIExpression(0, 7, -1)
6600bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6601 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6602 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6603 Lex.Lex();
6604
6605 return parseDIExpressionBody(Result, IsDistinct);
6606}
6607
6608/// ParseDIArgList:
6609/// ::= !DIArgList(i32 7, i64 %0)
6610bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6611 assert(PFS && "Expected valid function state");
6612 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6613 Lex.Lex();
6614
6615 if (parseToken(lltok::lparen, "expected '(' here"))
6616 return true;
6617
6619 if (Lex.getKind() != lltok::rparen)
6620 do {
6621 Metadata *MD;
6622 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6623 return true;
6624 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6625 } while (EatIfPresent(lltok::comma));
6626
6627 if (parseToken(lltok::rparen, "expected ')' here"))
6628 return true;
6629
6630 MD = DIArgList::get(Context, Args);
6631 return false;
6632}
6633
6634/// parseDIGlobalVariableExpression:
6635/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6636bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6637 bool IsDistinct) {
6638#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6639 REQUIRED(var, MDField, ); \
6640 REQUIRED(expr, MDField, );
6642#undef VISIT_MD_FIELDS
6643
6644 Result =
6645 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6646 return false;
6647}
6648
6649/// parseDIObjCProperty:
6650/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6651/// getter: "getFoo", attributes: 7, type: !2)
6652bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6653#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6654 OPTIONAL(name, MDStringField, ); \
6655 OPTIONAL(file, MDField, ); \
6656 OPTIONAL(line, LineField, ); \
6657 OPTIONAL(setter, MDStringField, ); \
6658 OPTIONAL(getter, MDStringField, ); \
6659 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6660 OPTIONAL(type, MDField, );
6662#undef VISIT_MD_FIELDS
6663
6664 Result = GET_OR_DISTINCT(DIObjCProperty,
6665 (Context, name.Val, file.Val, line.Val, getter.Val,
6666 setter.Val, attributes.Val, type.Val));
6667 return false;
6668}
6669
6670/// parseDIImportedEntity:
6671/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6672/// line: 7, name: "foo", elements: !2)
6673bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6674#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6675 REQUIRED(tag, DwarfTagField, ); \
6676 REQUIRED(scope, MDField, ); \
6677 OPTIONAL(entity, MDField, ); \
6678 OPTIONAL(file, MDField, ); \
6679 OPTIONAL(line, LineField, ); \
6680 OPTIONAL(name, MDStringField, ); \
6681 OPTIONAL(elements, MDField, );
6683#undef VISIT_MD_FIELDS
6684
6685 Result = GET_OR_DISTINCT(DIImportedEntity,
6686 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6687 line.Val, name.Val, elements.Val));
6688 return false;
6689}
6690
6691#undef PARSE_MD_FIELD
6692#undef NOP_FIELD
6693#undef REQUIRE_FIELD
6694#undef DECLARE_FIELD
6695
6696/// parseMetadataAsValue
6697/// ::= metadata i32 %local
6698/// ::= metadata i32 @global
6699/// ::= metadata i32 7
6700/// ::= metadata !0
6701/// ::= metadata !{...}
6702/// ::= metadata !"string"
6703bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6704 // Note: the type 'metadata' has already been parsed.
6705 Metadata *MD;
6706 if (parseMetadata(MD, &PFS))
6707 return true;
6708
6709 V = MetadataAsValue::get(Context, MD);
6710 return false;
6711}
6712
6713/// parseValueAsMetadata
6714/// ::= i32 %local
6715/// ::= i32 @global
6716/// ::= i32 7
6717bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6718 PerFunctionState *PFS) {
6719 Type *Ty;
6720 LocTy Loc;
6721 if (parseType(Ty, TypeMsg, Loc))
6722 return true;
6723 if (Ty->isMetadataTy())
6724 return error(Loc, "invalid metadata-value-metadata roundtrip");
6725
6726 Value *V;
6727 if (parseValue(Ty, V, PFS))
6728 return true;
6729
6730 MD = ValueAsMetadata::get(V);
6731 return false;
6732}
6733
6734/// parseMetadata
6735/// ::= i32 %local
6736/// ::= i32 @global
6737/// ::= i32 7
6738/// ::= !42
6739/// ::= !{...}
6740/// ::= !"string"
6741/// ::= !DILocation(...)
6742bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6743 if (Lex.getKind() == lltok::MetadataVar) {
6744 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6745 // so parsing this requires a Function State.
6746 if (Lex.getStrVal() == "DIArgList") {
6747 Metadata *AL;
6748 if (parseDIArgList(AL, PFS))
6749 return true;
6750 MD = AL;
6751 return false;
6752 }
6753 MDNode *N;
6754 if (parseSpecializedMDNode(N)) {
6755 return true;
6756 }
6757 MD = N;
6758 return false;
6759 }
6760
6761 // ValueAsMetadata:
6762 // <type> <value>
6763 if (Lex.getKind() != lltok::exclaim)
6764 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6765
6766 // '!'.
6767 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6768 Lex.Lex();
6769
6770 // MDString:
6771 // ::= '!' STRINGCONSTANT
6772 if (Lex.getKind() == lltok::StringConstant) {
6773 MDString *S;
6774 if (parseMDString(S))
6775 return true;
6776 MD = S;
6777 return false;
6778 }
6779
6780 // MDNode:
6781 // !{ ... }
6782 // !7
6783 MDNode *N;
6784 if (parseMDNodeTail(N))
6785 return true;
6786 MD = N;
6787 return false;
6788}
6789
6790//===----------------------------------------------------------------------===//
6791// Function Parsing.
6792//===----------------------------------------------------------------------===//
6793
6794bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6795 PerFunctionState *PFS) {
6796 if (Ty->isFunctionTy())
6797 return error(ID.Loc, "functions are not values, refer to them as pointers");
6798
6799 switch (ID.Kind) {
6800 case ValID::t_LocalID:
6801 if (!PFS)
6802 return error(ID.Loc, "invalid use of function-local name");
6803 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6804 return V == nullptr;
6805 case ValID::t_LocalName:
6806 if (!PFS)
6807 return error(ID.Loc, "invalid use of function-local name");
6808 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6809 return V == nullptr;
6810 case ValID::t_InlineAsm: {
6811 if (!ID.FTy)
6812 return error(ID.Loc, "invalid type for inline asm constraint string");
6813 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6814 return error(ID.Loc, toString(std::move(Err)));
6815 V = InlineAsm::get(
6816 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6817 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6818 return false;
6819 }
6821 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6822 if (V && ID.NoCFI)
6824 return V == nullptr;
6825 case ValID::t_GlobalID:
6826 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6827 if (V && ID.NoCFI)
6829 return V == nullptr;
6830 case ValID::t_APSInt:
6831 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6832 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6833 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6834 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6835 : V = ConstantByte::get(Context, ID.APSIntVal);
6836 return false;
6837 case ValID::t_APFloat:
6838 if (!Ty->isFloatingPointTy() ||
6839 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6840 return error(ID.Loc, "floating point constant invalid for type");
6841
6842 // The lexer has no type info, so builds all half, bfloat, float, and double
6843 // FP constants as double. Fix this here. Long double does not need this.
6844 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6845 // Check for signaling before potentially converting and losing that info.
6846 bool IsSNAN = ID.APFloatVal.isSignaling();
6847 bool Ignored;
6848 if (Ty->isHalfTy())
6849 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6850 &Ignored);
6851 else if (Ty->isBFloatTy())
6852 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6853 &Ignored);
6854 else if (Ty->isFloatTy())
6855 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6856 &Ignored);
6857 if (IsSNAN) {
6858 // The convert call above may quiet an SNaN, so manufacture another
6859 // SNaN. The bitcast works because the payload (significand) parameter
6860 // is truncated to fit.
6861 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6862 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6863 ID.APFloatVal.isNegative(), &Payload);
6864 }
6865 }
6866 V = ConstantFP::get(Context, ID.APFloatVal);
6867
6868 if (V->getType() != Ty)
6869 return error(ID.Loc, "floating point constant does not have type '" +
6870 getTypeString(Ty) + "'");
6871
6872 return false;
6873 case ValID::t_Null:
6874 if (!Ty->isPointerTy())
6875 return error(ID.Loc, "null must be a pointer type");
6877 return false;
6878 case ValID::t_Undef:
6879 // FIXME: LabelTy should not be a first-class type.
6880 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6881 return error(ID.Loc, "invalid type for undef constant");
6882 V = UndefValue::get(Ty);
6883 return false;
6885 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6886 return error(ID.Loc, "invalid empty array initializer");
6887 V = PoisonValue::get(Ty);
6888 return false;
6889 case ValID::t_Zero:
6890 // FIXME: LabelTy should not be a first-class type.
6891 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6892 return error(ID.Loc, "invalid type for null constant");
6893 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6894 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6895 return error(ID.Loc, "invalid type for null constant");
6897 return false;
6898 case ValID::t_None:
6899 if (!Ty->isTokenTy())
6900 return error(ID.Loc, "invalid type for none constant");
6902 return false;
6903 case ValID::t_Poison:
6904 // FIXME: LabelTy should not be a first-class type.
6905 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6906 return error(ID.Loc, "invalid type for poison constant");
6907 V = PoisonValue::get(Ty);
6908 return false;
6909 case ValID::t_Constant:
6910 if (ID.ConstantVal->getType() != Ty)
6911 return error(ID.Loc, "constant expression type mismatch: got type '" +
6912 getTypeString(ID.ConstantVal->getType()) +
6913 "' but expected '" + getTypeString(Ty) + "'");
6914 V = ID.ConstantVal;
6915 return false;
6917 if (!Ty->isVectorTy())
6918 return error(ID.Loc, "vector constant must have vector type");
6919 if (ID.ConstantVal->getType() != Ty->getScalarType())
6920 return error(ID.Loc, "constant expression type mismatch: got type '" +
6921 getTypeString(ID.ConstantVal->getType()) +
6922 "' but expected '" +
6923 getTypeString(Ty->getScalarType()) + "'");
6924 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6925 ID.ConstantVal);
6926 return false;
6929 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6930 if (ST->getNumElements() != ID.UIntVal)
6931 return error(ID.Loc,
6932 "initializer with struct type has wrong # elements");
6933 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6934 return error(ID.Loc, "packed'ness of initializer and type don't match");
6935
6936 // Verify that the elements are compatible with the structtype.
6937 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6938 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6939 return error(
6940 ID.Loc,
6941 "element " + Twine(i) +
6942 " of struct initializer doesn't match struct element type");
6943
6945 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6946 } else
6947 return error(ID.Loc, "constant expression type mismatch");
6948 return false;
6949 }
6950 llvm_unreachable("Invalid ValID");
6951}
6952
6953bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6954 C = nullptr;
6955 ValID ID;
6956 auto Loc = Lex.getLoc();
6957 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
6958 return true;
6959 switch (ID.Kind) {
6960 case ValID::t_APSInt:
6961 case ValID::t_APFloat:
6962 case ValID::t_Undef:
6963 case ValID::t_Poison:
6964 case ValID::t_Zero:
6965 case ValID::t_Constant:
6969 Value *V;
6970 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6971 return true;
6972 assert(isa<Constant>(V) && "Expected a constant value");
6973 C = cast<Constant>(V);
6974 return false;
6975 }
6976 case ValID::t_Null:
6978 return false;
6979 default:
6980 return error(Loc, "expected a constant value");
6981 }
6982}
6983
6984bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6985 V = nullptr;
6986 ValID ID;
6987
6988 FileLoc Start = getTokLineColumnPos();
6989 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
6990 if (!Ret && ParserContext) {
6991 FileLoc End = getPrevTokEndLineColumnPos();
6992 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6993 }
6994 return Ret;
6995}
6996
6997bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6998 Type *Ty = nullptr;
6999 return parseType(Ty) || parseValue(Ty, V, PFS);
7000}
7001
7002bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7003 PerFunctionState &PFS) {
7004 Value *V;
7005 Loc = Lex.getLoc();
7006 if (parseTypeAndValue(V, PFS))
7007 return true;
7008 if (!isa<BasicBlock>(V))
7009 return error(Loc, "expected a basic block");
7010 BB = cast<BasicBlock>(V);
7011 return false;
7012}
7013
7015 // Exit early for the common (non-debug-intrinsic) case.
7016 // We can make this the only check when we begin supporting all "llvm.dbg"
7017 // intrinsics in the new debug info format.
7018 if (!Name.starts_with("llvm.dbg."))
7019 return false;
7021 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7022 FnID == Intrinsic::dbg_assign;
7023}
7024
7025/// FunctionHeader
7026/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7027/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7028/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7029/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7030bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7031 unsigned &FunctionNumber,
7032 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7033 // parse the linkage.
7034 LocTy LinkageLoc = Lex.getLoc();
7035 unsigned Linkage;
7036 unsigned Visibility;
7037 unsigned DLLStorageClass;
7038 bool DSOLocal;
7039 AttrBuilder RetAttrs(M->getContext());
7040 unsigned CC;
7041 bool HasLinkage;
7042 Type *RetType = nullptr;
7043 LocTy RetTypeLoc = Lex.getLoc();
7044 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7045 DSOLocal) ||
7046 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7047 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7048 return true;
7049
7050 // Verify that the linkage is ok.
7053 break; // always ok.
7055 if (IsDefine)
7056 return error(LinkageLoc, "invalid linkage for function definition");
7057 break;
7065 if (!IsDefine)
7066 return error(LinkageLoc, "invalid linkage for function declaration");
7067 break;
7070 return error(LinkageLoc, "invalid function linkage type");
7071 }
7072
7073 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7074 return error(LinkageLoc,
7075 "symbol with local linkage must have default visibility");
7076
7077 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7078 return error(LinkageLoc,
7079 "symbol with local linkage cannot have a DLL storage class");
7080
7081 if (!FunctionType::isValidReturnType(RetType))
7082 return error(RetTypeLoc, "invalid function return type");
7083
7084 LocTy NameLoc = Lex.getLoc();
7085
7086 std::string FunctionName;
7087 if (Lex.getKind() == lltok::GlobalVar) {
7088 FunctionName = Lex.getStrVal();
7089 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7090 FunctionNumber = Lex.getUIntVal();
7091 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7092 FunctionNumber))
7093 return true;
7094 } else {
7095 return tokError("expected function name");
7096 }
7097
7098 Lex.Lex();
7099
7100 if (Lex.getKind() != lltok::lparen)
7101 return tokError("expected '(' in function argument list");
7102
7104 bool IsVarArg;
7105 AttrBuilder FuncAttrs(M->getContext());
7106 std::vector<unsigned> FwdRefAttrGrps;
7107 LocTy BuiltinLoc;
7108 std::string Section;
7109 std::string Partition;
7110 MaybeAlign Alignment, PrefAlignment;
7111 std::string GC;
7113 unsigned AddrSpace = 0;
7114 Constant *Prefix = nullptr;
7115 Constant *Prologue = nullptr;
7116 Constant *PersonalityFn = nullptr;
7117 Comdat *C;
7118
7119 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7120 parseOptionalUnnamedAddr(UnnamedAddr) ||
7121 parseOptionalProgramAddrSpace(AddrSpace) ||
7122 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7123 BuiltinLoc) ||
7124 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7125 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7126 parseOptionalComdat(FunctionName, C) ||
7127 parseOptionalAlignment(Alignment) ||
7128 parseOptionalPrefAlignment(PrefAlignment) ||
7129 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7130 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7131 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7132 (EatIfPresent(lltok::kw_personality) &&
7133 parseGlobalTypeAndValue(PersonalityFn)))
7134 return true;
7135
7136 if (FuncAttrs.contains(Attribute::Builtin))
7137 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7138
7139 // If the alignment was parsed as an attribute, move to the alignment field.
7140 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7141 Alignment = A;
7142 FuncAttrs.removeAttribute(Attribute::Alignment);
7143 }
7144
7145 // Okay, if we got here, the function is syntactically valid. Convert types
7146 // and do semantic checks.
7147 std::vector<Type*> ParamTypeList;
7149
7150 for (const ArgInfo &Arg : ArgList) {
7151 ParamTypeList.push_back(Arg.Ty);
7152 Attrs.push_back(Arg.Attrs);
7153 }
7154
7155 AttributeList PAL =
7156 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7157 AttributeSet::get(Context, RetAttrs), Attrs);
7158
7159 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7160 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7161
7162 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7163 PointerType *PFT = PointerType::get(Context, AddrSpace);
7164
7165 Fn = nullptr;
7166 GlobalValue *FwdFn = nullptr;
7167 if (!FunctionName.empty()) {
7168 // If this was a definition of a forward reference, remove the definition
7169 // from the forward reference table and fill in the forward ref.
7170 auto FRVI = ForwardRefVals.find(FunctionName);
7171 if (FRVI != ForwardRefVals.end()) {
7172 FwdFn = FRVI->second.first;
7173 if (FwdFn->getType() != PFT)
7174 return error(FRVI->second.second,
7175 "invalid forward reference to "
7176 "function '" +
7177 FunctionName +
7178 "' with wrong type: "
7179 "expected '" +
7180 getTypeString(PFT) + "' but was '" +
7181 getTypeString(FwdFn->getType()) + "'");
7182 ForwardRefVals.erase(FRVI);
7183 } else if ((Fn = M->getFunction(FunctionName))) {
7184 // Reject redefinitions.
7185 return error(NameLoc,
7186 "invalid redefinition of function '" + FunctionName + "'");
7187 } else if (M->getNamedValue(FunctionName)) {
7188 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7189 }
7190
7191 } else {
7192 // Handle @"", where a name is syntactically specified, but semantically
7193 // missing.
7194 if (FunctionNumber == (unsigned)-1)
7195 FunctionNumber = NumberedVals.getNext();
7196
7197 // If this is a definition of a forward referenced function, make sure the
7198 // types agree.
7199 auto I = ForwardRefValIDs.find(FunctionNumber);
7200 if (I != ForwardRefValIDs.end()) {
7201 FwdFn = I->second.first;
7202 if (FwdFn->getType() != PFT)
7203 return error(NameLoc, "type of definition and forward reference of '@" +
7204 Twine(FunctionNumber) +
7205 "' disagree: "
7206 "expected '" +
7207 getTypeString(PFT) + "' but was '" +
7208 getTypeString(FwdFn->getType()) + "'");
7209 ForwardRefValIDs.erase(I);
7210 }
7211 }
7212
7214 FunctionName, M);
7215
7216 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7217
7218 if (FunctionName.empty())
7219 NumberedVals.add(FunctionNumber, Fn);
7220
7222 maybeSetDSOLocal(DSOLocal, *Fn);
7225 Fn->setCallingConv(CC);
7226 Fn->setAttributes(PAL);
7227 Fn->setUnnamedAddr(UnnamedAddr);
7228 if (Alignment)
7229 Fn->setAlignment(*Alignment);
7230 Fn->setPreferredAlignment(PrefAlignment);
7231 Fn->setSection(Section);
7232 Fn->setPartition(Partition);
7233 Fn->setComdat(C);
7234 Fn->setPersonalityFn(PersonalityFn);
7235 if (!GC.empty()) Fn->setGC(GC);
7236 Fn->setPrefixData(Prefix);
7237 Fn->setPrologueData(Prologue);
7238 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7239
7240 // Add all of the arguments we parsed to the function.
7241 Function::arg_iterator ArgIt = Fn->arg_begin();
7242 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7243 if (ParserContext && ArgList[i].IdentLoc)
7244 ParserContext->addInstructionOrArgumentLocation(
7245 &*ArgIt, ArgList[i].IdentLoc.value());
7246 // If the argument has a name, insert it into the argument symbol table.
7247 if (ArgList[i].Name.empty()) continue;
7248
7249 // Set the name, if it conflicted, it will be auto-renamed.
7250 ArgIt->setName(ArgList[i].Name);
7251
7252 if (ArgIt->getName() != ArgList[i].Name)
7253 return error(ArgList[i].Loc,
7254 "redefinition of argument '%" + ArgList[i].Name + "'");
7255 }
7256
7257 if (FwdFn) {
7258 FwdFn->replaceAllUsesWith(Fn);
7259 FwdFn->eraseFromParent();
7260 }
7261
7262 if (IsDefine)
7263 return false;
7264
7265 // Check the declaration has no block address forward references.
7266 ValID ID;
7267 if (FunctionName.empty()) {
7268 ID.Kind = ValID::t_GlobalID;
7269 ID.UIntVal = FunctionNumber;
7270 } else {
7271 ID.Kind = ValID::t_GlobalName;
7272 ID.StrVal = FunctionName;
7273 }
7274 auto Blocks = ForwardRefBlockAddresses.find(ID);
7275 if (Blocks != ForwardRefBlockAddresses.end())
7276 return error(Blocks->first.Loc,
7277 "cannot take blockaddress inside a declaration");
7278 return false;
7279}
7280
7281bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7282 ValID ID;
7283 if (FunctionNumber == -1) {
7284 ID.Kind = ValID::t_GlobalName;
7285 ID.StrVal = std::string(F.getName());
7286 } else {
7287 ID.Kind = ValID::t_GlobalID;
7288 ID.UIntVal = FunctionNumber;
7289 }
7290
7291 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7292 if (Blocks == P.ForwardRefBlockAddresses.end())
7293 return false;
7294
7295 for (const auto &I : Blocks->second) {
7296 const ValID &BBID = I.first;
7297 GlobalValue *GV = I.second;
7298
7299 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7300 "Expected local id or name");
7301 BasicBlock *BB;
7302 if (BBID.Kind == ValID::t_LocalName)
7303 BB = getBB(BBID.StrVal, BBID.Loc);
7304 else
7305 BB = getBB(BBID.UIntVal, BBID.Loc);
7306 if (!BB)
7307 return P.error(BBID.Loc, "referenced value is not a basic block");
7308
7309 Value *ResolvedVal = BlockAddress::get(&F, BB);
7310 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7311 ResolvedVal);
7312 if (!ResolvedVal)
7313 return true;
7314 GV->replaceAllUsesWith(ResolvedVal);
7315 GV->eraseFromParent();
7316 }
7317
7318 P.ForwardRefBlockAddresses.erase(Blocks);
7319 return false;
7320}
7321
7322/// parseFunctionBody
7323/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7324bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7325 ArrayRef<unsigned> UnnamedArgNums) {
7326 if (Lex.getKind() != lltok::lbrace)
7327 return tokError("expected '{' in function body");
7328 Lex.Lex(); // eat the {.
7329
7330 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7331
7332 // Resolve block addresses and allow basic blocks to be forward-declared
7333 // within this function.
7334 if (PFS.resolveForwardRefBlockAddresses())
7335 return true;
7336 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7337
7338 // We need at least one basic block.
7339 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7340 return tokError("function body requires at least one basic block");
7341
7342 while (Lex.getKind() != lltok::rbrace &&
7343 Lex.getKind() != lltok::kw_uselistorder)
7344 if (parseBasicBlock(PFS))
7345 return true;
7346
7347 while (Lex.getKind() != lltok::rbrace)
7348 if (parseUseListOrder(&PFS))
7349 return true;
7350
7351 // Eat the }.
7352 Lex.Lex();
7353
7354 // Verify function is ok.
7355 return PFS.finishFunction();
7356}
7357
7358/// parseBasicBlock
7359/// ::= (LabelStr|LabelID)? Instruction*
7360bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7361 FileLoc BBStart = getTokLineColumnPos();
7362
7363 // If this basic block starts out with a name, remember it.
7364 std::string Name;
7365 int NameID = -1;
7366 LocTy NameLoc = Lex.getLoc();
7367 if (Lex.getKind() == lltok::LabelStr) {
7368 Name = Lex.getStrVal();
7369 Lex.Lex();
7370 } else if (Lex.getKind() == lltok::LabelID) {
7371 NameID = Lex.getUIntVal();
7372 Lex.Lex();
7373 }
7374
7375 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7376 if (!BB)
7377 return true;
7378
7379 std::string NameStr;
7380
7381 // Parse the instructions and debug values in this block until we get a
7382 // terminator.
7383 Instruction *Inst;
7384 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7385 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7386 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7387 do {
7388 // Handle debug records first - there should always be an instruction
7389 // following the debug records, i.e. they cannot appear after the block
7390 // terminator.
7391 while (Lex.getKind() == lltok::hash) {
7392 if (SeenOldDbgInfoFormat)
7393 return error(Lex.getLoc(), "debug record should not appear in a module "
7394 "containing debug info intrinsics");
7395 SeenNewDbgInfoFormat = true;
7396 Lex.Lex();
7397
7398 DbgRecord *DR;
7399 if (parseDebugRecord(DR, PFS))
7400 return true;
7401 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7402 }
7403
7404 FileLoc InstStart = getTokLineColumnPos();
7405 // This instruction may have three possibilities for a name: a) none
7406 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7407 LocTy NameLoc = Lex.getLoc();
7408 int NameID = -1;
7409 NameStr = "";
7410
7411 if (Lex.getKind() == lltok::LocalVarID) {
7412 NameID = Lex.getUIntVal();
7413 Lex.Lex();
7414 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7415 return true;
7416 } else if (Lex.getKind() == lltok::LocalVar) {
7417 NameStr = Lex.getStrVal();
7418 Lex.Lex();
7419 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7420 return true;
7421 }
7422
7423 switch (parseInstruction(Inst, BB, PFS)) {
7424 default:
7425 llvm_unreachable("Unknown parseInstruction result!");
7426 case InstError: return true;
7427 case InstNormal:
7428 Inst->insertInto(BB, BB->end());
7429
7430 // With a normal result, we check to see if the instruction is followed by
7431 // a comma and metadata.
7432 if (EatIfPresent(lltok::comma))
7433 if (parseInstructionMetadata(*Inst))
7434 return true;
7435 break;
7436 case InstExtraComma:
7437 Inst->insertInto(BB, BB->end());
7438
7439 // If the instruction parser ate an extra comma at the end of it, it
7440 // *must* be followed by metadata.
7441 if (parseInstructionMetadata(*Inst))
7442 return true;
7443 break;
7444 }
7445
7446 // Set the name on the instruction.
7447 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7448 return true;
7449
7450 // Attach any preceding debug values to this instruction.
7451 for (DbgRecordPtr &DR : TrailingDbgRecord)
7452 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7453 TrailingDbgRecord.clear();
7454 if (ParserContext) {
7455 ParserContext->addInstructionOrArgumentLocation(
7456 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7457 }
7458 } while (!Inst->isTerminator());
7459
7460 if (ParserContext)
7461 ParserContext->addBlockLocation(
7462 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7463
7464 assert(TrailingDbgRecord.empty() &&
7465 "All debug values should have been attached to an instruction.");
7466
7467 return false;
7468}
7469
7470/// parseDebugRecord
7471/// ::= #dbg_label '(' MDNode ')'
7472/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7473/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7474bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7475 using RecordKind = DbgRecord::Kind;
7476 using LocType = DbgVariableRecord::LocationType;
7477 LocTy DVRLoc = Lex.getLoc();
7478 if (Lex.getKind() != lltok::DbgRecordType)
7479 return error(DVRLoc, "expected debug record type here");
7480 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7481 .Case("declare", RecordKind::ValueKind)
7482 .Case("value", RecordKind::ValueKind)
7483 .Case("assign", RecordKind::ValueKind)
7484 .Case("label", RecordKind::LabelKind)
7485 .Case("declare_value", RecordKind::ValueKind);
7486
7487 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7488 // full DbgVariableRecord processing stage.
7489 if (RecordType == RecordKind::LabelKind) {
7490 Lex.Lex();
7491 if (parseToken(lltok::lparen, "Expected '(' here"))
7492 return true;
7493 MDNode *Label;
7494 if (parseMDNode(Label))
7495 return true;
7496 if (parseToken(lltok::comma, "Expected ',' here"))
7497 return true;
7498 MDNode *DbgLoc;
7499 if (parseMDNode(DbgLoc))
7500 return true;
7501 if (parseToken(lltok::rparen, "Expected ')' here"))
7502 return true;
7504 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7505 return false;
7506 }
7507
7508 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7509 .Case("declare", LocType::Declare)
7510 .Case("value", LocType::Value)
7511 .Case("assign", LocType::Assign)
7512 .Case("declare_value", LocType::DeclareValue);
7513
7514 Lex.Lex();
7515 if (parseToken(lltok::lparen, "Expected '(' here"))
7516 return true;
7517
7518 // Parse Value field.
7519 Metadata *ValLocMD;
7520 if (parseMetadata(ValLocMD, &PFS))
7521 return true;
7522 if (parseToken(lltok::comma, "Expected ',' here"))
7523 return true;
7524
7525 // Parse Variable field.
7526 MDNode *Variable;
7527 if (parseMDNode(Variable))
7528 return true;
7529 if (parseToken(lltok::comma, "Expected ',' here"))
7530 return true;
7531
7532 // Parse Expression field.
7533 MDNode *Expression;
7534 if (parseMDNode(Expression))
7535 return true;
7536 if (parseToken(lltok::comma, "Expected ',' here"))
7537 return true;
7538
7539 // Parse additional fields for #dbg_assign.
7540 MDNode *AssignID = nullptr;
7541 Metadata *AddressLocation = nullptr;
7542 MDNode *AddressExpression = nullptr;
7543 if (ValueType == LocType::Assign) {
7544 // Parse DIAssignID.
7545 if (parseMDNode(AssignID))
7546 return true;
7547 if (parseToken(lltok::comma, "Expected ',' here"))
7548 return true;
7549
7550 // Parse address ValueAsMetadata.
7551 if (parseMetadata(AddressLocation, &PFS))
7552 return true;
7553 if (parseToken(lltok::comma, "Expected ',' here"))
7554 return true;
7555
7556 // Parse address DIExpression.
7557 if (parseMDNode(AddressExpression))
7558 return true;
7559 if (parseToken(lltok::comma, "Expected ',' here"))
7560 return true;
7561 }
7562
7563 /// Parse DILocation.
7564 MDNode *DebugLoc;
7565 if (parseMDNode(DebugLoc))
7566 return true;
7567
7568 if (parseToken(lltok::rparen, "Expected ')' here"))
7569 return true;
7571 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7572 AddressExpression);
7573 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7574 return false;
7575}
7576//===----------------------------------------------------------------------===//
7577// Instruction Parsing.
7578//===----------------------------------------------------------------------===//
7579
7580/// parseInstruction - parse one of the many different instructions.
7581///
7582int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7583 PerFunctionState &PFS) {
7584 lltok::Kind Token = Lex.getKind();
7585 if (Token == lltok::Eof)
7586 return tokError("found end of file when expecting more instructions");
7587 LocTy Loc = Lex.getLoc();
7588 unsigned KeywordVal = Lex.getUIntVal();
7589 Lex.Lex(); // Eat the keyword.
7590
7591 switch (Token) {
7592 default:
7593 return error(Loc, "expected instruction opcode");
7594 // Terminator Instructions.
7595 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7596 case lltok::kw_ret:
7597 return parseRet(Inst, BB, PFS);
7598 case lltok::kw_br:
7599 return parseBr(Inst, PFS);
7600 case lltok::kw_switch:
7601 return parseSwitch(Inst, PFS);
7603 return parseIndirectBr(Inst, PFS);
7604 case lltok::kw_invoke:
7605 return parseInvoke(Inst, PFS);
7606 case lltok::kw_resume:
7607 return parseResume(Inst, PFS);
7609 return parseCleanupRet(Inst, PFS);
7610 case lltok::kw_catchret:
7611 return parseCatchRet(Inst, PFS);
7613 return parseCatchSwitch(Inst, PFS);
7614 case lltok::kw_catchpad:
7615 return parseCatchPad(Inst, PFS);
7617 return parseCleanupPad(Inst, PFS);
7618 case lltok::kw_callbr:
7619 return parseCallBr(Inst, PFS);
7620 // Unary Operators.
7621 case lltok::kw_fneg: {
7622 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7623 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7624 if (Res != 0)
7625 return Res;
7626 if (FMF.any())
7627 Inst->setFastMathFlags(FMF);
7628 return false;
7629 }
7630 // Binary Operators.
7631 case lltok::kw_add:
7632 case lltok::kw_sub:
7633 case lltok::kw_mul:
7634 case lltok::kw_shl: {
7635 bool NUW = EatIfPresent(lltok::kw_nuw);
7636 bool NSW = EatIfPresent(lltok::kw_nsw);
7637 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7638
7639 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7640 return true;
7641
7642 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7643 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7644 return false;
7645 }
7646 case lltok::kw_fadd:
7647 case lltok::kw_fsub:
7648 case lltok::kw_fmul:
7649 case lltok::kw_fdiv:
7650 case lltok::kw_frem: {
7651 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7652 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7653 if (Res != 0)
7654 return Res;
7655 if (FMF.any())
7656 Inst->setFastMathFlags(FMF);
7657 return 0;
7658 }
7659
7660 case lltok::kw_sdiv:
7661 case lltok::kw_udiv:
7662 case lltok::kw_lshr:
7663 case lltok::kw_ashr: {
7664 bool Exact = EatIfPresent(lltok::kw_exact);
7665
7666 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7667 return true;
7668 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7669 return false;
7670 }
7671
7672 case lltok::kw_urem:
7673 case lltok::kw_srem:
7674 return parseArithmetic(Inst, PFS, KeywordVal,
7675 /*IsFP*/ false);
7676 case lltok::kw_or: {
7677 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7678 if (parseLogical(Inst, PFS, KeywordVal))
7679 return true;
7680 if (Disjoint)
7681 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7682 return false;
7683 }
7684 case lltok::kw_and:
7685 case lltok::kw_xor:
7686 return parseLogical(Inst, PFS, KeywordVal);
7687 case lltok::kw_icmp: {
7688 bool SameSign = EatIfPresent(lltok::kw_samesign);
7689 if (parseCompare(Inst, PFS, KeywordVal))
7690 return true;
7691 if (SameSign)
7692 cast<ICmpInst>(Inst)->setSameSign();
7693 return false;
7694 }
7695 case lltok::kw_fcmp: {
7696 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7697 int Res = parseCompare(Inst, PFS, KeywordVal);
7698 if (Res != 0)
7699 return Res;
7700 if (FMF.any())
7701 Inst->setFastMathFlags(FMF);
7702 return 0;
7703 }
7704
7705 // Casts.
7706 case lltok::kw_uitofp: {
7707 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7708 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7709 bool Res = parseCast(Inst, PFS, KeywordVal);
7710 if (Res != 0)
7711 return Res;
7712 if (NonNeg)
7713 Inst->setNonNeg();
7714 Inst->setFastMathFlags(FMF);
7715 return 0;
7716 }
7717 case lltok::kw_zext: {
7718 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7719 bool Res = parseCast(Inst, PFS, KeywordVal);
7720 if (Res != 0)
7721 return Res;
7722 if (NonNeg)
7723 Inst->setNonNeg();
7724 return 0;
7725 }
7726 case lltok::kw_trunc: {
7727 bool NUW = EatIfPresent(lltok::kw_nuw);
7728 bool NSW = EatIfPresent(lltok::kw_nsw);
7729 if (!NUW)
7730 NUW = EatIfPresent(lltok::kw_nuw);
7731 if (parseCast(Inst, PFS, KeywordVal))
7732 return true;
7733 if (NUW)
7734 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7735 if (NSW)
7736 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7737 return false;
7738 }
7739 case lltok::kw_sext:
7740 case lltok::kw_bitcast:
7742 case lltok::kw_fptoui:
7743 case lltok::kw_fptosi:
7744 case lltok::kw_inttoptr:
7746 case lltok::kw_ptrtoint:
7747 return parseCast(Inst, PFS, KeywordVal);
7748 case lltok::kw_fptrunc:
7749 case lltok::kw_fpext:
7750 case lltok::kw_sitofp: {
7751 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7752 if (parseCast(Inst, PFS, KeywordVal))
7753 return true;
7754 if (FMF.any())
7755 Inst->setFastMathFlags(FMF);
7756 return false;
7757 }
7758
7759 // Other.
7760 case lltok::kw_select: {
7761 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7762 int Res = parseSelect(Inst, PFS);
7763 if (Res != 0)
7764 return Res;
7765 if (FMF.any()) {
7766 if (!isa<FPMathOperator>(Inst)) {
7767 Inst->deleteValue();
7768 return error(Loc, "fast-math-flags specified for select without "
7769 "floating-point scalar or vector return type");
7770 }
7771 Inst->setFastMathFlags(FMF);
7772 }
7773 return 0;
7774 }
7775 case lltok::kw_va_arg:
7776 return parseVAArg(Inst, PFS);
7778 return parseExtractElement(Inst, PFS);
7780 return parseInsertElement(Inst, PFS);
7782 return parseShuffleVector(Inst, PFS);
7783 case lltok::kw_phi: {
7784 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7785 int Res = parsePHI(Inst, PFS);
7786 if (Res != 0)
7787 return Res;
7788 if (FMF.any()) {
7789 if (!isa<FPMathOperator>(Inst)) {
7790 Inst->deleteValue();
7791 return error(Loc, "fast-math-flags specified for phi without "
7792 "floating-point scalar or vector return type");
7793 }
7794 Inst->setFastMathFlags(FMF);
7795 }
7796 return 0;
7797 }
7799 return parseLandingPad(Inst, PFS);
7800 case lltok::kw_freeze:
7801 return parseFreeze(Inst, PFS);
7802 // Call.
7803 case lltok::kw_call:
7804 return parseCall(Inst, PFS, CallInst::TCK_None);
7805 case lltok::kw_tail:
7806 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7807 case lltok::kw_musttail:
7808 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7809 case lltok::kw_notail:
7810 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7811 // Memory.
7812 case lltok::kw_alloca:
7813 return parseAlloc(Inst, PFS);
7814 case lltok::kw_load:
7815 return parseLoad(Inst, PFS);
7816 case lltok::kw_store:
7817 return parseStore(Inst, PFS);
7818 case lltok::kw_cmpxchg:
7819 return parseCmpXchg(Inst, PFS);
7821 return parseAtomicRMW(Inst, PFS);
7822 case lltok::kw_fence:
7823 return parseFence(Inst, PFS);
7825 return parseGetElementPtr(Inst, PFS);
7827 return parseExtractValue(Inst, PFS);
7829 return parseInsertValue(Inst, PFS);
7830 }
7831}
7832
7833/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7834bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7835 if (Opc == Instruction::FCmp) {
7836 switch (Lex.getKind()) {
7837 default:
7838 return tokError("expected fcmp predicate (e.g. 'oeq')");
7839 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7840 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7841 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7842 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7843 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7844 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7845 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7846 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7847 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7848 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7849 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7850 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7851 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7852 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7853 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7854 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7855 }
7856 } else {
7857 switch (Lex.getKind()) {
7858 default:
7859 return tokError("expected icmp predicate (e.g. 'eq')");
7860 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7861 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7862 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7863 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7864 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7865 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7866 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7867 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7868 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7869 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7870 }
7871 }
7872 Lex.Lex();
7873 return false;
7874}
7875
7876//===----------------------------------------------------------------------===//
7877// Terminator Instructions.
7878//===----------------------------------------------------------------------===//
7879
7880/// parseRet - parse a return instruction.
7881/// ::= 'ret' void (',' !dbg, !1)*
7882/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7883bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7884 PerFunctionState &PFS) {
7885 SMLoc TypeLoc = Lex.getLoc();
7886 Type *Ty = nullptr;
7887 if (parseType(Ty, true /*void allowed*/))
7888 return true;
7889
7890 Type *ResType = PFS.getFunction().getReturnType();
7891
7892 if (Ty->isVoidTy()) {
7893 if (!ResType->isVoidTy())
7894 return error(TypeLoc, "value doesn't match function result type '" +
7895 getTypeString(ResType) + "'");
7896
7897 Inst = ReturnInst::Create(Context);
7898 return false;
7899 }
7900
7901 Value *RV;
7902 if (parseValue(Ty, RV, PFS))
7903 return true;
7904
7905 if (ResType != RV->getType())
7906 return error(TypeLoc, "value doesn't match function result type '" +
7907 getTypeString(ResType) + "'");
7908
7909 Inst = ReturnInst::Create(Context, RV);
7910 return false;
7911}
7912
7913/// parseBr
7914/// ::= 'br' TypeAndValue
7915/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7916bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7917 LocTy Loc, Loc2;
7918 Value *Op0;
7919 BasicBlock *Op1, *Op2;
7920 if (parseTypeAndValue(Op0, Loc, PFS))
7921 return true;
7922
7923 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7924 Inst = UncondBrInst::Create(BB);
7925 return false;
7926 }
7927
7928 if (Op0->getType() != Type::getInt1Ty(Context))
7929 return error(Loc, "branch condition must have 'i1' type");
7930
7931 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7932 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7933 parseToken(lltok::comma, "expected ',' after true destination") ||
7934 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7935 return true;
7936
7937 Inst = CondBrInst::Create(Op0, Op1, Op2);
7938 return false;
7939}
7940
7941/// parseSwitch
7942/// Instruction
7943/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7944/// JumpTable
7945/// ::= (TypeAndValue ',' TypeAndValue)*
7946bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7947 LocTy CondLoc, BBLoc;
7948 Value *Cond;
7949 BasicBlock *DefaultBB;
7950 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7951 parseToken(lltok::comma, "expected ',' after switch condition") ||
7952 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7953 parseToken(lltok::lsquare, "expected '[' with switch table"))
7954 return true;
7955
7956 if (!Cond->getType()->isIntegerTy())
7957 return error(CondLoc, "switch condition must have integer type");
7958
7959 // parse the jump table pairs.
7960 SmallPtrSet<Value*, 32> SeenCases;
7962 while (Lex.getKind() != lltok::rsquare) {
7963 Value *Constant;
7964 BasicBlock *DestBB;
7965
7966 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7967 parseToken(lltok::comma, "expected ',' after case value") ||
7968 parseTypeAndBasicBlock(DestBB, PFS))
7969 return true;
7970
7971 if (!SeenCases.insert(Constant).second)
7972 return error(CondLoc, "duplicate case value in switch");
7973 if (!isa<ConstantInt>(Constant))
7974 return error(CondLoc, "case value is not a constant integer");
7975
7976 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7977 }
7978
7979 Lex.Lex(); // Eat the ']'.
7980
7981 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7982 for (const auto &[OnVal, Dest] : Table)
7983 SI->addCase(OnVal, Dest);
7984 Inst = SI;
7985 return false;
7986}
7987
7988/// parseIndirectBr
7989/// Instruction
7990/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7991bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7992 LocTy AddrLoc;
7993 Value *Address;
7994 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7995 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7996 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7997 return true;
7998
7999 if (!Address->getType()->isPointerTy())
8000 return error(AddrLoc, "indirectbr address must have pointer type");
8001
8002 // parse the destination list.
8003 SmallVector<BasicBlock*, 16> DestList;
8004
8005 if (Lex.getKind() != lltok::rsquare) {
8006 BasicBlock *DestBB;
8007 if (parseTypeAndBasicBlock(DestBB, PFS))
8008 return true;
8009 DestList.push_back(DestBB);
8010
8011 while (EatIfPresent(lltok::comma)) {
8012 if (parseTypeAndBasicBlock(DestBB, PFS))
8013 return true;
8014 DestList.push_back(DestBB);
8015 }
8016 }
8017
8018 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8019 return true;
8020
8021 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8022 for (BasicBlock *Dest : DestList)
8023 IBI->addDestination(Dest);
8024 Inst = IBI;
8025 return false;
8026}
8027
8028// If RetType is a non-function pointer type, then this is the short syntax
8029// for the call, which means that RetType is just the return type. Infer the
8030// rest of the function argument types from the arguments that are present.
8031bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8032 FunctionType *&FuncTy) {
8033 FuncTy = dyn_cast<FunctionType>(RetType);
8034 if (!FuncTy) {
8035 // Pull out the types of all of the arguments...
8036 SmallVector<Type *, 8> ParamTypes;
8037 ParamTypes.reserve(ArgList.size());
8038 for (const ParamInfo &Arg : ArgList)
8039 ParamTypes.push_back(Arg.V->getType());
8040
8041 if (!FunctionType::isValidReturnType(RetType))
8042 return true;
8043
8044 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8045 }
8046 return false;
8047}
8048
8049/// parseInvoke
8050/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8051/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8052bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8053 LocTy CallLoc = Lex.getLoc();
8054 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8055 std::vector<unsigned> FwdRefAttrGrps;
8056 LocTy NoBuiltinLoc;
8057 unsigned CC;
8058 unsigned InvokeAddrSpace;
8059 Type *RetType = nullptr;
8060 LocTy RetTypeLoc;
8061 ValID CalleeID;
8064
8065 BasicBlock *NormalBB, *UnwindBB;
8066 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8067 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8068 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8069 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8070 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8071 NoBuiltinLoc) ||
8072 parseOptionalOperandBundles(BundleList, PFS) ||
8073 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8074 parseTypeAndBasicBlock(NormalBB, PFS) ||
8075 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8076 parseTypeAndBasicBlock(UnwindBB, PFS))
8077 return true;
8078
8079 // If RetType is a non-function pointer type, then this is the short syntax
8080 // for the call, which means that RetType is just the return type. Infer the
8081 // rest of the function argument types from the arguments that are present.
8082 FunctionType *Ty;
8083 if (resolveFunctionType(RetType, ArgList, Ty))
8084 return error(RetTypeLoc, "Invalid result type for LLVM function");
8085
8086 CalleeID.FTy = Ty;
8087
8088 // Look up the callee.
8089 Value *Callee;
8090 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8091 Callee, &PFS))
8092 return true;
8093
8094 // Set up the Attribute for the function.
8095 SmallVector<Value *, 8> Args;
8097
8098 // Loop through FunctionType's arguments and ensure they are specified
8099 // correctly. Also, gather any parameter attributes.
8100 FunctionType::param_iterator I = Ty->param_begin();
8101 FunctionType::param_iterator E = Ty->param_end();
8102 for (const ParamInfo &Arg : ArgList) {
8103 Type *ExpectedTy = nullptr;
8104 if (I != E) {
8105 ExpectedTy = *I++;
8106 } else if (!Ty->isVarArg()) {
8107 return error(Arg.Loc, "too many arguments specified");
8108 }
8109
8110 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8111 return error(Arg.Loc, "argument is not of expected type '" +
8112 getTypeString(ExpectedTy) + "'");
8113 Args.push_back(Arg.V);
8114 ArgAttrs.push_back(Arg.Attrs);
8115 }
8116
8117 if (I != E)
8118 return error(CallLoc, "not enough parameters specified for call");
8119
8120 // Finish off the Attribute and check them
8121 AttributeList PAL =
8122 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8123 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8124
8125 InvokeInst *II =
8126 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8127 II->setCallingConv(CC);
8128 II->setAttributes(PAL);
8129 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8130 Inst = II;
8131 return false;
8132}
8133
8134/// parseResume
8135/// ::= 'resume' TypeAndValue
8136bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8137 Value *Exn; LocTy ExnLoc;
8138 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8139 return true;
8140
8141 ResumeInst *RI = ResumeInst::Create(Exn);
8142 Inst = RI;
8143 return false;
8144}
8145
8146bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8147 PerFunctionState &PFS) {
8148 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8149 return true;
8150
8151 while (Lex.getKind() != lltok::rsquare) {
8152 // If this isn't the first argument, we need a comma.
8153 if (!Args.empty() &&
8154 parseToken(lltok::comma, "expected ',' in argument list"))
8155 return true;
8156
8157 // parse the argument.
8158 LocTy ArgLoc;
8159 Type *ArgTy = nullptr;
8160 if (parseType(ArgTy, ArgLoc))
8161 return true;
8162
8163 Value *V;
8164 if (ArgTy->isMetadataTy()) {
8165 if (parseMetadataAsValue(V, PFS))
8166 return true;
8167 } else {
8168 if (parseValue(ArgTy, V, PFS))
8169 return true;
8170 }
8171 Args.push_back(V);
8172 }
8173
8174 Lex.Lex(); // Lex the ']'.
8175 return false;
8176}
8177
8178/// parseCleanupRet
8179/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8180bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8181 Value *CleanupPad = nullptr;
8182
8183 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8184 return true;
8185
8186 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8187 return true;
8188
8189 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8190 return true;
8191
8192 BasicBlock *UnwindBB = nullptr;
8193 if (Lex.getKind() == lltok::kw_to) {
8194 Lex.Lex();
8195 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8196 return true;
8197 } else {
8198 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8199 return true;
8200 }
8201 }
8202
8203 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8204 return false;
8205}
8206
8207/// parseCatchRet
8208/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8209bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8210 Value *CatchPad = nullptr;
8211
8212 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8213 return true;
8214
8215 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8216 return true;
8217
8218 BasicBlock *BB;
8219 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8220 parseTypeAndBasicBlock(BB, PFS))
8221 return true;
8222
8223 Inst = CatchReturnInst::Create(CatchPad, BB);
8224 return false;
8225}
8226
8227/// parseCatchSwitch
8228/// ::= 'catchswitch' within Parent
8229bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8230 Value *ParentPad;
8231
8232 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8233 return true;
8234
8235 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8236 Lex.getKind() != lltok::LocalVarID)
8237 return tokError("expected scope value for catchswitch");
8238
8239 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8240 return true;
8241
8242 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8243 return true;
8244
8246 do {
8247 BasicBlock *DestBB;
8248 if (parseTypeAndBasicBlock(DestBB, PFS))
8249 return true;
8250 Table.push_back(DestBB);
8251 } while (EatIfPresent(lltok::comma));
8252
8253 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8254 return true;
8255
8256 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8257 return true;
8258
8259 BasicBlock *UnwindBB = nullptr;
8260 if (EatIfPresent(lltok::kw_to)) {
8261 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8262 return true;
8263 } else {
8264 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8265 return true;
8266 }
8267
8268 auto *CatchSwitch =
8269 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8270 for (BasicBlock *DestBB : Table)
8271 CatchSwitch->addHandler(DestBB);
8272 Inst = CatchSwitch;
8273 return false;
8274}
8275
8276/// parseCatchPad
8277/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8278bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8279 Value *CatchSwitch = nullptr;
8280
8281 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8282 return true;
8283
8284 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8285 return tokError("expected scope value for catchpad");
8286
8287 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8288 return true;
8289
8290 SmallVector<Value *, 8> Args;
8291 if (parseExceptionArgs(Args, PFS))
8292 return true;
8293
8294 Inst = CatchPadInst::Create(CatchSwitch, Args);
8295 return false;
8296}
8297
8298/// parseCleanupPad
8299/// ::= 'cleanuppad' within Parent ParamList
8300bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8301 Value *ParentPad = nullptr;
8302
8303 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8304 return true;
8305
8306 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8307 Lex.getKind() != lltok::LocalVarID)
8308 return tokError("expected scope value for cleanuppad");
8309
8310 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8311 return true;
8312
8313 SmallVector<Value *, 8> Args;
8314 if (parseExceptionArgs(Args, PFS))
8315 return true;
8316
8317 Inst = CleanupPadInst::Create(ParentPad, Args);
8318 return false;
8319}
8320
8321//===----------------------------------------------------------------------===//
8322// Unary Operators.
8323//===----------------------------------------------------------------------===//
8324
8325/// parseUnaryOp
8326/// ::= UnaryOp TypeAndValue ',' Value
8327///
8328/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8329/// operand is allowed.
8330bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8331 unsigned Opc, bool IsFP) {
8332 LocTy Loc; Value *LHS;
8333 if (parseTypeAndValue(LHS, Loc, PFS))
8334 return true;
8335
8336 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8338
8339 if (!Valid)
8340 return error(Loc, "invalid operand type for instruction");
8341
8343 return false;
8344}
8345
8346/// parseCallBr
8347/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8348/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8349/// '[' LabelList ']'
8350bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8351 LocTy CallLoc = Lex.getLoc();
8352 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8353 std::vector<unsigned> FwdRefAttrGrps;
8354 LocTy NoBuiltinLoc;
8355 unsigned CC;
8356 Type *RetType = nullptr;
8357 LocTy RetTypeLoc;
8358 ValID CalleeID;
8361
8362 BasicBlock *DefaultDest;
8363 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8364 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8365 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8366 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8367 NoBuiltinLoc) ||
8368 parseOptionalOperandBundles(BundleList, PFS) ||
8369 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8370 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8371 parseToken(lltok::lsquare, "expected '[' in callbr"))
8372 return true;
8373
8374 // parse the destination list.
8375 SmallVector<BasicBlock *, 16> IndirectDests;
8376
8377 if (Lex.getKind() != lltok::rsquare) {
8378 BasicBlock *DestBB;
8379 if (parseTypeAndBasicBlock(DestBB, PFS))
8380 return true;
8381 IndirectDests.push_back(DestBB);
8382
8383 while (EatIfPresent(lltok::comma)) {
8384 if (parseTypeAndBasicBlock(DestBB, PFS))
8385 return true;
8386 IndirectDests.push_back(DestBB);
8387 }
8388 }
8389
8390 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8391 return true;
8392
8393 // If RetType is a non-function pointer type, then this is the short syntax
8394 // for the call, which means that RetType is just the return type. Infer the
8395 // rest of the function argument types from the arguments that are present.
8396 FunctionType *Ty;
8397 if (resolveFunctionType(RetType, ArgList, Ty))
8398 return error(RetTypeLoc, "Invalid result type for LLVM function");
8399
8400 CalleeID.FTy = Ty;
8401
8402 // Look up the callee.
8403 Value *Callee;
8404 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8405 &PFS))
8406 return true;
8407
8408 // Set up the Attribute for the function.
8409 SmallVector<Value *, 8> Args;
8411
8412 // Loop through FunctionType's arguments and ensure they are specified
8413 // correctly. Also, gather any parameter attributes.
8414 FunctionType::param_iterator I = Ty->param_begin();
8415 FunctionType::param_iterator E = Ty->param_end();
8416 for (const ParamInfo &Arg : ArgList) {
8417 Type *ExpectedTy = nullptr;
8418 if (I != E) {
8419 ExpectedTy = *I++;
8420 } else if (!Ty->isVarArg()) {
8421 return error(Arg.Loc, "too many arguments specified");
8422 }
8423
8424 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8425 return error(Arg.Loc, "argument is not of expected type '" +
8426 getTypeString(ExpectedTy) + "'");
8427 Args.push_back(Arg.V);
8428 ArgAttrs.push_back(Arg.Attrs);
8429 }
8430
8431 if (I != E)
8432 return error(CallLoc, "not enough parameters specified for call");
8433
8434 // Finish off the Attribute and check them
8435 AttributeList PAL =
8436 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8437 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8438
8439 CallBrInst *CBI =
8440 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8441 BundleList);
8442 CBI->setCallingConv(CC);
8443 CBI->setAttributes(PAL);
8444 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8445 Inst = CBI;
8446 return false;
8447}
8448
8449//===----------------------------------------------------------------------===//
8450// Binary Operators.
8451//===----------------------------------------------------------------------===//
8452
8453/// parseArithmetic
8454/// ::= ArithmeticOps TypeAndValue ',' Value
8455///
8456/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8457/// operand is allowed.
8458bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8459 unsigned Opc, bool IsFP) {
8460 LocTy Loc; Value *LHS, *RHS;
8461 if (parseTypeAndValue(LHS, Loc, PFS) ||
8462 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8463 parseValue(LHS->getType(), RHS, PFS))
8464 return true;
8465
8466 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8468
8469 if (!Valid)
8470 return error(Loc, "invalid operand type for instruction");
8471
8473 return false;
8474}
8475
8476/// parseLogical
8477/// ::= ArithmeticOps TypeAndValue ',' Value {
8478bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8479 unsigned Opc) {
8480 LocTy Loc; Value *LHS, *RHS;
8481 if (parseTypeAndValue(LHS, Loc, PFS) ||
8482 parseToken(lltok::comma, "expected ',' in logical operation") ||
8483 parseValue(LHS->getType(), RHS, PFS))
8484 return true;
8485
8486 if (!LHS->getType()->isIntOrIntVectorTy())
8487 return error(Loc,
8488 "instruction requires integer or integer vector operands");
8489
8491 return false;
8492}
8493
8494/// parseCompare
8495/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8496/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8497bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8498 unsigned Opc) {
8499 // parse the integer/fp comparison predicate.
8500 LocTy Loc;
8501 unsigned Pred;
8502 Value *LHS, *RHS;
8503 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8504 parseToken(lltok::comma, "expected ',' after compare value") ||
8505 parseValue(LHS->getType(), RHS, PFS))
8506 return true;
8507
8508 if (Opc == Instruction::FCmp) {
8509 if (!LHS->getType()->isFPOrFPVectorTy())
8510 return error(Loc, "fcmp requires floating point operands");
8511 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8512 } else {
8513 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8514 if (!LHS->getType()->isIntOrIntVectorTy() &&
8516 return error(Loc, "icmp requires integer operands");
8517 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8518 }
8519 return false;
8520}
8521
8522//===----------------------------------------------------------------------===//
8523// Other Instructions.
8524//===----------------------------------------------------------------------===//
8525
8526/// parseCast
8527/// ::= CastOpc TypeAndValue 'to' Type
8528bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8529 unsigned Opc) {
8530 LocTy Loc;
8531 Value *Op;
8532 Type *DestTy = nullptr;
8533 if (parseTypeAndValue(Op, Loc, PFS) ||
8534 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8535 parseType(DestTy))
8536 return true;
8537
8539 return error(Loc, "invalid cast opcode for cast from '" +
8540 getTypeString(Op->getType()) + "' to '" +
8541 getTypeString(DestTy) + "'");
8542 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8543 return false;
8544}
8545
8546/// parseSelect
8547/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8548bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8549 LocTy Loc;
8550 Value *Op0, *Op1, *Op2;
8551 if (parseTypeAndValue(Op0, Loc, PFS) ||
8552 parseToken(lltok::comma, "expected ',' after select condition") ||
8553 parseTypeAndValue(Op1, PFS) ||
8554 parseToken(lltok::comma, "expected ',' after select value") ||
8555 parseTypeAndValue(Op2, PFS))
8556 return true;
8557
8558 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8559 return error(Loc, Reason);
8560
8561 Inst = SelectInst::Create(Op0, Op1, Op2);
8562 return false;
8563}
8564
8565/// parseVAArg
8566/// ::= 'va_arg' TypeAndValue ',' Type
8567bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8568 Value *Op;
8569 Type *EltTy = nullptr;
8570 LocTy TypeLoc;
8571 if (parseTypeAndValue(Op, PFS) ||
8572 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8573 parseType(EltTy, TypeLoc))
8574 return true;
8575
8576 if (!EltTy->isFirstClassType())
8577 return error(TypeLoc, "va_arg requires operand with first class type");
8578
8579 Inst = new VAArgInst(Op, EltTy);
8580 return false;
8581}
8582
8583/// parseExtractElement
8584/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8585bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8586 LocTy Loc;
8587 Value *Op0, *Op1;
8588 if (parseTypeAndValue(Op0, Loc, PFS) ||
8589 parseToken(lltok::comma, "expected ',' after extract value") ||
8590 parseTypeAndValue(Op1, PFS))
8591 return true;
8592
8594 return error(Loc, "invalid extractelement operands");
8595
8596 Inst = ExtractElementInst::Create(Op0, Op1);
8597 return false;
8598}
8599
8600/// parseInsertElement
8601/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8602bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8603 LocTy Loc;
8604 Value *Op0, *Op1, *Op2;
8605 if (parseTypeAndValue(Op0, Loc, PFS) ||
8606 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8607 parseTypeAndValue(Op1, PFS) ||
8608 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8609 parseTypeAndValue(Op2, PFS))
8610 return true;
8611
8612 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8613 return error(Loc, "invalid insertelement operands");
8614
8615 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8616 return false;
8617}
8618
8619/// parseShuffleVector
8620/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8621bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8622 LocTy Loc;
8623 Value *Op0, *Op1, *Op2;
8624 if (parseTypeAndValue(Op0, Loc, PFS) ||
8625 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8626 parseTypeAndValue(Op1, PFS) ||
8627 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8628 parseTypeAndValue(Op2, PFS))
8629 return true;
8630
8631 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8632 return error(Loc, "invalid shufflevector operands");
8633
8634 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8635 return false;
8636}
8637
8638/// parsePHI
8639/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8640int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8641 Type *Ty = nullptr; LocTy TypeLoc;
8642 Value *Op0, *Op1;
8643
8644 if (parseType(Ty, TypeLoc))
8645 return true;
8646
8647 if (!Ty->isFirstClassType())
8648 return error(TypeLoc, "phi node must have first class type");
8649
8650 bool First = true;
8651 bool AteExtraComma = false;
8653
8654 while (true) {
8655 if (First) {
8656 if (Lex.getKind() != lltok::lsquare)
8657 break;
8658 First = false;
8659 } else if (!EatIfPresent(lltok::comma))
8660 break;
8661
8662 if (Lex.getKind() == lltok::MetadataVar) {
8663 AteExtraComma = true;
8664 break;
8665 }
8666
8667 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8668 parseValue(Ty, Op0, PFS) ||
8669 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8670 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8671 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8672 return true;
8673
8674 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8675 }
8676
8677 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8678 for (const auto &[Val, BB] : PHIVals)
8679 PN->addIncoming(Val, BB);
8680 Inst = PN;
8681 return AteExtraComma ? InstExtraComma : InstNormal;
8682}
8683
8684/// parseLandingPad
8685/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8686/// Clause
8687/// ::= 'catch' TypeAndValue
8688/// ::= 'filter'
8689/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8690bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8691 Type *Ty = nullptr; LocTy TyLoc;
8692
8693 if (parseType(Ty, TyLoc))
8694 return true;
8695
8696 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8697 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8698
8699 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8701 if (EatIfPresent(lltok::kw_catch))
8703 else if (EatIfPresent(lltok::kw_filter))
8705 else
8706 return tokError("expected 'catch' or 'filter' clause type");
8707
8708 Value *V;
8709 LocTy VLoc;
8710 if (parseTypeAndValue(V, VLoc, PFS))
8711 return true;
8712
8713 // A 'catch' type expects a non-array constant. A filter clause expects an
8714 // array constant.
8715 if (CT == LandingPadInst::Catch) {
8716 if (isa<ArrayType>(V->getType()))
8717 return error(VLoc, "'catch' clause has an invalid type");
8718 } else {
8719 if (!isa<ArrayType>(V->getType()))
8720 return error(VLoc, "'filter' clause has an invalid type");
8721 }
8722
8724 if (!CV)
8725 return error(VLoc, "clause argument must be a constant");
8726 LP->addClause(CV);
8727 }
8728
8729 Inst = LP.release();
8730 return false;
8731}
8732
8733/// parseFreeze
8734/// ::= 'freeze' Type Value
8735bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8736 LocTy Loc;
8737 Value *Op;
8738 if (parseTypeAndValue(Op, Loc, PFS))
8739 return true;
8740
8741 Inst = new FreezeInst(Op);
8742 return false;
8743}
8744
8745/// parseCall
8746/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8747/// OptionalAttrs Type Value ParameterList OptionalAttrs
8748/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8749/// OptionalAttrs Type Value ParameterList OptionalAttrs
8750/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8751/// OptionalAttrs Type Value ParameterList OptionalAttrs
8752/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8753/// OptionalAttrs Type Value ParameterList OptionalAttrs
8754bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8756 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8757 std::vector<unsigned> FwdRefAttrGrps;
8758 LocTy BuiltinLoc;
8759 unsigned CallAddrSpace;
8760 unsigned CC;
8761 Type *RetType = nullptr;
8762 LocTy RetTypeLoc;
8763 ValID CalleeID;
8766 LocTy CallLoc = Lex.getLoc();
8767
8768 if (TCK != CallInst::TCK_None &&
8769 parseToken(lltok::kw_call,
8770 "expected 'tail call', 'musttail call', or 'notail call'"))
8771 return true;
8772
8773 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8774
8775 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8776 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8777 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8778 parseValID(CalleeID, &PFS) ||
8779 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8780 PFS.getFunction().isVarArg()) ||
8781 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8782 parseOptionalOperandBundles(BundleList, PFS))
8783 return true;
8784
8785 // If RetType is a non-function pointer type, then this is the short syntax
8786 // for the call, which means that RetType is just the return type. Infer the
8787 // rest of the function argument types from the arguments that are present.
8788 FunctionType *Ty;
8789 if (resolveFunctionType(RetType, ArgList, Ty))
8790 return error(RetTypeLoc, "Invalid result type for LLVM function");
8791
8792 CalleeID.FTy = Ty;
8793
8794 // Look up the callee.
8795 Value *Callee;
8796 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8797 Callee, &PFS))
8798 return true;
8799
8800 // Set up the Attribute for the function.
8802
8803 SmallVector<Value*, 8> Args;
8804
8805 // Loop through FunctionType's arguments and ensure they are specified
8806 // correctly. Also, gather any parameter attributes.
8807 FunctionType::param_iterator I = Ty->param_begin();
8808 FunctionType::param_iterator E = Ty->param_end();
8809 for (const ParamInfo &Arg : ArgList) {
8810 Type *ExpectedTy = nullptr;
8811 if (I != E) {
8812 ExpectedTy = *I++;
8813 } else if (!Ty->isVarArg()) {
8814 return error(Arg.Loc, "too many arguments specified");
8815 }
8816
8817 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8818 return error(Arg.Loc, "argument is not of expected type '" +
8819 getTypeString(ExpectedTy) + "'");
8820 Args.push_back(Arg.V);
8821 Attrs.push_back(Arg.Attrs);
8822 }
8823
8824 if (I != E)
8825 return error(CallLoc, "not enough parameters specified for call");
8826
8827 // Finish off the Attribute and check them
8828 AttributeList PAL =
8829 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8830 AttributeSet::get(Context, RetAttrs), Attrs);
8831
8832 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8833 CI->setTailCallKind(TCK);
8834 CI->setCallingConv(CC);
8835 if (FMF.any()) {
8836 if (!isa<FPMathOperator>(CI)) {
8837 CI->deleteValue();
8838 return error(CallLoc, "fast-math-flags specified for call without "
8839 "floating-point scalar or vector return type");
8840 }
8841 CI->setFastMathFlags(FMF);
8842 }
8843
8844 if (CalleeID.Kind == ValID::t_GlobalName &&
8845 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8846 if (SeenNewDbgInfoFormat) {
8847 CI->deleteValue();
8848 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8849 "using non-intrinsic debug info");
8850 }
8851 SeenOldDbgInfoFormat = true;
8852 }
8853 CI->setAttributes(PAL);
8854 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8855 Inst = CI;
8856 return false;
8857}
8858
8859//===----------------------------------------------------------------------===//
8860// Memory Instructions.
8861//===----------------------------------------------------------------------===//
8862
8863/// parseAlloc
8864/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8865/// (',' 'align' i32)? (',', 'addrspace(n))?
8866int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8867 Value *Size = nullptr;
8868 LocTy SizeLoc, TyLoc, ASLoc;
8869 MaybeAlign Alignment;
8870 unsigned AddrSpace = 0;
8871 Type *Ty = nullptr;
8872
8873 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8874 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8875
8876 if (parseType(Ty, TyLoc))
8877 return true;
8878
8880 return error(TyLoc, "invalid type for alloca");
8881
8882 bool AteExtraComma = false;
8883 if (EatIfPresent(lltok::comma)) {
8884 if (Lex.getKind() == lltok::kw_align) {
8885 if (parseOptionalAlignment(Alignment))
8886 return true;
8887 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8888 return true;
8889 } else if (Lex.getKind() == lltok::kw_addrspace) {
8890 ASLoc = Lex.getLoc();
8891 if (parseOptionalAddrSpace(AddrSpace))
8892 return true;
8893 } else if (Lex.getKind() == lltok::MetadataVar) {
8894 AteExtraComma = true;
8895 } else {
8896 if (parseTypeAndValue(Size, SizeLoc, PFS))
8897 return true;
8898 if (EatIfPresent(lltok::comma)) {
8899 if (Lex.getKind() == lltok::kw_align) {
8900 if (parseOptionalAlignment(Alignment))
8901 return true;
8902 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8903 return true;
8904 } else if (Lex.getKind() == lltok::kw_addrspace) {
8905 ASLoc = Lex.getLoc();
8906 if (parseOptionalAddrSpace(AddrSpace))
8907 return true;
8908 } else if (Lex.getKind() == lltok::MetadataVar) {
8909 AteExtraComma = true;
8910 }
8911 }
8912 }
8913 }
8914
8915 if (Size && !Size->getType()->isIntegerTy())
8916 return error(SizeLoc, "element count must have integer type");
8917
8918 SmallPtrSet<Type *, 4> Visited;
8919 if (!Alignment && !Ty->isSized(&Visited))
8920 return error(TyLoc, "Cannot allocate unsized type");
8921 if (!Alignment)
8922 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8923 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8924 AI->setUsedWithInAlloca(IsInAlloca);
8925 AI->setSwiftError(IsSwiftError);
8926 Inst = AI;
8927 return AteExtraComma ? InstExtraComma : InstNormal;
8928}
8929
8930/// parseLoad
8931/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8932/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8933/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8934int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8935 Value *Val; LocTy Loc;
8936 MaybeAlign Alignment;
8937 bool AteExtraComma = false;
8938 bool isAtomic = false;
8941
8942 if (Lex.getKind() == lltok::kw_atomic) {
8943 isAtomic = true;
8944 Lex.Lex();
8945 }
8946
8947 bool isVolatile = false;
8948 if (Lex.getKind() == lltok::kw_volatile) {
8949 isVolatile = true;
8950 Lex.Lex();
8951 }
8952
8953 Type *Ty;
8954 LocTy ExplicitTypeLoc = Lex.getLoc();
8955 if (parseType(Ty) ||
8956 parseToken(lltok::comma, "expected comma after load's type") ||
8957 parseTypeAndValue(Val, Loc, PFS) ||
8958 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8959 parseOptionalCommaAlign(Alignment, AteExtraComma))
8960 return true;
8961
8962 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8963 return error(Loc, "load operand must be a pointer to a first class type");
8964 if (isAtomic && !Alignment)
8965 return error(Loc, "atomic load must have explicit non-zero alignment");
8966 if (Ordering == AtomicOrdering::Release ||
8968 return error(Loc, "atomic load cannot use Release ordering");
8969
8970 SmallPtrSet<Type *, 4> Visited;
8971 if (!Alignment && !Ty->isSized(&Visited))
8972 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8973 if (!Alignment)
8974 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8975 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8976 return AteExtraComma ? InstExtraComma : InstNormal;
8977}
8978
8979/// parseStore
8980
8981/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8982/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8983/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8984int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8985 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8986 MaybeAlign Alignment;
8987 bool AteExtraComma = false;
8988 bool isAtomic = false;
8991
8992 if (Lex.getKind() == lltok::kw_atomic) {
8993 isAtomic = true;
8994 Lex.Lex();
8995 }
8996
8997 bool isVolatile = false;
8998 if (Lex.getKind() == lltok::kw_volatile) {
8999 isVolatile = true;
9000 Lex.Lex();
9001 }
9002
9003 if (parseTypeAndValue(Val, Loc, PFS) ||
9004 parseToken(lltok::comma, "expected ',' after store operand") ||
9005 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9006 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9007 parseOptionalCommaAlign(Alignment, AteExtraComma))
9008 return true;
9009
9010 if (!Ptr->getType()->isPointerTy())
9011 return error(PtrLoc, "store operand must be a pointer");
9012 if (!Val->getType()->isFirstClassType())
9013 return error(Loc, "store operand must be a first class value");
9014 if (isAtomic && !Alignment)
9015 return error(Loc, "atomic store must have explicit non-zero alignment");
9016 if (Ordering == AtomicOrdering::Acquire ||
9018 return error(Loc, "atomic store cannot use Acquire ordering");
9019 SmallPtrSet<Type *, 4> Visited;
9020 if (!Alignment && !Val->getType()->isSized(&Visited))
9021 return error(Loc, "storing unsized types is not allowed");
9022 if (!Alignment)
9023 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9024
9025 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
9026 return AteExtraComma ? InstExtraComma : InstNormal;
9027}
9028
9029/// parseCmpXchg
9030/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9031/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9032/// 'Align'?
9033int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9034 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9035 bool AteExtraComma = false;
9036 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9037 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9039 bool isVolatile = false;
9040 bool isWeak = false;
9041 MaybeAlign Alignment;
9042
9043 if (EatIfPresent(lltok::kw_weak))
9044 isWeak = true;
9045
9046 if (EatIfPresent(lltok::kw_volatile))
9047 isVolatile = true;
9048
9049 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9050 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9051 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9052 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9053 parseTypeAndValue(New, NewLoc, PFS) ||
9054 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9055 parseOrdering(FailureOrdering) ||
9056 parseOptionalCommaAlign(Alignment, AteExtraComma))
9057 return true;
9058
9059 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9060 return tokError("invalid cmpxchg success ordering");
9061 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9062 return tokError("invalid cmpxchg failure ordering");
9063 if (!Ptr->getType()->isPointerTy())
9064 return error(PtrLoc, "cmpxchg operand must be a pointer");
9065 if (Cmp->getType() != New->getType())
9066 return error(NewLoc, "compare value and new value type do not match");
9067 if (!New->getType()->isFirstClassType())
9068 return error(NewLoc, "cmpxchg operand must be a first class value");
9069
9070 const Align DefaultAlignment(
9071 PFS.getFunction().getDataLayout().getTypeStoreSize(
9072 Cmp->getType()));
9073
9074 AtomicCmpXchgInst *CXI =
9075 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9076 SuccessOrdering, FailureOrdering, SSID);
9077 CXI->setVolatile(isVolatile);
9078 CXI->setWeak(isWeak);
9079
9080 Inst = CXI;
9081 return AteExtraComma ? InstExtraComma : InstNormal;
9082}
9083
9084/// parseAtomicRMW
9085/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9086/// TypeAndValue
9087/// 'singlethread'? AtomicOrdering
9088int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9089 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9090 bool AteExtraComma = false;
9093 bool IsVolatile = false;
9094 bool IsElementwise = false;
9095 bool IsFP = false;
9097 MaybeAlign Alignment;
9098
9099 if (EatIfPresent(lltok::kw_volatile))
9100 IsVolatile = true;
9101 if (EatIfPresent(lltok::kw_elementwise))
9102 IsElementwise = true;
9103
9104 switch (Lex.getKind()) {
9105 default:
9106 return tokError("expected binary operation in atomicrmw");
9120 break;
9123 break;
9126 break;
9127 case lltok::kw_usub_sat:
9129 break;
9130 case lltok::kw_fadd:
9132 IsFP = true;
9133 break;
9134 case lltok::kw_fsub:
9136 IsFP = true;
9137 break;
9138 case lltok::kw_fmax:
9140 IsFP = true;
9141 break;
9142 case lltok::kw_fmin:
9144 IsFP = true;
9145 break;
9146 case lltok::kw_fmaximum:
9148 IsFP = true;
9149 break;
9150 case lltok::kw_fminimum:
9152 IsFP = true;
9153 break;
9156 IsFP = true;
9157 break;
9160 IsFP = true;
9161 break;
9162 }
9163 Lex.Lex(); // Eat the operation.
9164
9165 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9166 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9167 parseTypeAndValue(Val, ValLoc, PFS) ||
9168 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9169 parseOptionalCommaAlign(Alignment, AteExtraComma))
9170 return true;
9171
9172 if (Ordering == AtomicOrdering::Unordered)
9173 return tokError("atomicrmw cannot be unordered");
9174 if (!Ptr->getType()->isPointerTy())
9175 return error(PtrLoc, "atomicrmw operand must be a pointer");
9176 if (Val->getType()->isScalableTy())
9177 return error(ValLoc, "atomicrmw operand may not be scalable");
9178
9179 // For elementwise ops, the value must be a fixed vector type whose element
9180 // type is legal for the corresponding scalar atomicrmw operation. So assign
9181 // ScalarTy the element type for elementwise ops so we can check this.
9182 Type *ScalarTy = Val->getType();
9183 if (IsElementwise) {
9184 auto *VecTy = dyn_cast<FixedVectorType>(Val->getType());
9185 if (!VecTy)
9186 return error(ValLoc,
9187 "atomicrmw elementwise operand must be a fixed vector type");
9188 ScalarTy = VecTy->getElementType();
9189 }
9190
9192 if (!ScalarTy->isIntegerTy() && !ScalarTy->isFloatingPointTy() &&
9193 !ScalarTy->isPointerTy()) {
9194 return error(
9195 ValLoc,
9197 " operand must be an integer, floating point, or pointer type");
9198 }
9199 } else if (IsFP) {
9200 if (!ScalarTy->isFPOrFPVectorTy()) {
9201 return error(ValLoc, "atomicrmw " +
9203 " operand must be a floating point type");
9204 }
9205 } else {
9206 if (!ScalarTy->isIntegerTy()) {
9207 return error(ValLoc, "atomicrmw " +
9209 " operand must be an integer");
9210 }
9211 }
9212
9213 unsigned Size =
9214 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->getType());
9215 if (Size < 8 || (Size & (Size - 1)))
9216 return error(ValLoc,
9217 "atomicrmw operand must have a power-of-two byte size");
9218 const Align DefaultAlignment(
9219 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9220 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9221 Alignment.value_or(DefaultAlignment),
9222 Ordering, SSID, IsElementwise);
9223 RMWI->setVolatile(IsVolatile);
9224 Inst = RMWI;
9225 return AteExtraComma ? InstExtraComma : InstNormal;
9226}
9227
9228/// parseFence
9229/// ::= 'fence' 'singlethread'? AtomicOrdering
9230int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9233 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9234 return true;
9235
9236 if (Ordering == AtomicOrdering::Unordered)
9237 return tokError("fence cannot be unordered");
9238 if (Ordering == AtomicOrdering::Monotonic)
9239 return tokError("fence cannot be monotonic");
9240
9241 Inst = new FenceInst(Context, Ordering, SSID);
9242 return InstNormal;
9243}
9244
9245/// parseGetElementPtr
9246/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9247int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9248 Value *Ptr = nullptr;
9249 Value *Val = nullptr;
9250 LocTy Loc, EltLoc;
9251 GEPNoWrapFlags NW;
9252
9253 while (true) {
9254 if (EatIfPresent(lltok::kw_inbounds))
9256 else if (EatIfPresent(lltok::kw_nusw))
9258 else if (EatIfPresent(lltok::kw_nuw))
9260 else
9261 break;
9262 }
9263
9264 Type *Ty = nullptr;
9265 if (parseType(Ty) ||
9266 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9267 parseTypeAndValue(Ptr, Loc, PFS))
9268 return true;
9269
9270 Type *BaseType = Ptr->getType();
9271 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9272 if (!BasePointerType)
9273 return error(Loc, "base of getelementptr must be a pointer");
9274
9275 SmallVector<Value*, 16> Indices;
9276 bool AteExtraComma = false;
9277 // GEP returns a vector of pointers if at least one of parameters is a vector.
9278 // All vector parameters should have the same vector width.
9279 ElementCount GEPWidth = BaseType->isVectorTy()
9280 ? cast<VectorType>(BaseType)->getElementCount()
9282
9283 while (EatIfPresent(lltok::comma)) {
9284 if (Lex.getKind() == lltok::MetadataVar) {
9285 AteExtraComma = true;
9286 break;
9287 }
9288 if (parseTypeAndValue(Val, EltLoc, PFS))
9289 return true;
9290 if (!Val->getType()->isIntOrIntVectorTy())
9291 return error(EltLoc, "getelementptr index must be an integer");
9292
9293 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9294 ElementCount ValNumEl = ValVTy->getElementCount();
9295 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9296 return error(
9297 EltLoc,
9298 "getelementptr vector index has a wrong number of elements");
9299 GEPWidth = ValNumEl;
9300 }
9301 Indices.push_back(Val);
9302 }
9303
9304 SmallPtrSet<Type*, 4> Visited;
9305 if (!Indices.empty() && !Ty->isSized(&Visited))
9306 return error(Loc, "base element of getelementptr must be sized");
9307
9308 auto *STy = dyn_cast<StructType>(Ty);
9309 if (STy && STy->isScalableTy())
9310 return error(Loc, "getelementptr cannot target structure that contains "
9311 "scalable vector type");
9312
9313 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9314 return error(Loc, "invalid getelementptr indices");
9315 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9316 Inst = GEP;
9317 GEP->setNoWrapFlags(NW);
9318 return AteExtraComma ? InstExtraComma : InstNormal;
9319}
9320
9321/// parseExtractValue
9322/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9323int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9324 Value *Val; LocTy Loc;
9325 SmallVector<unsigned, 4> Indices;
9326 bool AteExtraComma;
9327 if (parseTypeAndValue(Val, Loc, PFS) ||
9328 parseIndexList(Indices, AteExtraComma))
9329 return true;
9330
9331 if (!Val->getType()->isAggregateType())
9332 return error(Loc, "extractvalue operand must be aggregate type");
9333
9334 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9335 return error(Loc, "invalid indices for extractvalue");
9336 Inst = ExtractValueInst::Create(Val, Indices);
9337 return AteExtraComma ? InstExtraComma : InstNormal;
9338}
9339
9340/// parseInsertValue
9341/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9342int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9343 Value *Val0, *Val1; LocTy Loc0, Loc1;
9344 SmallVector<unsigned, 4> Indices;
9345 bool AteExtraComma;
9346 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9347 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9348 parseTypeAndValue(Val1, Loc1, PFS) ||
9349 parseIndexList(Indices, AteExtraComma))
9350 return true;
9351
9352 if (!Val0->getType()->isAggregateType())
9353 return error(Loc0, "insertvalue operand must be aggregate type");
9354
9355 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9356 if (!IndexedType)
9357 return error(Loc0, "invalid indices for insertvalue");
9358 if (IndexedType != Val1->getType())
9359 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9360 getTypeString(Val1->getType()) + "' instead of '" +
9361 getTypeString(IndexedType) + "'");
9362 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9363 return AteExtraComma ? InstExtraComma : InstNormal;
9364}
9365
9366//===----------------------------------------------------------------------===//
9367// Embedded metadata.
9368//===----------------------------------------------------------------------===//
9369
9370/// parseMDNodeVector
9371/// ::= { Element (',' Element)* }
9372/// Element
9373/// ::= 'null' | Metadata
9374bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9375 if (parseToken(lltok::lbrace, "expected '{' here"))
9376 return true;
9377
9378 // Check for an empty list.
9379 if (EatIfPresent(lltok::rbrace))
9380 return false;
9381
9382 do {
9383 if (EatIfPresent(lltok::kw_null)) {
9384 Elts.push_back(nullptr);
9385 continue;
9386 }
9387
9388 Metadata *MD;
9389 if (parseMetadata(MD, nullptr))
9390 return true;
9391 Elts.push_back(MD);
9392 } while (EatIfPresent(lltok::comma));
9393
9394 return parseToken(lltok::rbrace, "expected end of metadata node");
9395}
9396
9397//===----------------------------------------------------------------------===//
9398// Use-list order directives.
9399//===----------------------------------------------------------------------===//
9400bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9401 SMLoc Loc) {
9402 if (!V->hasUseList())
9403 return false;
9404 if (V->use_empty())
9405 return error(Loc, "value has no uses");
9406
9407 unsigned NumUses = 0;
9408 SmallDenseMap<const Use *, unsigned, 16> Order;
9409 for (const Use &U : V->uses()) {
9410 if (++NumUses > Indexes.size())
9411 break;
9412 Order[&U] = Indexes[NumUses - 1];
9413 }
9414 if (NumUses < 2)
9415 return error(Loc, "value only has one use");
9416 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9417 return error(Loc,
9418 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9419
9420 V->sortUseList([&](const Use &L, const Use &R) {
9421 return Order.lookup(&L) < Order.lookup(&R);
9422 });
9423 return false;
9424}
9425
9426/// parseUseListOrderIndexes
9427/// ::= '{' uint32 (',' uint32)+ '}'
9428bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9429 SMLoc Loc = Lex.getLoc();
9430 if (parseToken(lltok::lbrace, "expected '{' here"))
9431 return true;
9432 if (Lex.getKind() == lltok::rbrace)
9433 return tokError("expected non-empty list of uselistorder indexes");
9434
9435 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9436 // indexes should be distinct numbers in the range [0, size-1], and should
9437 // not be in order.
9438 unsigned Offset = 0;
9439 unsigned Max = 0;
9440 bool IsOrdered = true;
9441 assert(Indexes.empty() && "Expected empty order vector");
9442 do {
9443 unsigned Index;
9444 if (parseUInt32(Index))
9445 return true;
9446
9447 // Update consistency checks.
9448 Offset += Index - Indexes.size();
9449 Max = std::max(Max, Index);
9450 IsOrdered &= Index == Indexes.size();
9451
9452 Indexes.push_back(Index);
9453 } while (EatIfPresent(lltok::comma));
9454
9455 if (parseToken(lltok::rbrace, "expected '}' here"))
9456 return true;
9457
9458 if (Indexes.size() < 2)
9459 return error(Loc, "expected >= 2 uselistorder indexes");
9460 if (Offset != 0 || Max >= Indexes.size())
9461 return error(Loc,
9462 "expected distinct uselistorder indexes in range [0, size)");
9463 if (IsOrdered)
9464 return error(Loc, "expected uselistorder indexes to change the order");
9465
9466 return false;
9467}
9468
9469/// parseUseListOrder
9470/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9471bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9472 SMLoc Loc = Lex.getLoc();
9473 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9474 return true;
9475
9476 Value *V;
9477 SmallVector<unsigned, 16> Indexes;
9478 if (parseTypeAndValue(V, PFS) ||
9479 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9480 parseUseListOrderIndexes(Indexes))
9481 return true;
9482
9483 return sortUseListOrder(V, Indexes, Loc);
9484}
9485
9486/// ModuleEntry
9487/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9488/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9489bool LLParser::parseModuleEntry(unsigned ID) {
9490 assert(Lex.getKind() == lltok::kw_module);
9491 Lex.Lex();
9492
9493 std::string Path;
9494 if (parseToken(lltok::colon, "expected ':' here") ||
9495 parseToken(lltok::lparen, "expected '(' here") ||
9496 parseToken(lltok::kw_path, "expected 'path' here") ||
9497 parseToken(lltok::colon, "expected ':' here") ||
9498 parseStringConstant(Path) ||
9499 parseToken(lltok::comma, "expected ',' here") ||
9500 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9501 parseToken(lltok::colon, "expected ':' here") ||
9502 parseToken(lltok::lparen, "expected '(' here"))
9503 return true;
9504
9505 ModuleHash Hash;
9506 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9507 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9508 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9509 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9510 parseUInt32(Hash[4]))
9511 return true;
9512
9513 if (parseToken(lltok::rparen, "expected ')' here") ||
9514 parseToken(lltok::rparen, "expected ')' here"))
9515 return true;
9516
9517 auto ModuleEntry = Index->addModule(Path, Hash);
9518 ModuleIdMap[ID] = ModuleEntry->first();
9519
9520 return false;
9521}
9522
9523/// TypeIdEntry
9524/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9525bool LLParser::parseTypeIdEntry(unsigned ID) {
9526 assert(Lex.getKind() == lltok::kw_typeid);
9527 Lex.Lex();
9528
9529 std::string Name;
9530 if (parseToken(lltok::colon, "expected ':' here") ||
9531 parseToken(lltok::lparen, "expected '(' here") ||
9532 parseToken(lltok::kw_name, "expected 'name' here") ||
9533 parseToken(lltok::colon, "expected ':' here") ||
9534 parseStringConstant(Name))
9535 return true;
9536
9537 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9538 if (parseToken(lltok::comma, "expected ',' here") ||
9539 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9540 return true;
9541
9542 // Check if this ID was forward referenced, and if so, update the
9543 // corresponding GUIDs.
9544 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9545 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9546 for (auto TIDRef : FwdRefTIDs->second) {
9547 assert(!*TIDRef.first &&
9548 "Forward referenced type id GUID expected to be 0");
9549 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9550 }
9551 ForwardRefTypeIds.erase(FwdRefTIDs);
9552 }
9553
9554 return false;
9555}
9556
9557/// TypeIdSummary
9558/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9559bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9560 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9561 parseToken(lltok::colon, "expected ':' here") ||
9562 parseToken(lltok::lparen, "expected '(' here") ||
9563 parseTypeTestResolution(TIS.TTRes))
9564 return true;
9565
9566 if (EatIfPresent(lltok::comma)) {
9567 // Expect optional wpdResolutions field
9568 if (parseOptionalWpdResolutions(TIS.WPDRes))
9569 return true;
9570 }
9571
9572 if (parseToken(lltok::rparen, "expected ')' here"))
9573 return true;
9574
9575 return false;
9576}
9577
9579 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9580
9581/// TypeIdCompatibleVtableEntry
9582/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9583/// TypeIdCompatibleVtableInfo
9584/// ')'
9585bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9587 Lex.Lex();
9588
9589 std::string Name;
9590 if (parseToken(lltok::colon, "expected ':' here") ||
9591 parseToken(lltok::lparen, "expected '(' here") ||
9592 parseToken(lltok::kw_name, "expected 'name' here") ||
9593 parseToken(lltok::colon, "expected ':' here") ||
9594 parseStringConstant(Name))
9595 return true;
9596
9598 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9599 if (parseToken(lltok::comma, "expected ',' here") ||
9600 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9601 parseToken(lltok::colon, "expected ':' here") ||
9602 parseToken(lltok::lparen, "expected '(' here"))
9603 return true;
9604
9605 IdToIndexMapType IdToIndexMap;
9606 // parse each call edge
9607 do {
9609 if (parseToken(lltok::lparen, "expected '(' here") ||
9610 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9611 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9612 parseToken(lltok::comma, "expected ',' here"))
9613 return true;
9614
9615 LocTy Loc = Lex.getLoc();
9616 unsigned GVId;
9617 ValueInfo VI;
9618 if (parseGVReference(VI, GVId))
9619 return true;
9620
9621 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9622 // forward reference. We will save the location of the ValueInfo needing an
9623 // update, but can only do so once the std::vector is finalized.
9624 if (VI == EmptyVI)
9625 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9626 TI.push_back({Offset, VI});
9627
9628 if (parseToken(lltok::rparen, "expected ')' in call"))
9629 return true;
9630 } while (EatIfPresent(lltok::comma));
9631
9632 // Now that the TI vector is finalized, it is safe to save the locations
9633 // of any forward GV references that need updating later.
9634 for (auto I : IdToIndexMap) {
9635 auto &Infos = ForwardRefValueInfos[I.first];
9636 for (auto P : I.second) {
9637 assert(TI[P.first].VTableVI == EmptyVI &&
9638 "Forward referenced ValueInfo expected to be empty");
9639 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9640 }
9641 }
9642
9643 if (parseToken(lltok::rparen, "expected ')' here") ||
9644 parseToken(lltok::rparen, "expected ')' here"))
9645 return true;
9646
9647 // Check if this ID was forward referenced, and if so, update the
9648 // corresponding GUIDs.
9649 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9650 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9651 for (auto TIDRef : FwdRefTIDs->second) {
9652 assert(!*TIDRef.first &&
9653 "Forward referenced type id GUID expected to be 0");
9654 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9655 }
9656 ForwardRefTypeIds.erase(FwdRefTIDs);
9657 }
9658
9659 return false;
9660}
9661
9662/// TypeTestResolution
9663/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9664/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9665/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9666/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9667/// [',' 'inlinesBits' ':' UInt64]? ')'
9668bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9669 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9670 parseToken(lltok::colon, "expected ':' here") ||
9671 parseToken(lltok::lparen, "expected '(' here") ||
9672 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9673 parseToken(lltok::colon, "expected ':' here"))
9674 return true;
9675
9676 switch (Lex.getKind()) {
9677 case lltok::kw_unknown:
9679 break;
9680 case lltok::kw_unsat:
9682 break;
9685 break;
9686 case lltok::kw_inline:
9688 break;
9689 case lltok::kw_single:
9691 break;
9692 case lltok::kw_allOnes:
9694 break;
9695 default:
9696 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9697 }
9698 Lex.Lex();
9699
9700 if (parseToken(lltok::comma, "expected ',' here") ||
9701 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9702 parseToken(lltok::colon, "expected ':' here") ||
9703 parseUInt32(TTRes.SizeM1BitWidth))
9704 return true;
9705
9706 // parse optional fields
9707 while (EatIfPresent(lltok::comma)) {
9708 switch (Lex.getKind()) {
9710 Lex.Lex();
9711 if (parseToken(lltok::colon, "expected ':'") ||
9712 parseUInt64(TTRes.AlignLog2))
9713 return true;
9714 break;
9715 case lltok::kw_sizeM1:
9716 Lex.Lex();
9717 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9718 return true;
9719 break;
9720 case lltok::kw_bitMask: {
9721 unsigned Val;
9722 Lex.Lex();
9723 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9724 return true;
9725 assert(Val <= 0xff);
9726 TTRes.BitMask = (uint8_t)Val;
9727 break;
9728 }
9730 Lex.Lex();
9731 if (parseToken(lltok::colon, "expected ':'") ||
9732 parseUInt64(TTRes.InlineBits))
9733 return true;
9734 break;
9735 default:
9736 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9737 }
9738 }
9739
9740 if (parseToken(lltok::rparen, "expected ')' here"))
9741 return true;
9742
9743 return false;
9744}
9745
9746/// OptionalWpdResolutions
9747/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9748/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9749bool LLParser::parseOptionalWpdResolutions(
9750 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9751 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9752 parseToken(lltok::colon, "expected ':' here") ||
9753 parseToken(lltok::lparen, "expected '(' here"))
9754 return true;
9755
9756 do {
9757 uint64_t Offset;
9758 WholeProgramDevirtResolution WPDRes;
9759 if (parseToken(lltok::lparen, "expected '(' here") ||
9760 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9761 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9762 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9763 parseToken(lltok::rparen, "expected ')' here"))
9764 return true;
9765 WPDResMap[Offset] = WPDRes;
9766 } while (EatIfPresent(lltok::comma));
9767
9768 if (parseToken(lltok::rparen, "expected ')' here"))
9769 return true;
9770
9771 return false;
9772}
9773
9774/// WpdRes
9775/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9776/// [',' OptionalResByArg]? ')'
9777/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9778/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9779/// [',' OptionalResByArg]? ')'
9780/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9781/// [',' OptionalResByArg]? ')'
9782bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9783 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9784 parseToken(lltok::colon, "expected ':' here") ||
9785 parseToken(lltok::lparen, "expected '(' here") ||
9786 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9787 parseToken(lltok::colon, "expected ':' here"))
9788 return true;
9789
9790 switch (Lex.getKind()) {
9791 case lltok::kw_indir:
9793 break;
9796 break;
9799 break;
9800 default:
9801 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9802 }
9803 Lex.Lex();
9804
9805 // parse optional fields
9806 while (EatIfPresent(lltok::comma)) {
9807 switch (Lex.getKind()) {
9809 Lex.Lex();
9810 if (parseToken(lltok::colon, "expected ':' here") ||
9811 parseStringConstant(WPDRes.SingleImplName))
9812 return true;
9813 break;
9814 case lltok::kw_resByArg:
9815 if (parseOptionalResByArg(WPDRes.ResByArg))
9816 return true;
9817 break;
9818 default:
9819 return error(Lex.getLoc(),
9820 "expected optional WholeProgramDevirtResolution field");
9821 }
9822 }
9823
9824 if (parseToken(lltok::rparen, "expected ')' here"))
9825 return true;
9826
9827 return false;
9828}
9829
9830/// OptionalResByArg
9831/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9832/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9833/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9834/// 'virtualConstProp' )
9835/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9836/// [',' 'bit' ':' UInt32]? ')'
9837bool LLParser::parseOptionalResByArg(
9838 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9839 &ResByArg) {
9840 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9841 parseToken(lltok::colon, "expected ':' here") ||
9842 parseToken(lltok::lparen, "expected '(' here"))
9843 return true;
9844
9845 do {
9846 std::vector<uint64_t> Args;
9847 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9848 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9849 parseToken(lltok::colon, "expected ':' here") ||
9850 parseToken(lltok::lparen, "expected '(' here") ||
9851 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9852 parseToken(lltok::colon, "expected ':' here"))
9853 return true;
9854
9855 WholeProgramDevirtResolution::ByArg ByArg;
9856 switch (Lex.getKind()) {
9857 case lltok::kw_indir:
9859 break;
9862 break;
9865 break;
9868 break;
9869 default:
9870 return error(Lex.getLoc(),
9871 "unexpected WholeProgramDevirtResolution::ByArg kind");
9872 }
9873 Lex.Lex();
9874
9875 // parse optional fields
9876 while (EatIfPresent(lltok::comma)) {
9877 switch (Lex.getKind()) {
9878 case lltok::kw_info:
9879 Lex.Lex();
9880 if (parseToken(lltok::colon, "expected ':' here") ||
9881 parseUInt64(ByArg.Info))
9882 return true;
9883 break;
9884 case lltok::kw_byte:
9885 Lex.Lex();
9886 if (parseToken(lltok::colon, "expected ':' here") ||
9887 parseUInt32(ByArg.Byte))
9888 return true;
9889 break;
9890 case lltok::kw_bit:
9891 Lex.Lex();
9892 if (parseToken(lltok::colon, "expected ':' here") ||
9893 parseUInt32(ByArg.Bit))
9894 return true;
9895 break;
9896 default:
9897 return error(Lex.getLoc(),
9898 "expected optional whole program devirt field");
9899 }
9900 }
9901
9902 if (parseToken(lltok::rparen, "expected ')' here"))
9903 return true;
9904
9905 ResByArg[Args] = ByArg;
9906 } while (EatIfPresent(lltok::comma));
9907
9908 if (parseToken(lltok::rparen, "expected ')' here"))
9909 return true;
9910
9911 return false;
9912}
9913
9914/// OptionalResByArg
9915/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9916bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9917 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9918 parseToken(lltok::colon, "expected ':' here") ||
9919 parseToken(lltok::lparen, "expected '(' here"))
9920 return true;
9921
9922 do {
9923 uint64_t Val;
9924 if (parseUInt64(Val))
9925 return true;
9926 Args.push_back(Val);
9927 } while (EatIfPresent(lltok::comma));
9928
9929 if (parseToken(lltok::rparen, "expected ')' here"))
9930 return true;
9931
9932 return false;
9933}
9934
9935static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9936
9937static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9938 bool ReadOnly = Fwd->isReadOnly();
9939 bool WriteOnly = Fwd->isWriteOnly();
9940 assert(!(ReadOnly && WriteOnly));
9941 *Fwd = Resolved;
9942 if (ReadOnly)
9943 Fwd->setReadOnly();
9944 if (WriteOnly)
9945 Fwd->setWriteOnly();
9946}
9947
9948/// Stores the given Name/GUID and associated summary into the Index.
9949/// Also updates any forward references to the associated entry ID.
9950bool LLParser::addGlobalValueToIndex(
9951 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9952 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9953 // First create the ValueInfo utilizing the Name or GUID.
9954 ValueInfo VI;
9955 if (GUID != 0) {
9956 assert(Name.empty());
9957 VI = Index->getOrInsertValueInfo(GUID);
9958 } else {
9959 assert(!Name.empty());
9960 if (M) {
9961 auto *GV = M->getNamedValue(Name);
9962 if (!GV)
9963 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9964
9965 VI = Index->getOrInsertValueInfo(GV);
9966 } else {
9967 assert(
9968 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9969 "Need a source_filename to compute GUID for local");
9971 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9972 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9973 }
9974 }
9975
9976 // Resolve forward references from calls/refs
9977 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9978 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9979 for (auto VIRef : FwdRefVIs->second) {
9980 assert(VIRef.first->getRef() == FwdVIRef &&
9981 "Forward referenced ValueInfo expected to be empty");
9982 resolveFwdRef(VIRef.first, VI);
9983 }
9984 ForwardRefValueInfos.erase(FwdRefVIs);
9985 }
9986
9987 // Resolve forward references from aliases
9988 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9989 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9990 for (auto AliaseeRef : FwdRefAliasees->second) {
9991 assert(!AliaseeRef.first->hasAliasee() &&
9992 "Forward referencing alias already has aliasee");
9993 assert(Summary && "Aliasee must be a definition");
9994 AliaseeRef.first->setAliasee(VI, Summary.get());
9995 }
9996 ForwardRefAliasees.erase(FwdRefAliasees);
9997 }
9998
9999 // Add the summary if one was provided.
10000 if (Summary)
10001 Index->addGlobalValueSummary(VI, std::move(Summary));
10002
10003 // Save the associated ValueInfo for use in later references by ID.
10004 if (ID == NumberedValueInfos.size())
10005 NumberedValueInfos.push_back(VI);
10006 else {
10007 // Handle non-continuous numbers (to make test simplification easier).
10008 if (ID > NumberedValueInfos.size())
10009 NumberedValueInfos.resize(ID + 1);
10010 NumberedValueInfos[ID] = VI;
10011 }
10012
10013 return false;
10014}
10015
10016/// parseSummaryIndexFlags
10017/// ::= 'flags' ':' UInt64
10018bool LLParser::parseSummaryIndexFlags() {
10019 assert(Lex.getKind() == lltok::kw_flags);
10020 Lex.Lex();
10021
10022 if (parseToken(lltok::colon, "expected ':' here"))
10023 return true;
10024 uint64_t Flags;
10025 if (parseUInt64(Flags))
10026 return true;
10027 if (Index)
10028 Index->setFlags(Flags);
10029 return false;
10030}
10031
10032/// parseBlockCount
10033/// ::= 'blockcount' ':' UInt64
10034bool LLParser::parseBlockCount() {
10035 assert(Lex.getKind() == lltok::kw_blockcount);
10036 Lex.Lex();
10037
10038 if (parseToken(lltok::colon, "expected ':' here"))
10039 return true;
10040 uint64_t BlockCount;
10041 if (parseUInt64(BlockCount))
10042 return true;
10043 if (Index)
10044 Index->setBlockCount(BlockCount);
10045 return false;
10046}
10047
10048/// parseGVEntry
10049/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10050/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10051/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10052bool LLParser::parseGVEntry(unsigned ID) {
10053 assert(Lex.getKind() == lltok::kw_gv);
10054 Lex.Lex();
10055
10056 if (parseToken(lltok::colon, "expected ':' here") ||
10057 parseToken(lltok::lparen, "expected '(' here"))
10058 return true;
10059
10060 LocTy Loc = Lex.getLoc();
10061 std::string Name;
10063 switch (Lex.getKind()) {
10064 case lltok::kw_name:
10065 Lex.Lex();
10066 if (parseToken(lltok::colon, "expected ':' here") ||
10067 parseStringConstant(Name))
10068 return true;
10069 // Can't create GUID/ValueInfo until we have the linkage.
10070 break;
10071 case lltok::kw_guid:
10072 Lex.Lex();
10073 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10074 return true;
10075 break;
10076 default:
10077 return error(Lex.getLoc(), "expected name or guid tag");
10078 }
10079
10080 if (!EatIfPresent(lltok::comma)) {
10081 // No summaries. Wrap up.
10082 if (parseToken(lltok::rparen, "expected ')' here"))
10083 return true;
10084 // This was created for a call to an external or indirect target.
10085 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10086 // created for indirect calls with VP. A Name with no GUID came from
10087 // an external definition. We pass ExternalLinkage since that is only
10088 // used when the GUID must be computed from Name, and in that case
10089 // the symbol must have external linkage.
10090 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10091 nullptr, Loc);
10092 }
10093
10094 // Have a list of summaries
10095 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10096 parseToken(lltok::colon, "expected ':' here") ||
10097 parseToken(lltok::lparen, "expected '(' here"))
10098 return true;
10099 do {
10100 switch (Lex.getKind()) {
10101 case lltok::kw_function:
10102 if (parseFunctionSummary(Name, GUID, ID))
10103 return true;
10104 break;
10105 case lltok::kw_variable:
10106 if (parseVariableSummary(Name, GUID, ID))
10107 return true;
10108 break;
10109 case lltok::kw_alias:
10110 if (parseAliasSummary(Name, GUID, ID))
10111 return true;
10112 break;
10113 default:
10114 return error(Lex.getLoc(), "expected summary type");
10115 }
10116 } while (EatIfPresent(lltok::comma));
10117
10118 if (parseToken(lltok::rparen, "expected ')' here") ||
10119 parseToken(lltok::rparen, "expected ')' here"))
10120 return true;
10121
10122 return false;
10123}
10124
10125/// FunctionSummary
10126/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10127/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10128/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10129/// [',' OptionalRefs]? ')'
10130bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10131 unsigned ID) {
10132 LocTy Loc = Lex.getLoc();
10133 assert(Lex.getKind() == lltok::kw_function);
10134 Lex.Lex();
10135
10136 StringRef ModulePath;
10137 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10139 /*NotEligibleToImport=*/false,
10140 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10141 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10142 unsigned InstCount;
10144 FunctionSummary::TypeIdInfo TypeIdInfo;
10145 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10147 std::vector<CallsiteInfo> Callsites;
10148 std::vector<AllocInfo> Allocs;
10149 // Default is all-zeros (conservative values).
10150 FunctionSummary::FFlags FFlags = {};
10151 if (parseToken(lltok::colon, "expected ':' here") ||
10152 parseToken(lltok::lparen, "expected '(' here") ||
10153 parseModuleReference(ModulePath) ||
10154 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10155 parseToken(lltok::comma, "expected ',' here") ||
10156 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10157 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10158 return true;
10159
10160 // parse optional fields
10161 while (EatIfPresent(lltok::comma)) {
10162 switch (Lex.getKind()) {
10164 if (parseOptionalFFlags(FFlags))
10165 return true;
10166 break;
10167 case lltok::kw_calls:
10168 if (parseOptionalCalls(Calls))
10169 return true;
10170 break;
10172 if (parseOptionalTypeIdInfo(TypeIdInfo))
10173 return true;
10174 break;
10175 case lltok::kw_refs:
10176 if (parseOptionalRefs(Refs))
10177 return true;
10178 break;
10179 case lltok::kw_params:
10180 if (parseOptionalParamAccesses(ParamAccesses))
10181 return true;
10182 break;
10183 case lltok::kw_allocs:
10184 if (parseOptionalAllocs(Allocs))
10185 return true;
10186 break;
10188 if (parseOptionalCallsites(Callsites))
10189 return true;
10190 break;
10191 default:
10192 return error(Lex.getLoc(), "expected optional function summary field");
10193 }
10194 }
10195
10196 if (parseToken(lltok::rparen, "expected ')' here"))
10197 return true;
10198
10199 auto FS = std::make_unique<FunctionSummary>(
10200 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10201 std::move(TypeIdInfo.TypeTests),
10202 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10203 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10204 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10205 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10206 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10207
10208 FS->setModulePath(ModulePath);
10209
10210 return addGlobalValueToIndex(Name, GUID,
10212 std::move(FS), Loc);
10213}
10214
10215/// VariableSummary
10216/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10217/// [',' OptionalRefs]? ')'
10218bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10219 unsigned ID) {
10220 LocTy Loc = Lex.getLoc();
10221 assert(Lex.getKind() == lltok::kw_variable);
10222 Lex.Lex();
10223
10224 StringRef ModulePath;
10225 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10227 /*NotEligibleToImport=*/false,
10228 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10229 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10230 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10231 /* WriteOnly */ false,
10232 /* Constant */ false,
10235 VTableFuncList VTableFuncs;
10236 if (parseToken(lltok::colon, "expected ':' here") ||
10237 parseToken(lltok::lparen, "expected '(' here") ||
10238 parseModuleReference(ModulePath) ||
10239 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10240 parseToken(lltok::comma, "expected ',' here") ||
10241 parseGVarFlags(GVarFlags))
10242 return true;
10243
10244 // parse optional fields
10245 while (EatIfPresent(lltok::comma)) {
10246 switch (Lex.getKind()) {
10248 if (parseOptionalVTableFuncs(VTableFuncs))
10249 return true;
10250 break;
10251 case lltok::kw_refs:
10252 if (parseOptionalRefs(Refs))
10253 return true;
10254 break;
10255 default:
10256 return error(Lex.getLoc(), "expected optional variable summary field");
10257 }
10258 }
10259
10260 if (parseToken(lltok::rparen, "expected ')' here"))
10261 return true;
10262
10263 auto GS =
10264 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10265
10266 GS->setModulePath(ModulePath);
10267 GS->setVTableFuncs(std::move(VTableFuncs));
10268
10269 return addGlobalValueToIndex(Name, GUID,
10271 std::move(GS), Loc);
10272}
10273
10274/// AliasSummary
10275/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10276/// 'aliasee' ':' GVReference ')'
10277bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10278 unsigned ID) {
10279 assert(Lex.getKind() == lltok::kw_alias);
10280 LocTy Loc = Lex.getLoc();
10281 Lex.Lex();
10282
10283 StringRef ModulePath;
10284 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10286 /*NotEligibleToImport=*/false,
10287 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10288 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10289 if (parseToken(lltok::colon, "expected ':' here") ||
10290 parseToken(lltok::lparen, "expected '(' here") ||
10291 parseModuleReference(ModulePath) ||
10292 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10293 parseToken(lltok::comma, "expected ',' here") ||
10294 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10295 parseToken(lltok::colon, "expected ':' here"))
10296 return true;
10297
10298 ValueInfo AliaseeVI;
10299 unsigned GVId;
10300 auto AS = std::make_unique<AliasSummary>(GVFlags);
10301 AS->setModulePath(ModulePath);
10302
10303 if (!EatIfPresent(lltok::kw_null)) {
10304 if (parseGVReference(AliaseeVI, GVId))
10305 return true;
10306
10307 // Record forward reference if the aliasee is not parsed yet.
10308 if (AliaseeVI.getRef() == FwdVIRef) {
10309 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10310 } else {
10311 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10312 assert(Summary && "Aliasee must be a definition");
10313 AS->setAliasee(AliaseeVI, Summary);
10314 }
10315 }
10316
10317 if (parseToken(lltok::rparen, "expected ')' here"))
10318 return true;
10319
10320 return addGlobalValueToIndex(Name, GUID,
10322 std::move(AS), Loc);
10323}
10324
10325/// Flag
10326/// ::= [0|1]
10327bool LLParser::parseFlag(unsigned &Val) {
10328 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10329 return tokError("expected integer");
10330 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10331 Lex.Lex();
10332 return false;
10333}
10334
10335/// OptionalFFlags
10336/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10337/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10338/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10339/// [',' 'noInline' ':' Flag]? ')'
10340/// [',' 'alwaysInline' ':' Flag]? ')'
10341/// [',' 'noUnwind' ':' Flag]? ')'
10342/// [',' 'mayThrow' ':' Flag]? ')'
10343/// [',' 'hasUnknownCall' ':' Flag]? ')'
10344/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10345
10346bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10347 assert(Lex.getKind() == lltok::kw_funcFlags);
10348 Lex.Lex();
10349
10350 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10351 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10352 return true;
10353
10354 do {
10355 unsigned Val = 0;
10356 switch (Lex.getKind()) {
10357 case lltok::kw_readNone:
10358 Lex.Lex();
10359 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10360 return true;
10361 FFlags.ReadNone = Val;
10362 break;
10363 case lltok::kw_readOnly:
10364 Lex.Lex();
10365 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10366 return true;
10367 FFlags.ReadOnly = Val;
10368 break;
10370 Lex.Lex();
10371 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10372 return true;
10373 FFlags.NoRecurse = Val;
10374 break;
10376 Lex.Lex();
10377 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10378 return true;
10379 FFlags.ReturnDoesNotAlias = Val;
10380 break;
10381 case lltok::kw_noInline:
10382 Lex.Lex();
10383 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10384 return true;
10385 FFlags.NoInline = Val;
10386 break;
10388 Lex.Lex();
10389 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10390 return true;
10391 FFlags.AlwaysInline = Val;
10392 break;
10393 case lltok::kw_noUnwind:
10394 Lex.Lex();
10395 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10396 return true;
10397 FFlags.NoUnwind = Val;
10398 break;
10399 case lltok::kw_mayThrow:
10400 Lex.Lex();
10401 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10402 return true;
10403 FFlags.MayThrow = Val;
10404 break;
10406 Lex.Lex();
10407 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10408 return true;
10409 FFlags.HasUnknownCall = Val;
10410 break;
10412 Lex.Lex();
10413 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10414 return true;
10415 FFlags.MustBeUnreachable = Val;
10416 break;
10417 default:
10418 return error(Lex.getLoc(), "expected function flag type");
10419 }
10420 } while (EatIfPresent(lltok::comma));
10421
10422 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10423 return true;
10424
10425 return false;
10426}
10427
10428/// OptionalCalls
10429/// := 'calls' ':' '(' Call [',' Call]* ')'
10430/// Call ::= '(' 'callee' ':' GVReference
10431/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10432/// [ ',' 'tail' ]? ')'
10433bool LLParser::parseOptionalCalls(
10434 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10435 assert(Lex.getKind() == lltok::kw_calls);
10436 Lex.Lex();
10437
10438 if (parseToken(lltok::colon, "expected ':' in calls") ||
10439 parseToken(lltok::lparen, "expected '(' in calls"))
10440 return true;
10441
10442 IdToIndexMapType IdToIndexMap;
10443 // parse each call edge
10444 do {
10445 ValueInfo VI;
10446 if (parseToken(lltok::lparen, "expected '(' in call") ||
10447 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10448 parseToken(lltok::colon, "expected ':'"))
10449 return true;
10450
10451 LocTy Loc = Lex.getLoc();
10452 unsigned GVId;
10453 if (parseGVReference(VI, GVId))
10454 return true;
10455
10457 unsigned RelBF = 0;
10458 unsigned HasTailCall = false;
10459
10460 // parse optional fields
10461 while (EatIfPresent(lltok::comma)) {
10462 switch (Lex.getKind()) {
10463 case lltok::kw_hotness:
10464 Lex.Lex();
10465 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10466 return true;
10467 break;
10468 // Deprecated, keep in order to support old files.
10469 case lltok::kw_relbf:
10470 Lex.Lex();
10471 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10472 return true;
10473 break;
10474 case lltok::kw_tail:
10475 Lex.Lex();
10476 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10477 return true;
10478 break;
10479 default:
10480 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10481 }
10482 }
10483 // Keep track of the Call array index needing a forward reference.
10484 // We will save the location of the ValueInfo needing an update, but
10485 // can only do so once the std::vector is finalized.
10486 if (VI.getRef() == FwdVIRef)
10487 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10488 Calls.push_back(
10489 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10490
10491 if (parseToken(lltok::rparen, "expected ')' in call"))
10492 return true;
10493 } while (EatIfPresent(lltok::comma));
10494
10495 // Now that the Calls vector is finalized, it is safe to save the locations
10496 // of any forward GV references that need updating later.
10497 for (auto I : IdToIndexMap) {
10498 auto &Infos = ForwardRefValueInfos[I.first];
10499 for (auto P : I.second) {
10500 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10501 "Forward referenced ValueInfo expected to be empty");
10502 Infos.emplace_back(&Calls[P.first].first, P.second);
10503 }
10504 }
10505
10506 if (parseToken(lltok::rparen, "expected ')' in calls"))
10507 return true;
10508
10509 return false;
10510}
10511
10512/// Hotness
10513/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10514bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10515 switch (Lex.getKind()) {
10516 case lltok::kw_unknown:
10518 break;
10519 case lltok::kw_cold:
10521 break;
10522 case lltok::kw_none:
10524 break;
10525 case lltok::kw_hot:
10527 break;
10528 case lltok::kw_critical:
10530 break;
10531 default:
10532 return error(Lex.getLoc(), "invalid call edge hotness");
10533 }
10534 Lex.Lex();
10535 return false;
10536}
10537
10538/// OptionalVTableFuncs
10539/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10540/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10541bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10542 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10543 Lex.Lex();
10544
10545 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10546 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10547 return true;
10548
10549 IdToIndexMapType IdToIndexMap;
10550 // parse each virtual function pair
10551 do {
10552 ValueInfo VI;
10553 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10554 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10555 parseToken(lltok::colon, "expected ':'"))
10556 return true;
10557
10558 LocTy Loc = Lex.getLoc();
10559 unsigned GVId;
10560 if (parseGVReference(VI, GVId))
10561 return true;
10562
10563 uint64_t Offset;
10564 if (parseToken(lltok::comma, "expected comma") ||
10565 parseToken(lltok::kw_offset, "expected offset") ||
10566 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10567 return true;
10568
10569 // Keep track of the VTableFuncs array index needing a forward reference.
10570 // We will save the location of the ValueInfo needing an update, but
10571 // can only do so once the std::vector is finalized.
10572 if (VI == EmptyVI)
10573 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10574 VTableFuncs.push_back({VI, Offset});
10575
10576 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10577 return true;
10578 } while (EatIfPresent(lltok::comma));
10579
10580 // Now that the VTableFuncs vector is finalized, it is safe to save the
10581 // locations of any forward GV references that need updating later.
10582 for (auto I : IdToIndexMap) {
10583 auto &Infos = ForwardRefValueInfos[I.first];
10584 for (auto P : I.second) {
10585 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10586 "Forward referenced ValueInfo expected to be empty");
10587 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10588 }
10589 }
10590
10591 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10592 return true;
10593
10594 return false;
10595}
10596
10597/// ParamNo := 'param' ':' UInt64
10598bool LLParser::parseParamNo(uint64_t &ParamNo) {
10599 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10600 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10601 return true;
10602 return false;
10603}
10604
10605/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10606bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10607 APSInt Lower;
10608 APSInt Upper;
10609 auto ParseAPSInt = [&](APSInt &Val) {
10610 if (Lex.getKind() != lltok::APSInt)
10611 return tokError("expected integer");
10612 Val = Lex.getAPSIntVal();
10613 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10614 Val.setIsSigned(true);
10615 Lex.Lex();
10616 return false;
10617 };
10618 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10619 parseToken(lltok::colon, "expected ':' here") ||
10620 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10621 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10622 parseToken(lltok::rsquare, "expected ']' here"))
10623 return true;
10624
10625 ++Upper;
10626 Range =
10627 (Lower == Upper && !Lower.isMaxValue())
10628 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10629 : ConstantRange(Lower, Upper);
10630
10631 return false;
10632}
10633
10634/// ParamAccessCall
10635/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10636bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10637 IdLocListType &IdLocList) {
10638 if (parseToken(lltok::lparen, "expected '(' here") ||
10639 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10640 parseToken(lltok::colon, "expected ':' here"))
10641 return true;
10642
10643 unsigned GVId;
10644 ValueInfo VI;
10645 LocTy Loc = Lex.getLoc();
10646 if (parseGVReference(VI, GVId))
10647 return true;
10648
10649 Call.Callee = VI;
10650 IdLocList.emplace_back(GVId, Loc);
10651
10652 if (parseToken(lltok::comma, "expected ',' here") ||
10653 parseParamNo(Call.ParamNo) ||
10654 parseToken(lltok::comma, "expected ',' here") ||
10655 parseParamAccessOffset(Call.Offsets))
10656 return true;
10657
10658 if (parseToken(lltok::rparen, "expected ')' here"))
10659 return true;
10660
10661 return false;
10662}
10663
10664/// ParamAccess
10665/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10666/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10667bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10668 IdLocListType &IdLocList) {
10669 if (parseToken(lltok::lparen, "expected '(' here") ||
10670 parseParamNo(Param.ParamNo) ||
10671 parseToken(lltok::comma, "expected ',' here") ||
10672 parseParamAccessOffset(Param.Use))
10673 return true;
10674
10675 if (EatIfPresent(lltok::comma)) {
10676 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10677 parseToken(lltok::colon, "expected ':' here") ||
10678 parseToken(lltok::lparen, "expected '(' here"))
10679 return true;
10680 do {
10681 FunctionSummary::ParamAccess::Call Call;
10682 if (parseParamAccessCall(Call, IdLocList))
10683 return true;
10684 Param.Calls.push_back(Call);
10685 } while (EatIfPresent(lltok::comma));
10686
10687 if (parseToken(lltok::rparen, "expected ')' here"))
10688 return true;
10689 }
10690
10691 if (parseToken(lltok::rparen, "expected ')' here"))
10692 return true;
10693
10694 return false;
10695}
10696
10697/// OptionalParamAccesses
10698/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10699bool LLParser::parseOptionalParamAccesses(
10700 std::vector<FunctionSummary::ParamAccess> &Params) {
10701 assert(Lex.getKind() == lltok::kw_params);
10702 Lex.Lex();
10703
10704 if (parseToken(lltok::colon, "expected ':' here") ||
10705 parseToken(lltok::lparen, "expected '(' here"))
10706 return true;
10707
10708 IdLocListType VContexts;
10709 size_t CallsNum = 0;
10710 do {
10711 FunctionSummary::ParamAccess ParamAccess;
10712 if (parseParamAccess(ParamAccess, VContexts))
10713 return true;
10714 CallsNum += ParamAccess.Calls.size();
10715 assert(VContexts.size() == CallsNum);
10716 (void)CallsNum;
10717 Params.emplace_back(std::move(ParamAccess));
10718 } while (EatIfPresent(lltok::comma));
10719
10720 if (parseToken(lltok::rparen, "expected ')' here"))
10721 return true;
10722
10723 // Now that the Params is finalized, it is safe to save the locations
10724 // of any forward GV references that need updating later.
10725 IdLocListType::const_iterator ItContext = VContexts.begin();
10726 for (auto &PA : Params) {
10727 for (auto &C : PA.Calls) {
10728 if (C.Callee.getRef() == FwdVIRef)
10729 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10730 ItContext->second);
10731 ++ItContext;
10732 }
10733 }
10734 assert(ItContext == VContexts.end());
10735
10736 return false;
10737}
10738
10739/// OptionalRefs
10740/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10741bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10742 assert(Lex.getKind() == lltok::kw_refs);
10743 Lex.Lex();
10744
10745 if (parseToken(lltok::colon, "expected ':' in refs") ||
10746 parseToken(lltok::lparen, "expected '(' in refs"))
10747 return true;
10748
10749 struct ValueContext {
10750 ValueInfo VI;
10751 unsigned GVId;
10752 LocTy Loc;
10753 };
10754 std::vector<ValueContext> VContexts;
10755 // parse each ref edge
10756 do {
10757 ValueContext VC;
10758 VC.Loc = Lex.getLoc();
10759 if (parseGVReference(VC.VI, VC.GVId))
10760 return true;
10761 VContexts.push_back(VC);
10762 } while (EatIfPresent(lltok::comma));
10763
10764 // Sort value contexts so that ones with writeonly
10765 // and readonly ValueInfo are at the end of VContexts vector.
10766 // See FunctionSummary::specialRefCounts()
10767 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10768 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10769 });
10770
10771 IdToIndexMapType IdToIndexMap;
10772 for (auto &VC : VContexts) {
10773 // Keep track of the Refs array index needing a forward reference.
10774 // We will save the location of the ValueInfo needing an update, but
10775 // can only do so once the std::vector is finalized.
10776 if (VC.VI.getRef() == FwdVIRef)
10777 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10778 Refs.push_back(VC.VI);
10779 }
10780
10781 // Now that the Refs vector is finalized, it is safe to save the locations
10782 // of any forward GV references that need updating later.
10783 for (auto I : IdToIndexMap) {
10784 auto &Infos = ForwardRefValueInfos[I.first];
10785 for (auto P : I.second) {
10786 assert(Refs[P.first].getRef() == FwdVIRef &&
10787 "Forward referenced ValueInfo expected to be empty");
10788 Infos.emplace_back(&Refs[P.first], P.second);
10789 }
10790 }
10791
10792 if (parseToken(lltok::rparen, "expected ')' in refs"))
10793 return true;
10794
10795 return false;
10796}
10797
10798/// OptionalTypeIdInfo
10799/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10800/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10801/// [',' TypeCheckedLoadConstVCalls]? ')'
10802bool LLParser::parseOptionalTypeIdInfo(
10803 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10804 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10805 Lex.Lex();
10806
10807 if (parseToken(lltok::colon, "expected ':' here") ||
10808 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10809 return true;
10810
10811 do {
10812 switch (Lex.getKind()) {
10814 if (parseTypeTests(TypeIdInfo.TypeTests))
10815 return true;
10816 break;
10818 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10819 TypeIdInfo.TypeTestAssumeVCalls))
10820 return true;
10821 break;
10823 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10824 TypeIdInfo.TypeCheckedLoadVCalls))
10825 return true;
10826 break;
10828 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10829 TypeIdInfo.TypeTestAssumeConstVCalls))
10830 return true;
10831 break;
10833 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10834 TypeIdInfo.TypeCheckedLoadConstVCalls))
10835 return true;
10836 break;
10837 default:
10838 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10839 }
10840 } while (EatIfPresent(lltok::comma));
10841
10842 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10843 return true;
10844
10845 return false;
10846}
10847
10848/// TypeTests
10849/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10850/// [',' (SummaryID | UInt64)]* ')'
10851bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10852 assert(Lex.getKind() == lltok::kw_typeTests);
10853 Lex.Lex();
10854
10855 if (parseToken(lltok::colon, "expected ':' here") ||
10856 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10857 return true;
10858
10859 IdToIndexMapType IdToIndexMap;
10860 do {
10862 if (Lex.getKind() == lltok::SummaryID) {
10863 unsigned ID = Lex.getUIntVal();
10864 LocTy Loc = Lex.getLoc();
10865 // Keep track of the TypeTests array index needing a forward reference.
10866 // We will save the location of the GUID needing an update, but
10867 // can only do so once the std::vector is finalized.
10868 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10869 Lex.Lex();
10870 } else if (parseUInt64(GUID))
10871 return true;
10872 TypeTests.push_back(GUID);
10873 } while (EatIfPresent(lltok::comma));
10874
10875 // Now that the TypeTests vector is finalized, it is safe to save the
10876 // locations of any forward GV references that need updating later.
10877 for (auto I : IdToIndexMap) {
10878 auto &Ids = ForwardRefTypeIds[I.first];
10879 for (auto P : I.second) {
10880 assert(TypeTests[P.first] == 0 &&
10881 "Forward referenced type id GUID expected to be 0");
10882 Ids.emplace_back(&TypeTests[P.first], P.second);
10883 }
10884 }
10885
10886 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10887 return true;
10888
10889 return false;
10890}
10891
10892/// VFuncIdList
10893/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10894bool LLParser::parseVFuncIdList(
10895 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10896 assert(Lex.getKind() == Kind);
10897 Lex.Lex();
10898
10899 if (parseToken(lltok::colon, "expected ':' here") ||
10900 parseToken(lltok::lparen, "expected '(' here"))
10901 return true;
10902
10903 IdToIndexMapType IdToIndexMap;
10904 do {
10905 FunctionSummary::VFuncId VFuncId;
10906 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10907 return true;
10908 VFuncIdList.push_back(VFuncId);
10909 } while (EatIfPresent(lltok::comma));
10910
10911 if (parseToken(lltok::rparen, "expected ')' here"))
10912 return true;
10913
10914 // Now that the VFuncIdList vector is finalized, it is safe to save the
10915 // locations of any forward GV references that need updating later.
10916 for (auto I : IdToIndexMap) {
10917 auto &Ids = ForwardRefTypeIds[I.first];
10918 for (auto P : I.second) {
10919 assert(VFuncIdList[P.first].GUID == 0 &&
10920 "Forward referenced type id GUID expected to be 0");
10921 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10922 }
10923 }
10924
10925 return false;
10926}
10927
10928/// ConstVCallList
10929/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10930bool LLParser::parseConstVCallList(
10931 lltok::Kind Kind,
10932 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10933 assert(Lex.getKind() == Kind);
10934 Lex.Lex();
10935
10936 if (parseToken(lltok::colon, "expected ':' here") ||
10937 parseToken(lltok::lparen, "expected '(' here"))
10938 return true;
10939
10940 IdToIndexMapType IdToIndexMap;
10941 do {
10942 FunctionSummary::ConstVCall ConstVCall;
10943 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10944 return true;
10945 ConstVCallList.push_back(ConstVCall);
10946 } while (EatIfPresent(lltok::comma));
10947
10948 if (parseToken(lltok::rparen, "expected ')' here"))
10949 return true;
10950
10951 // Now that the ConstVCallList vector is finalized, it is safe to save the
10952 // locations of any forward GV references that need updating later.
10953 for (auto I : IdToIndexMap) {
10954 auto &Ids = ForwardRefTypeIds[I.first];
10955 for (auto P : I.second) {
10956 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10957 "Forward referenced type id GUID expected to be 0");
10958 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10959 }
10960 }
10961
10962 return false;
10963}
10964
10965/// ConstVCall
10966/// ::= '(' VFuncId ',' Args ')'
10967bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10968 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10969 if (parseToken(lltok::lparen, "expected '(' here") ||
10970 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10971 return true;
10972
10973 if (EatIfPresent(lltok::comma))
10974 if (parseArgs(ConstVCall.Args))
10975 return true;
10976
10977 if (parseToken(lltok::rparen, "expected ')' here"))
10978 return true;
10979
10980 return false;
10981}
10982
10983/// VFuncId
10984/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10985/// 'offset' ':' UInt64 ')'
10986bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10987 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10988 assert(Lex.getKind() == lltok::kw_vFuncId);
10989 Lex.Lex();
10990
10991 if (parseToken(lltok::colon, "expected ':' here") ||
10992 parseToken(lltok::lparen, "expected '(' here"))
10993 return true;
10994
10995 if (Lex.getKind() == lltok::SummaryID) {
10996 VFuncId.GUID = 0;
10997 unsigned ID = Lex.getUIntVal();
10998 LocTy Loc = Lex.getLoc();
10999 // Keep track of the array index needing a forward reference.
11000 // We will save the location of the GUID needing an update, but
11001 // can only do so once the caller's std::vector is finalized.
11002 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11003 Lex.Lex();
11004 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11005 parseToken(lltok::colon, "expected ':' here") ||
11006 parseUInt64(VFuncId.GUID))
11007 return true;
11008
11009 if (parseToken(lltok::comma, "expected ',' here") ||
11010 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11011 parseToken(lltok::colon, "expected ':' here") ||
11012 parseUInt64(VFuncId.Offset) ||
11013 parseToken(lltok::rparen, "expected ')' here"))
11014 return true;
11015
11016 return false;
11017}
11018
11019/// GVFlags
11020/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11021/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11022/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11023/// 'canAutoHide' ':' Flag ',' ')'
11024bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11025 assert(Lex.getKind() == lltok::kw_flags);
11026 Lex.Lex();
11027
11028 if (parseToken(lltok::colon, "expected ':' here") ||
11029 parseToken(lltok::lparen, "expected '(' here"))
11030 return true;
11031
11032 do {
11033 unsigned Flag = 0;
11034 switch (Lex.getKind()) {
11035 case lltok::kw_linkage:
11036 Lex.Lex();
11037 if (parseToken(lltok::colon, "expected ':'"))
11038 return true;
11039 bool HasLinkage;
11040 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11041 assert(HasLinkage && "Linkage not optional in summary entry");
11042 Lex.Lex();
11043 break;
11045 Lex.Lex();
11046 if (parseToken(lltok::colon, "expected ':'"))
11047 return true;
11048 parseOptionalVisibility(Flag);
11049 GVFlags.Visibility = Flag;
11050 break;
11052 Lex.Lex();
11053 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11054 return true;
11055 GVFlags.NotEligibleToImport = Flag;
11056 break;
11057 case lltok::kw_live:
11058 Lex.Lex();
11059 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11060 return true;
11061 GVFlags.Live = Flag;
11062 break;
11063 case lltok::kw_dsoLocal:
11064 Lex.Lex();
11065 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11066 return true;
11067 GVFlags.DSOLocal = Flag;
11068 break;
11070 Lex.Lex();
11071 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11072 return true;
11073 GVFlags.CanAutoHide = Flag;
11074 break;
11076 Lex.Lex();
11077 if (parseToken(lltok::colon, "expected ':'"))
11078 return true;
11080 if (parseOptionalImportType(Lex.getKind(), IK))
11081 return true;
11082 GVFlags.ImportType = static_cast<unsigned>(IK);
11083 Lex.Lex();
11084 break;
11086 Lex.Lex();
11087 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11088 return true;
11089 GVFlags.NoRenameOnPromotion = Flag;
11090 break;
11091 default:
11092 return error(Lex.getLoc(), "expected gv flag type");
11093 }
11094 } while (EatIfPresent(lltok::comma));
11095
11096 if (parseToken(lltok::rparen, "expected ')' here"))
11097 return true;
11098
11099 return false;
11100}
11101
11102/// GVarFlags
11103/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11104/// ',' 'writeonly' ':' Flag
11105/// ',' 'constant' ':' Flag ')'
11106bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11107 assert(Lex.getKind() == lltok::kw_varFlags);
11108 Lex.Lex();
11109
11110 if (parseToken(lltok::colon, "expected ':' here") ||
11111 parseToken(lltok::lparen, "expected '(' here"))
11112 return true;
11113
11114 auto ParseRest = [this](unsigned int &Val) {
11115 Lex.Lex();
11116 if (parseToken(lltok::colon, "expected ':'"))
11117 return true;
11118 return parseFlag(Val);
11119 };
11120
11121 do {
11122 unsigned Flag = 0;
11123 switch (Lex.getKind()) {
11124 case lltok::kw_readonly:
11125 if (ParseRest(Flag))
11126 return true;
11127 GVarFlags.MaybeReadOnly = Flag;
11128 break;
11129 case lltok::kw_writeonly:
11130 if (ParseRest(Flag))
11131 return true;
11132 GVarFlags.MaybeWriteOnly = Flag;
11133 break;
11134 case lltok::kw_constant:
11135 if (ParseRest(Flag))
11136 return true;
11137 GVarFlags.Constant = Flag;
11138 break;
11140 if (ParseRest(Flag))
11141 return true;
11142 GVarFlags.VCallVisibility = Flag;
11143 break;
11144 default:
11145 return error(Lex.getLoc(), "expected gvar flag type");
11146 }
11147 } while (EatIfPresent(lltok::comma));
11148 return parseToken(lltok::rparen, "expected ')' here");
11149}
11150
11151/// ModuleReference
11152/// ::= 'module' ':' UInt
11153bool LLParser::parseModuleReference(StringRef &ModulePath) {
11154 // parse module id.
11155 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11156 parseToken(lltok::colon, "expected ':' here") ||
11157 parseToken(lltok::SummaryID, "expected module ID"))
11158 return true;
11159
11160 unsigned ModuleID = Lex.getUIntVal();
11161 auto I = ModuleIdMap.find(ModuleID);
11162 // We should have already parsed all module IDs
11163 assert(I != ModuleIdMap.end());
11164 ModulePath = I->second;
11165 return false;
11166}
11167
11168/// GVReference
11169/// ::= SummaryID
11170bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11171 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11172 if (!ReadOnly)
11173 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11174 if (parseToken(lltok::SummaryID, "expected GV ID"))
11175 return true;
11176
11177 GVId = Lex.getUIntVal();
11178 // Check if we already have a VI for this GV
11179 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11180 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11181 VI = NumberedValueInfos[GVId];
11182 } else
11183 // We will create a forward reference to the stored location.
11184 VI = ValueInfo(false, FwdVIRef);
11185
11186 if (ReadOnly)
11187 VI.setReadOnly();
11188 if (WriteOnly)
11189 VI.setWriteOnly();
11190 return false;
11191}
11192
11193/// OptionalAllocs
11194/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11195/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11196/// ',' MemProfs ')'
11197/// Version ::= UInt32
11198bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11199 assert(Lex.getKind() == lltok::kw_allocs);
11200 Lex.Lex();
11201
11202 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11203 parseToken(lltok::lparen, "expected '(' in allocs"))
11204 return true;
11205
11206 // parse each alloc
11207 do {
11208 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11209 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11210 parseToken(lltok::colon, "expected ':'") ||
11211 parseToken(lltok::lparen, "expected '(' in versions"))
11212 return true;
11213
11214 SmallVector<uint8_t> Versions;
11215 do {
11216 uint8_t V = 0;
11217 if (parseAllocType(V))
11218 return true;
11219 Versions.push_back(V);
11220 } while (EatIfPresent(lltok::comma));
11221
11222 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11223 parseToken(lltok::comma, "expected ',' in alloc"))
11224 return true;
11225
11226 std::vector<MIBInfo> MIBs;
11227 if (parseMemProfs(MIBs))
11228 return true;
11229
11230 Allocs.push_back({Versions, MIBs});
11231
11232 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11233 return true;
11234 } while (EatIfPresent(lltok::comma));
11235
11236 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11237 return true;
11238
11239 return false;
11240}
11241
11242/// MemProfs
11243/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11244/// MemProf ::= '(' 'type' ':' AllocType
11245/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11246/// StackId ::= UInt64
11247bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11248 assert(Lex.getKind() == lltok::kw_memProf);
11249 Lex.Lex();
11250
11251 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11252 parseToken(lltok::lparen, "expected '(' in memprof"))
11253 return true;
11254
11255 // parse each MIB
11256 do {
11257 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11258 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11259 parseToken(lltok::colon, "expected ':'"))
11260 return true;
11261
11262 uint8_t AllocType;
11263 if (parseAllocType(AllocType))
11264 return true;
11265
11266 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11267 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11268 parseToken(lltok::colon, "expected ':'") ||
11269 parseToken(lltok::lparen, "expected '(' in stackIds"))
11270 return true;
11271
11272 SmallVector<unsigned> StackIdIndices;
11273 // Combined index alloc records may not have a stack id list.
11274 if (Lex.getKind() != lltok::rparen) {
11275 do {
11276 uint64_t StackId = 0;
11277 if (parseUInt64(StackId))
11278 return true;
11279 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11280 } while (EatIfPresent(lltok::comma));
11281 }
11282
11283 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11284 return true;
11285
11286 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11287
11288 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11289 return true;
11290 } while (EatIfPresent(lltok::comma));
11291
11292 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11293 return true;
11294
11295 return false;
11296}
11297
11298/// AllocType
11299/// := ('none'|'notcold'|'cold'|'hot')
11300bool LLParser::parseAllocType(uint8_t &AllocType) {
11301 switch (Lex.getKind()) {
11302 case lltok::kw_none:
11304 break;
11305 case lltok::kw_notcold:
11307 break;
11308 case lltok::kw_cold:
11310 break;
11311 case lltok::kw_hot:
11312 AllocType = (uint8_t)AllocationType::Hot;
11313 break;
11314 default:
11315 return error(Lex.getLoc(), "invalid alloc type");
11316 }
11317 Lex.Lex();
11318 return false;
11319}
11320
11321/// OptionalCallsites
11322/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11323/// Callsite ::= '(' 'callee' ':' GVReference
11324/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11325/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11326/// Version ::= UInt32
11327/// StackId ::= UInt64
11328bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11329 assert(Lex.getKind() == lltok::kw_callsites);
11330 Lex.Lex();
11331
11332 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11333 parseToken(lltok::lparen, "expected '(' in callsites"))
11334 return true;
11335
11336 IdToIndexMapType IdToIndexMap;
11337 // parse each callsite
11338 do {
11339 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11340 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11341 parseToken(lltok::colon, "expected ':'"))
11342 return true;
11343
11344 ValueInfo VI;
11345 unsigned GVId = 0;
11346 LocTy Loc = Lex.getLoc();
11347 if (!EatIfPresent(lltok::kw_null)) {
11348 if (parseGVReference(VI, GVId))
11349 return true;
11350 }
11351
11352 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11353 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11354 parseToken(lltok::colon, "expected ':'") ||
11355 parseToken(lltok::lparen, "expected '(' in clones"))
11356 return true;
11357
11358 SmallVector<unsigned> Clones;
11359 do {
11360 unsigned V = 0;
11361 if (parseUInt32(V))
11362 return true;
11363 Clones.push_back(V);
11364 } while (EatIfPresent(lltok::comma));
11365
11366 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11367 parseToken(lltok::comma, "expected ',' in callsite") ||
11368 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11369 parseToken(lltok::colon, "expected ':'") ||
11370 parseToken(lltok::lparen, "expected '(' in stackIds"))
11371 return true;
11372
11373 SmallVector<unsigned> StackIdIndices;
11374 // Synthesized callsite records will not have a stack id list.
11375 if (Lex.getKind() != lltok::rparen) {
11376 do {
11377 uint64_t StackId = 0;
11378 if (parseUInt64(StackId))
11379 return true;
11380 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11381 } while (EatIfPresent(lltok::comma));
11382 }
11383
11384 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11385 return true;
11386
11387 // Keep track of the Callsites array index needing a forward reference.
11388 // We will save the location of the ValueInfo needing an update, but
11389 // can only do so once the SmallVector is finalized.
11390 if (VI.getRef() == FwdVIRef)
11391 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11392 Callsites.push_back({VI, Clones, StackIdIndices});
11393
11394 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11395 return true;
11396 } while (EatIfPresent(lltok::comma));
11397
11398 // Now that the Callsites vector is finalized, it is safe to save the
11399 // locations of any forward GV references that need updating later.
11400 for (auto I : IdToIndexMap) {
11401 auto &Infos = ForwardRefValueInfos[I.first];
11402 for (auto P : I.second) {
11403 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11404 "Forward referenced ValueInfo expected to be empty");
11405 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11406 }
11407 }
11408
11409 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11410 return true;
11411
11412 return false;
11413}
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
This file contains the simple types necessary to represent the attributes associated with functions a...
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
static uint64_t align(uint64_t Size)
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:253
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 void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
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:152
#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:68
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
if(PassOpts->AAPipeline)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
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 & IEEEdouble()
Definition APFloat.h:297
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:291
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:360
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1244
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:119
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
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
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:831
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
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ 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:143
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ None
No attributes have been set.
Definition Attributes.h:126
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
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.
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:427
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:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
@ 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 CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
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:1592
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:1464
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, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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.
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
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)
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)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:252
unsigned size() const
Definition DenseMap.h:174
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:469
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:464
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:168
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:823
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1040
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1052
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
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:621
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:678
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:223
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:284
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:80
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:254
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:96
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:170
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:260
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:237
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:542
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:589
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:124
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:236
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:76
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:1075
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1575
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1535
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1524
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1544
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:224
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
Definition ModRef.h:279
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:110
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:942
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
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:479
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:685
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:769
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:604
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:506
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:980
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:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:289
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:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:283
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:251
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
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:326
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:319
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:273
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
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 UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
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:509
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
static constexpr uint64_t MaximumAlignment
Definition Value.h:798
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:552
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:107
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:318
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:599
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
Definition Dwarf.cpp:618
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:654
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:726
#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 IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
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 * > OverloadTys={})
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 isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
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:771
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:226
MacinfoRecordType
Definition Dwarf.h:821
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:827
@ 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:155
@ kw_riscv_vls_cc
Definition LLToken.h:191
@ kw_cxx_fast_tlscc
Definition LLToken.h:174
@ kw_extractvalue
Definition LLToken.h:377
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:512
@ DwarfLangDialect
Definition LLToken.h:515
@ kw_arm_apcscc
Definition LLToken.h:147
@ kw_inteldialect
Definition LLToken.h:129
@ kw_x86_stdcallcc
Definition LLToken.h:142
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:153
@ kw_provenance
Definition LLToken.h:225
@ kw_mustBeUnreachable
Definition LLToken.h:423
@ kw_internal
Definition LLToken.h:54
@ kw_target_mem
Definition LLToken.h:211
@ kw_no_sanitize_hwaddress
Definition LLToken.h:491
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:462
@ kw_canAutoHide
Definition LLToken.h:406
@ kw_alwaysInline
Definition LLToken.h:419
@ kw_insertelement
Definition LLToken.h:374
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:194
@ kw_fmaximumnum
Definition LLToken.h:296
@ kw_inaccessiblememonly
Definition LLToken.h:218
@ kw_amdgpu_gfx
Definition LLToken.h:185
@ kw_getelementptr
Definition LLToken.h:371
@ FloatHexLiteral
Definition LLToken.h:532
@ kw_m68k_rtdcc
Definition LLToken.h:188
@ kw_preserve_nonecc
Definition LLToken.h:169
@ kw_x86_fastcallcc
Definition LLToken.h:143
@ kw_visibility
Definition LLToken.h:402
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:193
@ kw_positivezero
Definition LLToken.h:231
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:465
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:442
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:151
@ kw_amdgpu_kernel
Definition LLToken.h:184
@ kw_uselistorder
Definition LLToken.h:390
@ kw_blockcount
Definition LLToken.h:400
@ kw_notEligibleToImport
Definition LLToken.h:403
@ 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:145
@ kw_ptx_device
Definition LLToken.h:159
@ kw_personality
Definition LLToken.h:346
@ DwarfEnumKind
Definition LLToken.h:526
@ kw_declaration
Definition LLToken.h:409
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:511
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:160
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:422
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:341
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:509
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:192
@ kw_unnamed_addr
Definition LLToken.h:67
@ NameTableKind
Definition LLToken.h:518
@ kw_inlineBits
Definition LLToken.h:460
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:217
@ kw_blockaddress
Definition LLToken.h:379
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:186
@ kw_landingpad
Definition LLToken.h:345
@ kw_aarch64_vector_pcs
Definition LLToken.h:150
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:441
@ FixedPointKind
Definition LLToken.h:519
@ kw_target_mem1
Definition LLToken.h:213
@ kw_ptx_kernel
Definition LLToken.h:158
@ kw_extractelement
Definition LLToken.h:373
@ kw_branchFunnel
Definition LLToken.h:466
@ kw_typeidCompatibleVTable
Definition LLToken.h:447
@ kw_vTableFuncs
Definition LLToken.h:433
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:440
@ kw_no_sanitize_address
Definition LLToken.h:488
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:219
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:494
@ DwarfSourceLangName
Definition LLToken.h:514
@ kw_noRenameOnPromotion
Definition LLToken.h:410
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:183
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:359
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:148
@ kw_read_provenance
Definition LLToken.h:226
@ kw_cleanuppad
Definition LLToken.h:362
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:467
@ kw_target_mem0
Definition LLToken.h:212
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:439
@ kw_preservesign
Definition LLToken.h:230
@ kw_attributes
Definition LLToken.h:197
@ kw_code_model
Definition LLToken.h:123
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:470
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:456
@ kw_nodeduplicate
Definition LLToken.h:261
@ kw_avr_signalcc
Definition LLToken.h:157
@ kw_exactmatch
Definition LLToken.h:259
@ kw_fminimumnum
Definition LLToken.h:297
@ kw_unreachable
Definition LLToken.h:357
@ kw_intel_ocl_bicc
Definition LLToken.h:140
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:417
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:407
@ kw_cleanupret
Definition LLToken.h:358
@ kw_shufflevector
Definition LLToken.h:375
@ kw_riscv_vector_cc
Definition LLToken.h:190
@ kw_avr_intrcc
Definition LLToken.h:156
@ kw_definition
Definition LLToken.h:408
@ kw_virtualConstProp
Definition LLToken.h:472
@ kw_vcall_visibility
Definition LLToken.h:461
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:210
@ kw_preserve_mostcc
Definition LLToken.h:167
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:149
@ kw_typeTestRes
Definition LLToken.h:449
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:437
@ kw_amdgpu_cs_chain
Definition LLToken.h:182
@ kw_dso_local_equivalent
Definition LLToken.h:380
@ kw_x86_64_sysvcc
Definition LLToken.h:162
@ DbgRecordType
Definition LLToken.h:525
@ kw_address_is_null
Definition LLToken.h:224
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:154
@ kw_uniqueRetVal
Definition LLToken.h:471
@ kw_insertvalue
Definition LLToken.h:378
@ kw_indirectbr
Definition LLToken.h:354
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:594
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
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:1668
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:53
scope_exit(Callable) -> scope_exit< Callable >
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:633
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.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
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:356
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
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
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:371
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:365
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
IRMemLocation
The locations at which a function might access memory.
Definition ModRef.h:60
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
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:2011
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
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:1916
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2191
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:375
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
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
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 NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
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.