LLVM 22.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
50#include "llvm/Support/ModRef.h"
53#include <algorithm>
54#include <cassert>
55#include <cstring>
56#include <optional>
57#include <vector>
58
59using namespace llvm;
60
62 "allow-incomplete-ir", cl::init(false), cl::Hidden,
64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
66
67static std::string getTypeString(Type *T) {
68 std::string Result;
69 raw_string_ostream Tmp(Result);
70 Tmp << *T;
71 return Tmp.str();
72}
73
74/// Run: module ::= toplevelentity*
75bool LLParser::Run(bool UpgradeDebugInfo,
76 DataLayoutCallbackTy DataLayoutCallback) {
77 // Prime the lexer.
78 Lex.Lex();
79
80 if (Context.shouldDiscardValueNames())
81 return error(
82 Lex.getLoc(),
83 "Can't read textual IR with a Context that discards named Values");
84
85 if (M) {
86 if (parseTargetDefinitions(DataLayoutCallback))
87 return true;
88 }
89
90 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
91 validateEndOfIndex();
92}
93
95 const SlotMapping *Slots) {
96 restoreParsingState(Slots);
97 Lex.Lex();
98
99 Type *Ty = nullptr;
100 if (parseType(Ty) || parseConstantValue(Ty, C))
101 return true;
102 if (Lex.getKind() != lltok::Eof)
103 return error(Lex.getLoc(), "expected end of string");
104 return false;
105}
106
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
111
112 Read = 0;
113 SMLoc Start = Lex.getLoc();
114 Ty = nullptr;
115 if (parseType(Ty))
116 return true;
117 SMLoc End = Lex.getLoc();
118 Read = End.getPointer() - Start.getPointer();
119
120 return false;
121}
122
124 const SlotMapping *Slots) {
125 restoreParsingState(Slots);
126 Lex.Lex();
127
128 Read = 0;
129 SMLoc Start = Lex.getLoc();
130 Result = nullptr;
131 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
132 SMLoc End = Lex.getLoc();
133 Read = End.getPointer() - Start.getPointer();
134
135 return Status;
136}
137
138void LLParser::restoreParsingState(const SlotMapping *Slots) {
139 if (!Slots)
140 return;
141 NumberedVals = Slots->GlobalValues;
142 NumberedMetadata = Slots->MetadataNodes;
143 for (const auto &I : Slots->NamedTypes)
144 NamedTypes.insert(
145 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
146 for (const auto &I : Slots->Types)
147 NumberedTypes.insert(
148 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149}
150
152 // White-list intrinsics that are safe to drop.
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
155 return;
156
158 for (Value *V : II->args())
159 if (auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
162 MVs.push_back(MV);
163
164 if (!MVs.empty()) {
165 assert(II->use_empty() && "Cannot have uses");
166 II->eraseFromParent();
167
168 // Also remove no longer used MetadataAsValue wrappers.
169 for (MetadataAsValue *MV : MVs)
170 if (MV->use_empty())
171 delete MV;
172 }
173}
174
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
177 for (Function &F : *M) {
178 F.eraseMetadataIf(Pred);
179 for (Instruction &I : make_early_inc_range(instructions(F))) {
180 I.eraseMetadataIf(Pred);
181
182 if (auto *II = dyn_cast<IntrinsicInst>(&I))
184 }
185 }
186
187 for (GlobalVariable &GV : M->globals())
188 GV.eraseMetadataIf(Pred);
189
190 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
191 // Check whether there is only a single use left, which would be in our
192 // own NumberedMetadata.
193 if (Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(ID);
195 ForwardRefMDNodes.erase(ID);
196 }
197 }
198}
199
200/// validateEndOfModule - Do final validity and basic correctness checks at the
201/// end of the module.
202bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
203 if (!M)
204 return false;
205
206 // We should have already returned an error if we observed both intrinsics and
207 // records in this IR.
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
210
211 // Handle any function attribute group forward references.
212 for (const auto &RAG : ForwardRefAttrGroups) {
213 Value *V = RAG.first;
214 const std::vector<unsigned> &Attrs = RAG.second;
215 AttrBuilder B(Context);
216
217 for (const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
220 B.merge(R->second);
221 }
222
223 if (Function *Fn = dyn_cast<Function>(V)) {
224 AttributeList AS = Fn->getAttributes();
225 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
226 AS = AS.removeFnAttributes(Context);
227
228 FnAttrs.merge(B);
229
230 // If the alignment was parsed as an attribute, move to the alignment
231 // field.
232 if (MaybeAlign A = FnAttrs.getAlignment()) {
233 Fn->setAlignment(*A);
234 FnAttrs.removeAttribute(Attribute::Alignment);
235 }
236
237 AS = AS.addFnAttributes(Context, FnAttrs);
238 Fn->setAttributes(AS);
239 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
240 AttributeList AS = CI->getAttributes();
241 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
242 AS = AS.removeFnAttributes(Context);
243 FnAttrs.merge(B);
244 AS = AS.addFnAttributes(Context, FnAttrs);
245 CI->setAttributes(AS);
246 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
247 AttributeList AS = II->getAttributes();
248 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
249 AS = AS.removeFnAttributes(Context);
250 FnAttrs.merge(B);
251 AS = AS.addFnAttributes(Context, FnAttrs);
252 II->setAttributes(AS);
253 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 AttributeList AS = CBI->getAttributes();
255 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
256 AS = AS.removeFnAttributes(Context);
257 FnAttrs.merge(B);
258 AS = AS.addFnAttributes(Context, FnAttrs);
259 CBI->setAttributes(AS);
260 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
261 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
262 Attrs.merge(B);
263 GV->setAttributes(AttributeSet::get(Context,Attrs));
264 } else {
265 llvm_unreachable("invalid object with forward attribute group reference");
266 }
267 }
268
269 // If there are entries in ForwardRefBlockAddresses at this point, the
270 // function was never defined.
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
274
275 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
276 GlobalValue *FwdRef) {
277 GlobalValue *GV = nullptr;
278 if (GVRef.Kind == ValID::t_GlobalName) {
279 GV = M->getNamedValue(GVRef.StrVal);
280 } else {
281 GV = NumberedVals.get(GVRef.UIntVal);
282 }
283
284 if (!GV)
285 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
286 "' referenced by dso_local_equivalent");
287
288 if (!GV->getValueType()->isFunctionTy())
289 return error(GVRef.Loc,
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
292
293 auto *Equiv = DSOLocalEquivalent::get(GV);
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
296 return false;
297 };
298
299 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
300 // point, they are references after the function was defined. Resolve those
301 // now.
302 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 return true;
305 }
306 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
308 return true;
309 }
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
312
313 for (const auto &NT : NumberedTypes)
314 if (NT.second.second.isValid())
315 return error(NT.second.second,
316 "use of undefined type '%" + Twine(NT.first) + "'");
317
318 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
319 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
320 if (I->second.second.isValid())
321 return error(I->second.second,
322 "use of undefined type named '" + I->getKey() + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 if (IID == Intrinsic::not_intrinsic)
333 // Don't do anything for unknown intrinsics.
334 continue;
335
336 // Automatically create declarations for intrinsics. Intrinsics can only
337 // be called directly, so the call function type directly determines the
338 // declaration function type.
339 //
340 // Additionally, automatically add the required mangling suffix to the
341 // intrinsic name. This means that we may replace a single forward
342 // declaration with multiple functions here.
343 for (Use &U : make_early_inc_range(Info.first->uses())) {
344 auto *CB = dyn_cast<CallBase>(U.getUser());
345 if (!CB || !CB->isCallee(&U))
346 return error(Info.second, "intrinsic can only be used as callee");
347
348 SmallVector<Type *> OverloadTys;
349 if (!Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
350 OverloadTys))
351 return error(Info.second, "invalid intrinsic signature");
352
353 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
354 }
355
356 Info.first->eraseFromParent();
357 ForwardRefVals.erase(Name);
358 continue;
359 }
360
361 // If incomplete IR is allowed, also add declarations for
362 // non-intrinsics.
364 continue;
365
366 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
367 FunctionType *FTy = nullptr;
368 for (Use &U : V->uses()) {
369 auto *CB = dyn_cast<CallBase>(U.getUser());
370 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
371 return nullptr;
372 FTy = CB->getFunctionType();
373 }
374 return FTy;
375 };
376
377 // First check whether this global is only used in calls with the same
378 // type, in which case we'll insert a function. Otherwise, fall back to
379 // using a dummy i8 type.
380 Type *Ty = GetCommonFunctionType(Info.first);
381 if (!Ty)
382 Ty = Type::getInt8Ty(Context);
383
384 GlobalValue *GV;
385 if (auto *FTy = dyn_cast<FunctionType>(Ty))
387 else
388 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
390 /*Initializer*/ nullptr, Name);
391 Info.first->replaceAllUsesWith(GV);
392 Info.first->eraseFromParent();
393 ForwardRefVals.erase(Name);
394 }
395
396 if (!ForwardRefVals.empty())
397 return error(ForwardRefVals.begin()->second.second,
398 "use of undefined value '@" + ForwardRefVals.begin()->first +
399 "'");
400
401 if (!ForwardRefValIDs.empty())
402 return error(ForwardRefValIDs.begin()->second.second,
403 "use of undefined value '@" +
404 Twine(ForwardRefValIDs.begin()->first) + "'");
405
406 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
407 dropUnknownMetadataReferences();
408
409 if (!ForwardRefMDNodes.empty())
410 return error(ForwardRefMDNodes.begin()->second.second,
411 "use of undefined metadata '!" +
412 Twine(ForwardRefMDNodes.begin()->first) + "'");
413
414 // Resolve metadata cycles.
415 for (auto &N : NumberedMetadata) {
416 if (N.second && !N.second->isResolved())
417 N.second->resolveCycles();
418 }
419
420 for (auto *Inst : InstsWithTBAATag) {
421 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
422 // With incomplete IR, the tbaa metadata may have been dropped.
424 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
425 if (MD) {
426 auto *UpgradedMD = UpgradeTBAANode(*MD);
427 if (MD != UpgradedMD)
428 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
429 }
430 }
431
432 // Look for intrinsic functions and CallInst that need to be upgraded. We use
433 // make_early_inc_range here because we may remove some functions.
434 for (Function &F : llvm::make_early_inc_range(*M))
436
437 if (UpgradeDebugInfo)
439
443
444 if (!Slots)
445 return false;
446 // Initialize the slot mapping.
447 // Because by this point we've parsed and validated everything, we can "steal"
448 // the mapping from LLParser as it doesn't need it anymore.
449 Slots->GlobalValues = std::move(NumberedVals);
450 Slots->MetadataNodes = std::move(NumberedMetadata);
451 for (const auto &I : NamedTypes)
452 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
453 for (const auto &I : NumberedTypes)
454 Slots->Types.insert(std::make_pair(I.first, I.second.first));
455
456 return false;
457}
458
459/// Do final validity and basic correctness checks at the end of the index.
460bool LLParser::validateEndOfIndex() {
461 if (!Index)
462 return false;
463
464 if (!ForwardRefValueInfos.empty())
465 return error(ForwardRefValueInfos.begin()->second.front().second,
466 "use of undefined summary '^" +
467 Twine(ForwardRefValueInfos.begin()->first) + "'");
468
469 if (!ForwardRefAliasees.empty())
470 return error(ForwardRefAliasees.begin()->second.front().second,
471 "use of undefined summary '^" +
472 Twine(ForwardRefAliasees.begin()->first) + "'");
473
474 if (!ForwardRefTypeIds.empty())
475 return error(ForwardRefTypeIds.begin()->second.front().second,
476 "use of undefined type id summary '^" +
477 Twine(ForwardRefTypeIds.begin()->first) + "'");
478
479 return false;
480}
481
482//===----------------------------------------------------------------------===//
483// Top-Level Entities
484//===----------------------------------------------------------------------===//
485
486bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
487 // Delay parsing of the data layout string until the target triple is known.
488 // Then, pass both the the target triple and the tentative data layout string
489 // to DataLayoutCallback, allowing to override the DL string.
490 // This enables importing modules with invalid DL strings.
491 std::string TentativeDLStr = M->getDataLayoutStr();
492 LocTy DLStrLoc;
493
494 bool Done = false;
495 while (!Done) {
496 switch (Lex.getKind()) {
497 case lltok::kw_target:
498 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
499 return true;
500 break;
502 if (parseSourceFileName())
503 return true;
504 break;
505 default:
506 Done = true;
507 }
508 }
509 // Run the override callback to potentially change the data layout string, and
510 // parse the data layout string.
511 if (auto LayoutOverride =
512 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
513 TentativeDLStr = *LayoutOverride;
514 DLStrLoc = {};
515 }
516 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
517 if (!MaybeDL)
518 return error(DLStrLoc, toString(MaybeDL.takeError()));
519 M->setDataLayout(MaybeDL.get());
520 return false;
521}
522
523bool LLParser::parseTopLevelEntities() {
524 // If there is no Module, then parse just the summary index entries.
525 if (!M) {
526 while (true) {
527 switch (Lex.getKind()) {
528 case lltok::Eof:
529 return false;
530 case lltok::SummaryID:
531 if (parseSummaryEntry())
532 return true;
533 break;
535 if (parseSourceFileName())
536 return true;
537 break;
538 default:
539 // Skip everything else
540 Lex.Lex();
541 }
542 }
543 }
544 while (true) {
545 switch (Lex.getKind()) {
546 default:
547 return tokError("expected top-level entity");
548 case lltok::Eof: return false;
550 if (parseDeclare())
551 return true;
552 break;
553 case lltok::kw_define:
554 if (parseDefine())
555 return true;
556 break;
557 case lltok::kw_module:
558 if (parseModuleAsm())
559 return true;
560 break;
562 if (parseUnnamedType())
563 return true;
564 break;
565 case lltok::LocalVar:
566 if (parseNamedType())
567 return true;
568 break;
569 case lltok::GlobalID:
570 if (parseUnnamedGlobal())
571 return true;
572 break;
573 case lltok::GlobalVar:
574 if (parseNamedGlobal())
575 return true;
576 break;
577 case lltok::ComdatVar: if (parseComdat()) return true; break;
578 case lltok::exclaim:
579 if (parseStandaloneMetadata())
580 return true;
581 break;
582 case lltok::SummaryID:
583 if (parseSummaryEntry())
584 return true;
585 break;
587 if (parseNamedMetadata())
588 return true;
589 break;
591 if (parseUnnamedAttrGrp())
592 return true;
593 break;
595 if (parseUseListOrder())
596 return true;
597 break;
599 if (parseUseListOrderBB())
600 return true;
601 break;
602 }
603 }
604}
605
606/// toplevelentity
607/// ::= 'module' 'asm' STRINGCONSTANT
608bool LLParser::parseModuleAsm() {
609 assert(Lex.getKind() == lltok::kw_module);
610 Lex.Lex();
611
612 std::string AsmStr;
613 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
614 parseStringConstant(AsmStr))
615 return true;
616
617 M->appendModuleInlineAsm(AsmStr);
618 return false;
619}
620
621/// toplevelentity
622/// ::= 'target' 'triple' '=' STRINGCONSTANT
623/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
624bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
625 LocTy &DLStrLoc) {
626 assert(Lex.getKind() == lltok::kw_target);
627 std::string Str;
628 switch (Lex.Lex()) {
629 default:
630 return tokError("unknown target property");
631 case lltok::kw_triple:
632 Lex.Lex();
633 if (parseToken(lltok::equal, "expected '=' after target triple") ||
634 parseStringConstant(Str))
635 return true;
636 M->setTargetTriple(Triple(std::move(Str)));
637 return false;
639 Lex.Lex();
640 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
641 return true;
642 DLStrLoc = Lex.getLoc();
643 if (parseStringConstant(TentativeDLStr))
644 return true;
645 return false;
646 }
647}
648
649/// toplevelentity
650/// ::= 'source_filename' '=' STRINGCONSTANT
651bool LLParser::parseSourceFileName() {
652 assert(Lex.getKind() == lltok::kw_source_filename);
653 Lex.Lex();
654 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
655 parseStringConstant(SourceFileName))
656 return true;
657 if (M)
658 M->setSourceFileName(SourceFileName);
659 return false;
660}
661
662/// parseUnnamedType:
663/// ::= LocalVarID '=' 'type' type
664bool LLParser::parseUnnamedType() {
665 LocTy TypeLoc = Lex.getLoc();
666 unsigned TypeID = Lex.getUIntVal();
667 Lex.Lex(); // eat LocalVarID;
668
669 if (parseToken(lltok::equal, "expected '=' after name") ||
670 parseToken(lltok::kw_type, "expected 'type' after '='"))
671 return true;
672
673 Type *Result = nullptr;
674 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
675 return true;
676
677 if (!isa<StructType>(Result)) {
678 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
679 if (Entry.first)
680 return error(TypeLoc, "non-struct types may not be recursive");
681 Entry.first = Result;
682 Entry.second = SMLoc();
683 }
684
685 return false;
686}
687
688/// toplevelentity
689/// ::= LocalVar '=' 'type' type
690bool LLParser::parseNamedType() {
691 std::string Name = Lex.getStrVal();
692 LocTy NameLoc = Lex.getLoc();
693 Lex.Lex(); // eat LocalVar.
694
695 if (parseToken(lltok::equal, "expected '=' after name") ||
696 parseToken(lltok::kw_type, "expected 'type' after name"))
697 return true;
698
699 Type *Result = nullptr;
700 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
701 return true;
702
703 if (!isa<StructType>(Result)) {
704 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
705 if (Entry.first)
706 return error(NameLoc, "non-struct types may not be recursive");
707 Entry.first = Result;
708 Entry.second = SMLoc();
709 }
710
711 return false;
712}
713
714/// toplevelentity
715/// ::= 'declare' FunctionHeader
716bool LLParser::parseDeclare() {
717 assert(Lex.getKind() == lltok::kw_declare);
718 Lex.Lex();
719
720 std::vector<std::pair<unsigned, MDNode *>> MDs;
721 while (Lex.getKind() == lltok::MetadataVar) {
722 unsigned MDK;
723 MDNode *N;
724 if (parseMetadataAttachment(MDK, N))
725 return true;
726 MDs.push_back({MDK, N});
727 }
728
729 Function *F;
730 unsigned FunctionNumber = -1;
731 SmallVector<unsigned> UnnamedArgNums;
732 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
733 return true;
734 for (auto &MD : MDs)
735 F->addMetadata(MD.first, *MD.second);
736 return false;
737}
738
739/// toplevelentity
740/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
741bool LLParser::parseDefine() {
742 assert(Lex.getKind() == lltok::kw_define);
743 Lex.Lex();
744
745 Function *F;
746 unsigned FunctionNumber = -1;
747 SmallVector<unsigned> UnnamedArgNums;
748 return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
749 parseOptionalFunctionMetadata(*F) ||
750 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
751}
752
753/// parseGlobalType
754/// ::= 'constant'
755/// ::= 'global'
756bool LLParser::parseGlobalType(bool &IsConstant) {
757 if (Lex.getKind() == lltok::kw_constant)
758 IsConstant = true;
759 else if (Lex.getKind() == lltok::kw_global)
760 IsConstant = false;
761 else {
762 IsConstant = false;
763 return tokError("expected 'global' or 'constant'");
764 }
765 Lex.Lex();
766 return false;
767}
768
769bool LLParser::parseOptionalUnnamedAddr(
770 GlobalVariable::UnnamedAddr &UnnamedAddr) {
771 if (EatIfPresent(lltok::kw_unnamed_addr))
773 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
775 else
776 UnnamedAddr = GlobalValue::UnnamedAddr::None;
777 return false;
778}
779
780/// parseUnnamedGlobal:
781/// OptionalVisibility (ALIAS | IFUNC) ...
782/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
783/// OptionalDLLStorageClass
784/// ... -> global variable
785/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
786/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
787/// OptionalVisibility
788/// OptionalDLLStorageClass
789/// ... -> global variable
790bool LLParser::parseUnnamedGlobal() {
791 unsigned VarID;
792 std::string Name;
793 LocTy NameLoc = Lex.getLoc();
794
795 // Handle the GlobalID form.
796 if (Lex.getKind() == lltok::GlobalID) {
797 VarID = Lex.getUIntVal();
798 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
799 return true;
800
801 Lex.Lex(); // eat GlobalID;
802 if (parseToken(lltok::equal, "expected '=' after name"))
803 return true;
804 } else {
805 VarID = NumberedVals.getNext();
806 }
807
808 bool HasLinkage;
809 unsigned Linkage, Visibility, DLLStorageClass;
810 bool DSOLocal;
812 GlobalVariable::UnnamedAddr UnnamedAddr;
813 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
814 DSOLocal) ||
815 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
816 return true;
817
818 switch (Lex.getKind()) {
819 default:
820 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
821 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
822 case lltok::kw_alias:
823 case lltok::kw_ifunc:
824 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
825 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
826 }
827}
828
829/// parseNamedGlobal:
830/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
831/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
832/// OptionalVisibility OptionalDLLStorageClass
833/// ... -> global variable
834bool LLParser::parseNamedGlobal() {
835 assert(Lex.getKind() == lltok::GlobalVar);
836 LocTy NameLoc = Lex.getLoc();
837 std::string Name = Lex.getStrVal();
838 Lex.Lex();
839
840 bool HasLinkage;
841 unsigned Linkage, Visibility, DLLStorageClass;
842 bool DSOLocal;
844 GlobalVariable::UnnamedAddr UnnamedAddr;
845 if (parseToken(lltok::equal, "expected '=' in global variable") ||
846 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
847 DSOLocal) ||
848 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
849 return true;
850
851 switch (Lex.getKind()) {
852 default:
853 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
854 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
855 case lltok::kw_alias:
856 case lltok::kw_ifunc:
857 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
858 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
859 }
860}
861
862bool LLParser::parseComdat() {
863 assert(Lex.getKind() == lltok::ComdatVar);
864 std::string Name = Lex.getStrVal();
865 LocTy NameLoc = Lex.getLoc();
866 Lex.Lex();
867
868 if (parseToken(lltok::equal, "expected '=' here"))
869 return true;
870
871 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
872 return tokError("expected comdat type");
873
875 switch (Lex.getKind()) {
876 default:
877 return tokError("unknown selection kind");
878 case lltok::kw_any:
879 SK = Comdat::Any;
880 break;
883 break;
885 SK = Comdat::Largest;
886 break;
889 break;
891 SK = Comdat::SameSize;
892 break;
893 }
894 Lex.Lex();
895
896 // See if the comdat was forward referenced, if so, use the comdat.
897 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
898 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
899 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
900 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
901
902 Comdat *C;
903 if (I != ComdatSymTab.end())
904 C = &I->second;
905 else
906 C = M->getOrInsertComdat(Name);
907 C->setSelectionKind(SK);
908
909 return false;
910}
911
912// MDString:
913// ::= '!' STRINGCONSTANT
914bool LLParser::parseMDString(MDString *&Result) {
915 std::string Str;
916 if (parseStringConstant(Str))
917 return true;
918 Result = MDString::get(Context, Str);
919 return false;
920}
921
922// MDNode:
923// ::= '!' MDNodeNumber
924bool LLParser::parseMDNodeID(MDNode *&Result) {
925 // !{ ..., !42, ... }
926 LocTy IDLoc = Lex.getLoc();
927 unsigned MID = 0;
928 if (parseUInt32(MID))
929 return true;
930
931 // If not a forward reference, just return it now.
932 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
933 if (!Inserted) {
934 Result = It->second;
935 return false;
936 }
937
938 // Otherwise, create MDNode forward reference.
939 auto &FwdRef = ForwardRefMDNodes[MID];
940 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
941
942 Result = FwdRef.first.get();
943 It->second.reset(Result);
944 return false;
945}
946
947/// parseNamedMetadata:
948/// !foo = !{ !1, !2 }
949bool LLParser::parseNamedMetadata() {
950 assert(Lex.getKind() == lltok::MetadataVar);
951 std::string Name = Lex.getStrVal();
952 Lex.Lex();
953
954 if (parseToken(lltok::equal, "expected '=' here") ||
955 parseToken(lltok::exclaim, "Expected '!' here") ||
956 parseToken(lltok::lbrace, "Expected '{' here"))
957 return true;
958
959 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
960 if (Lex.getKind() != lltok::rbrace)
961 do {
962 MDNode *N = nullptr;
963 // parse DIExpressions inline as a special case. They are still MDNodes,
964 // so they can still appear in named metadata. Remove this logic if they
965 // become plain Metadata.
966 if (Lex.getKind() == lltok::MetadataVar &&
967 Lex.getStrVal() == "DIExpression") {
968 if (parseDIExpression(N, /*IsDistinct=*/false))
969 return true;
970 // DIArgLists should only appear inline in a function, as they may
971 // contain LocalAsMetadata arguments which require a function context.
972 } else if (Lex.getKind() == lltok::MetadataVar &&
973 Lex.getStrVal() == "DIArgList") {
974 return tokError("found DIArgList outside of function");
975 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
976 parseMDNodeID(N)) {
977 return true;
978 }
979 NMD->addOperand(N);
980 } while (EatIfPresent(lltok::comma));
981
982 return parseToken(lltok::rbrace, "expected end of metadata node");
983}
984
985/// parseStandaloneMetadata:
986/// !42 = !{...}
987bool LLParser::parseStandaloneMetadata() {
988 assert(Lex.getKind() == lltok::exclaim);
989 Lex.Lex();
990 unsigned MetadataID = 0;
991
992 MDNode *Init;
993 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
994 return true;
995
996 // Detect common error, from old metadata syntax.
997 if (Lex.getKind() == lltok::Type)
998 return tokError("unexpected type in metadata definition");
999
1000 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1001 if (Lex.getKind() == lltok::MetadataVar) {
1002 if (parseSpecializedMDNode(Init, IsDistinct))
1003 return true;
1004 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1005 parseMDTuple(Init, IsDistinct))
1006 return true;
1007
1008 // See if this was forward referenced, if so, handle it.
1009 auto FI = ForwardRefMDNodes.find(MetadataID);
1010 if (FI != ForwardRefMDNodes.end()) {
1011 auto *ToReplace = FI->second.first.get();
1012 // DIAssignID has its own special forward-reference "replacement" for
1013 // attachments (the temporary attachments are never actually attached).
1014 if (isa<DIAssignID>(Init)) {
1015 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1016 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1017 "Inst unexpectedly already has DIAssignID attachment");
1018 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1019 }
1020 }
1021
1022 ToReplace->replaceAllUsesWith(Init);
1023 ForwardRefMDNodes.erase(FI);
1024
1025 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1026 } else {
1027 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1028 if (!Inserted)
1029 return tokError("Metadata id is already used");
1030 It->second.reset(Init);
1031 }
1032
1033 return false;
1034}
1035
1036// Skips a single module summary entry.
1037bool LLParser::skipModuleSummaryEntry() {
1038 // Each module summary entry consists of a tag for the entry
1039 // type, followed by a colon, then the fields which may be surrounded by
1040 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1041 // support is in place we will look for the tokens corresponding to the
1042 // expected tags.
1043 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1044 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1045 Lex.getKind() != lltok::kw_blockcount)
1046 return tokError(
1047 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1048 "start of summary entry");
1049 if (Lex.getKind() == lltok::kw_flags)
1050 return parseSummaryIndexFlags();
1051 if (Lex.getKind() == lltok::kw_blockcount)
1052 return parseBlockCount();
1053 Lex.Lex();
1054 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1055 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1056 return true;
1057 // Now walk through the parenthesized entry, until the number of open
1058 // parentheses goes back down to 0 (the first '(' was parsed above).
1059 unsigned NumOpenParen = 1;
1060 do {
1061 switch (Lex.getKind()) {
1062 case lltok::lparen:
1063 NumOpenParen++;
1064 break;
1065 case lltok::rparen:
1066 NumOpenParen--;
1067 break;
1068 case lltok::Eof:
1069 return tokError("found end of file while parsing summary entry");
1070 default:
1071 // Skip everything in between parentheses.
1072 break;
1073 }
1074 Lex.Lex();
1075 } while (NumOpenParen > 0);
1076 return false;
1077}
1078
1079/// SummaryEntry
1080/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1081bool LLParser::parseSummaryEntry() {
1082 assert(Lex.getKind() == lltok::SummaryID);
1083 unsigned SummaryID = Lex.getUIntVal();
1084
1085 // For summary entries, colons should be treated as distinct tokens,
1086 // not an indication of the end of a label token.
1087 Lex.setIgnoreColonInIdentifiers(true);
1088
1089 Lex.Lex();
1090 if (parseToken(lltok::equal, "expected '=' here"))
1091 return true;
1092
1093 // If we don't have an index object, skip the summary entry.
1094 if (!Index)
1095 return skipModuleSummaryEntry();
1096
1097 bool result = false;
1098 switch (Lex.getKind()) {
1099 case lltok::kw_gv:
1100 result = parseGVEntry(SummaryID);
1101 break;
1102 case lltok::kw_module:
1103 result = parseModuleEntry(SummaryID);
1104 break;
1105 case lltok::kw_typeid:
1106 result = parseTypeIdEntry(SummaryID);
1107 break;
1109 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1110 break;
1111 case lltok::kw_flags:
1112 result = parseSummaryIndexFlags();
1113 break;
1115 result = parseBlockCount();
1116 break;
1117 default:
1118 result = error(Lex.getLoc(), "unexpected summary kind");
1119 break;
1120 }
1121 Lex.setIgnoreColonInIdentifiers(false);
1122 return result;
1123}
1124
1133
1134// If there was an explicit dso_local, update GV. In the absence of an explicit
1135// dso_local we keep the default value.
1136static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1137 if (DSOLocal)
1138 GV.setDSOLocal(true);
1139}
1140
1141/// parseAliasOrIFunc:
1142/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1143/// OptionalVisibility OptionalDLLStorageClass
1144/// OptionalThreadLocal OptionalUnnamedAddr
1145/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1146///
1147/// AliaseeOrResolver
1148/// ::= TypeAndValue
1149///
1150/// SymbolAttrs
1151/// ::= ',' 'partition' StringConstant
1152///
1153/// Everything through OptionalUnnamedAddr has already been parsed.
1154///
1155bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1156 LocTy NameLoc, unsigned L, unsigned Visibility,
1157 unsigned DLLStorageClass, bool DSOLocal,
1159 GlobalVariable::UnnamedAddr UnnamedAddr) {
1160 bool IsAlias;
1161 if (Lex.getKind() == lltok::kw_alias)
1162 IsAlias = true;
1163 else if (Lex.getKind() == lltok::kw_ifunc)
1164 IsAlias = false;
1165 else
1166 llvm_unreachable("Not an alias or ifunc!");
1167 Lex.Lex();
1168
1170
1171 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1172 return error(NameLoc, "invalid linkage type for alias");
1173
1174 if (!isValidVisibilityForLinkage(Visibility, L))
1175 return error(NameLoc,
1176 "symbol with local linkage must have default visibility");
1177
1178 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1179 return error(NameLoc,
1180 "symbol with local linkage cannot have a DLL storage class");
1181
1182 Type *Ty;
1183 LocTy ExplicitTypeLoc = Lex.getLoc();
1184 if (parseType(Ty) ||
1185 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1186 return true;
1187
1188 Constant *Aliasee;
1189 LocTy AliaseeLoc = Lex.getLoc();
1190 if (Lex.getKind() != lltok::kw_bitcast &&
1191 Lex.getKind() != lltok::kw_getelementptr &&
1192 Lex.getKind() != lltok::kw_addrspacecast &&
1193 Lex.getKind() != lltok::kw_inttoptr) {
1194 if (parseGlobalTypeAndValue(Aliasee))
1195 return true;
1196 } else {
1197 // The bitcast dest type is not present, it is implied by the dest type.
1198 ValID ID;
1199 if (parseValID(ID, /*PFS=*/nullptr))
1200 return true;
1201 if (ID.Kind != ValID::t_Constant)
1202 return error(AliaseeLoc, "invalid aliasee");
1203 Aliasee = ID.ConstantVal;
1204 }
1205
1206 Type *AliaseeType = Aliasee->getType();
1207 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1208 if (!PTy)
1209 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1210 unsigned AddrSpace = PTy->getAddressSpace();
1211
1212 GlobalValue *GVal = nullptr;
1213
1214 // See if the alias was forward referenced, if so, prepare to replace the
1215 // forward reference.
1216 if (!Name.empty()) {
1217 auto I = ForwardRefVals.find(Name);
1218 if (I != ForwardRefVals.end()) {
1219 GVal = I->second.first;
1220 ForwardRefVals.erase(Name);
1221 } else if (M->getNamedValue(Name)) {
1222 return error(NameLoc, "redefinition of global '@" + Name + "'");
1223 }
1224 } else {
1225 auto I = ForwardRefValIDs.find(NameID);
1226 if (I != ForwardRefValIDs.end()) {
1227 GVal = I->second.first;
1228 ForwardRefValIDs.erase(I);
1229 }
1230 }
1231
1232 // Okay, create the alias/ifunc but do not insert it into the module yet.
1233 std::unique_ptr<GlobalAlias> GA;
1234 std::unique_ptr<GlobalIFunc> GI;
1235 GlobalValue *GV;
1236 if (IsAlias) {
1237 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1238 /*Parent=*/nullptr));
1239 GV = GA.get();
1240 } else {
1241 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1242 /*Parent=*/nullptr));
1243 GV = GI.get();
1244 }
1245 GV->setThreadLocalMode(TLM);
1248 GV->setUnnamedAddr(UnnamedAddr);
1249 maybeSetDSOLocal(DSOLocal, *GV);
1250
1251 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1252 // Now parse them if there are any.
1253 while (Lex.getKind() == lltok::comma) {
1254 Lex.Lex();
1255
1256 if (Lex.getKind() == lltok::kw_partition) {
1257 Lex.Lex();
1258 GV->setPartition(Lex.getStrVal());
1259 if (parseToken(lltok::StringConstant, "expected partition string"))
1260 return true;
1261 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1262 if (parseGlobalObjectMetadataAttachment(*GI.get()))
1263 return true;
1264 } else {
1265 return tokError("unknown alias or ifunc property!");
1266 }
1267 }
1268
1269 if (Name.empty())
1270 NumberedVals.add(NameID, GV);
1271
1272 if (GVal) {
1273 // Verify that types agree.
1274 if (GVal->getType() != GV->getType())
1275 return error(
1276 ExplicitTypeLoc,
1277 "forward reference and definition of alias have different types");
1278
1279 // If they agree, just RAUW the old value with the alias and remove the
1280 // forward ref info.
1281 GVal->replaceAllUsesWith(GV);
1282 GVal->eraseFromParent();
1283 }
1284
1285 // Insert into the module, we know its name won't collide now.
1286 if (IsAlias)
1287 M->insertAlias(GA.release());
1288 else
1289 M->insertIFunc(GI.release());
1290 assert(GV->getName() == Name && "Should not be a name conflict!");
1291
1292 return false;
1293}
1294
1295static bool isSanitizer(lltok::Kind Kind) {
1296 switch (Kind) {
1299 case lltok::kw_sanitize_memtag:
1301 return true;
1302 default:
1303 return false;
1304 }
1305}
1306
1307bool LLParser::parseSanitizer(GlobalVariable *GV) {
1308 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1310 if (GV->hasSanitizerMetadata())
1311 Meta = GV->getSanitizerMetadata();
1312
1313 switch (Lex.getKind()) {
1315 Meta.NoAddress = true;
1316 break;
1318 Meta.NoHWAddress = true;
1319 break;
1320 case lltok::kw_sanitize_memtag:
1321 Meta.Memtag = true;
1322 break;
1324 Meta.IsDynInit = true;
1325 break;
1326 default:
1327 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1328 }
1329 GV->setSanitizerMetadata(Meta);
1330 Lex.Lex();
1331 return false;
1332}
1333
1334/// parseGlobal
1335/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1336/// OptionalVisibility OptionalDLLStorageClass
1337/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1338/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1339/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1340/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1341/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1342/// Const OptionalAttrs
1343///
1344/// Everything up to and including OptionalUnnamedAddr has been parsed
1345/// already.
1346///
1347bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1348 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1349 unsigned Visibility, unsigned DLLStorageClass,
1350 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1351 GlobalVariable::UnnamedAddr UnnamedAddr) {
1352 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1353 return error(NameLoc,
1354 "symbol with local linkage must have default visibility");
1355
1356 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1357 return error(NameLoc,
1358 "symbol with local linkage cannot have a DLL storage class");
1359
1360 unsigned AddrSpace;
1361 bool IsConstant, IsExternallyInitialized;
1362 LocTy IsExternallyInitializedLoc;
1363 LocTy TyLoc;
1364
1365 Type *Ty = nullptr;
1366 if (parseOptionalAddrSpace(AddrSpace) ||
1367 parseOptionalToken(lltok::kw_externally_initialized,
1368 IsExternallyInitialized,
1369 &IsExternallyInitializedLoc) ||
1370 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1371 return true;
1372
1373 // If the linkage is specified and is external, then no initializer is
1374 // present.
1375 Constant *Init = nullptr;
1376 if (!HasLinkage ||
1379 if (parseGlobalValue(Ty, Init))
1380 return true;
1381 }
1382
1384 return error(TyLoc, "invalid type for global variable");
1385
1386 GlobalValue *GVal = nullptr;
1387
1388 // See if the global was forward referenced, if so, use the global.
1389 if (!Name.empty()) {
1390 auto I = ForwardRefVals.find(Name);
1391 if (I != ForwardRefVals.end()) {
1392 GVal = I->second.first;
1393 ForwardRefVals.erase(I);
1394 } else if (M->getNamedValue(Name)) {
1395 return error(NameLoc, "redefinition of global '@" + Name + "'");
1396 }
1397 } else {
1398 // Handle @"", where a name is syntactically specified, but semantically
1399 // missing.
1400 if (NameID == (unsigned)-1)
1401 NameID = NumberedVals.getNext();
1402
1403 auto I = ForwardRefValIDs.find(NameID);
1404 if (I != ForwardRefValIDs.end()) {
1405 GVal = I->second.first;
1406 ForwardRefValIDs.erase(I);
1407 }
1408 }
1409
1410 GlobalVariable *GV = new GlobalVariable(
1411 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1413
1414 if (Name.empty())
1415 NumberedVals.add(NameID, GV);
1416
1417 // Set the parsed properties on the global.
1418 if (Init)
1419 GV->setInitializer(Init);
1420 GV->setConstant(IsConstant);
1422 maybeSetDSOLocal(DSOLocal, *GV);
1425 GV->setExternallyInitialized(IsExternallyInitialized);
1426 GV->setThreadLocalMode(TLM);
1427 GV->setUnnamedAddr(UnnamedAddr);
1428
1429 if (GVal) {
1430 if (GVal->getAddressSpace() != AddrSpace)
1431 return error(
1432 TyLoc,
1433 "forward reference and definition of global have different types");
1434
1435 GVal->replaceAllUsesWith(GV);
1436 GVal->eraseFromParent();
1437 }
1438
1439 // parse attributes on the global.
1440 while (Lex.getKind() == lltok::comma) {
1441 Lex.Lex();
1442
1443 if (Lex.getKind() == lltok::kw_section) {
1444 Lex.Lex();
1445 GV->setSection(Lex.getStrVal());
1446 if (parseToken(lltok::StringConstant, "expected global section string"))
1447 return true;
1448 } else if (Lex.getKind() == lltok::kw_partition) {
1449 Lex.Lex();
1450 GV->setPartition(Lex.getStrVal());
1451 if (parseToken(lltok::StringConstant, "expected partition string"))
1452 return true;
1453 } else if (Lex.getKind() == lltok::kw_align) {
1454 MaybeAlign Alignment;
1455 if (parseOptionalAlignment(Alignment))
1456 return true;
1457 if (Alignment)
1458 GV->setAlignment(*Alignment);
1459 } else if (Lex.getKind() == lltok::kw_code_model) {
1461 if (parseOptionalCodeModel(CodeModel))
1462 return true;
1463 GV->setCodeModel(CodeModel);
1464 } else if (Lex.getKind() == lltok::MetadataVar) {
1465 if (parseGlobalObjectMetadataAttachment(*GV))
1466 return true;
1467 } else if (isSanitizer(Lex.getKind())) {
1468 if (parseSanitizer(GV))
1469 return true;
1470 } else {
1471 Comdat *C;
1472 if (parseOptionalComdat(Name, C))
1473 return true;
1474 if (C)
1475 GV->setComdat(C);
1476 else
1477 return tokError("unknown global variable property!");
1478 }
1479 }
1480
1481 AttrBuilder Attrs(M->getContext());
1482 LocTy BuiltinLoc;
1483 std::vector<unsigned> FwdRefAttrGrps;
1484 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1485 return true;
1486 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1487 GV->setAttributes(AttributeSet::get(Context, Attrs));
1488 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1489 }
1490
1491 return false;
1492}
1493
1494/// parseUnnamedAttrGrp
1495/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1496bool LLParser::parseUnnamedAttrGrp() {
1497 assert(Lex.getKind() == lltok::kw_attributes);
1498 LocTy AttrGrpLoc = Lex.getLoc();
1499 Lex.Lex();
1500
1501 if (Lex.getKind() != lltok::AttrGrpID)
1502 return tokError("expected attribute group id");
1503
1504 unsigned VarID = Lex.getUIntVal();
1505 std::vector<unsigned> unused;
1506 LocTy BuiltinLoc;
1507 Lex.Lex();
1508
1509 if (parseToken(lltok::equal, "expected '=' here") ||
1510 parseToken(lltok::lbrace, "expected '{' here"))
1511 return true;
1512
1513 auto R = NumberedAttrBuilders.find(VarID);
1514 if (R == NumberedAttrBuilders.end())
1515 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1516
1517 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1518 parseToken(lltok::rbrace, "expected end of attribute group"))
1519 return true;
1520
1521 if (!R->second.hasAttributes())
1522 return error(AttrGrpLoc, "attribute group has no attributes");
1523
1524 return false;
1525}
1526
1528 switch (Kind) {
1529#define GET_ATTR_NAMES
1530#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1531 case lltok::kw_##DISPLAY_NAME: \
1532 return Attribute::ENUM_NAME;
1533#include "llvm/IR/Attributes.inc"
1534 default:
1535 return Attribute::None;
1536 }
1537}
1538
1539bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1540 bool InAttrGroup) {
1541 if (Attribute::isTypeAttrKind(Attr))
1542 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1543
1544 switch (Attr) {
1545 case Attribute::Alignment: {
1546 MaybeAlign Alignment;
1547 if (InAttrGroup) {
1548 uint32_t Value = 0;
1549 Lex.Lex();
1550 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1551 return true;
1552 Alignment = Align(Value);
1553 } else {
1554 if (parseOptionalAlignment(Alignment, true))
1555 return true;
1556 }
1557 B.addAlignmentAttr(Alignment);
1558 return false;
1559 }
1560 case Attribute::StackAlignment: {
1561 unsigned Alignment;
1562 if (InAttrGroup) {
1563 Lex.Lex();
1564 if (parseToken(lltok::equal, "expected '=' here") ||
1565 parseUInt32(Alignment))
1566 return true;
1567 } else {
1568 if (parseOptionalStackAlignment(Alignment))
1569 return true;
1570 }
1571 B.addStackAlignmentAttr(Alignment);
1572 return false;
1573 }
1574 case Attribute::AllocSize: {
1575 unsigned ElemSizeArg;
1576 std::optional<unsigned> NumElemsArg;
1577 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1578 return true;
1579 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1580 return false;
1581 }
1582 case Attribute::VScaleRange: {
1583 unsigned MinValue, MaxValue;
1584 if (parseVScaleRangeArguments(MinValue, MaxValue))
1585 return true;
1586 B.addVScaleRangeAttr(MinValue,
1587 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1588 return false;
1589 }
1590 case Attribute::Dereferenceable: {
1591 uint64_t Bytes;
1592 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1593 return true;
1594 B.addDereferenceableAttr(Bytes);
1595 return false;
1596 }
1597 case Attribute::DereferenceableOrNull: {
1598 uint64_t Bytes;
1599 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1600 return true;
1601 B.addDereferenceableOrNullAttr(Bytes);
1602 return false;
1603 }
1604 case Attribute::UWTable: {
1606 if (parseOptionalUWTableKind(Kind))
1607 return true;
1608 B.addUWTableAttr(Kind);
1609 return false;
1610 }
1611 case Attribute::AllocKind: {
1613 if (parseAllocKind(Kind))
1614 return true;
1615 B.addAllocKindAttr(Kind);
1616 return false;
1617 }
1618 case Attribute::Memory: {
1619 std::optional<MemoryEffects> ME = parseMemoryAttr();
1620 if (!ME)
1621 return true;
1622 B.addMemoryAttr(*ME);
1623 return false;
1624 }
1625 case Attribute::NoFPClass: {
1626 if (FPClassTest NoFPClass =
1627 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1628 B.addNoFPClassAttr(NoFPClass);
1629 return false;
1630 }
1631
1632 return true;
1633 }
1634 case Attribute::Range:
1635 return parseRangeAttr(B);
1636 case Attribute::Initializes:
1637 return parseInitializesAttr(B);
1638 case Attribute::Captures:
1639 return parseCapturesAttr(B);
1640 default:
1641 B.addAttribute(Attr);
1642 Lex.Lex();
1643 return false;
1644 }
1645}
1646
1648 switch (Kind) {
1649 case lltok::kw_readnone:
1650 ME &= MemoryEffects::none();
1651 return true;
1652 case lltok::kw_readonly:
1654 return true;
1655 case lltok::kw_writeonly:
1657 return true;
1660 return true;
1663 return true;
1666 return true;
1667 default:
1668 return false;
1669 }
1670}
1671
1672/// parseFnAttributeValuePairs
1673/// ::= <attr> | <attr> '=' <value>
1674bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1675 std::vector<unsigned> &FwdRefAttrGrps,
1676 bool InAttrGrp, LocTy &BuiltinLoc) {
1677 bool HaveError = false;
1678
1679 B.clear();
1680
1682 while (true) {
1683 lltok::Kind Token = Lex.getKind();
1684 if (Token == lltok::rbrace)
1685 break; // Finished.
1686
1687 if (Token == lltok::StringConstant) {
1688 if (parseStringAttribute(B))
1689 return true;
1690 continue;
1691 }
1692
1693 if (Token == lltok::AttrGrpID) {
1694 // Allow a function to reference an attribute group:
1695 //
1696 // define void @foo() #1 { ... }
1697 if (InAttrGrp) {
1698 HaveError |= error(
1699 Lex.getLoc(),
1700 "cannot have an attribute group reference in an attribute group");
1701 } else {
1702 // Save the reference to the attribute group. We'll fill it in later.
1703 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1704 }
1705 Lex.Lex();
1706 continue;
1707 }
1708
1709 SMLoc Loc = Lex.getLoc();
1710 if (Token == lltok::kw_builtin)
1711 BuiltinLoc = Loc;
1712
1713 if (upgradeMemoryAttr(ME, Token)) {
1714 Lex.Lex();
1715 continue;
1716 }
1717
1719 if (Attr == Attribute::None) {
1720 if (!InAttrGrp)
1721 break;
1722 return error(Lex.getLoc(), "unterminated attribute group");
1723 }
1724
1725 if (parseEnumAttribute(Attr, B, InAttrGrp))
1726 return true;
1727
1728 // As a hack, we allow function alignment to be initially parsed as an
1729 // attribute on a function declaration/definition or added to an attribute
1730 // group and later moved to the alignment field.
1731 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1732 HaveError |= error(Loc, "this attribute does not apply to functions");
1733 }
1734
1735 if (ME != MemoryEffects::unknown())
1736 B.addMemoryAttr(ME);
1737 return HaveError;
1738}
1739
1740//===----------------------------------------------------------------------===//
1741// GlobalValue Reference/Resolution Routines.
1742//===----------------------------------------------------------------------===//
1743
1745 // The used global type does not matter. We will later RAUW it with a
1746 // global/function of the correct type.
1747 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1750 PTy->getAddressSpace());
1751}
1752
1753Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1754 Value *Val) {
1755 Type *ValTy = Val->getType();
1756 if (ValTy == Ty)
1757 return Val;
1758 if (Ty->isLabelTy())
1759 error(Loc, "'" + Name + "' is not a basic block");
1760 else
1761 error(Loc, "'" + Name + "' defined with type '" +
1762 getTypeString(Val->getType()) + "' but expected '" +
1763 getTypeString(Ty) + "'");
1764 return nullptr;
1765}
1766
1767/// getGlobalVal - Get a value with the specified name or ID, creating a
1768/// forward reference record if needed. This can return null if the value
1769/// exists but does not have the right type.
1770GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1771 LocTy Loc) {
1773 if (!PTy) {
1774 error(Loc, "global variable reference must have pointer type");
1775 return nullptr;
1776 }
1777
1778 // Look this name up in the normal function symbol table.
1779 GlobalValue *Val =
1780 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1781
1782 // If this is a forward reference for the value, see if we already created a
1783 // forward ref record.
1784 if (!Val) {
1785 auto I = ForwardRefVals.find(Name);
1786 if (I != ForwardRefVals.end())
1787 Val = I->second.first;
1788 }
1789
1790 // If we have the value in the symbol table or fwd-ref table, return it.
1791 if (Val)
1793 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1794
1795 // Otherwise, create a new forward reference for this value and remember it.
1796 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1797 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1798 return FwdVal;
1799}
1800
1801GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1803 if (!PTy) {
1804 error(Loc, "global variable reference must have pointer type");
1805 return nullptr;
1806 }
1807
1808 GlobalValue *Val = NumberedVals.get(ID);
1809
1810 // If this is a forward reference for the value, see if we already created a
1811 // forward ref record.
1812 if (!Val) {
1813 auto I = ForwardRefValIDs.find(ID);
1814 if (I != ForwardRefValIDs.end())
1815 Val = I->second.first;
1816 }
1817
1818 // If we have the value in the symbol table or fwd-ref table, return it.
1819 if (Val)
1821 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1822
1823 // Otherwise, create a new forward reference for this value and remember it.
1824 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1825 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1826 return FwdVal;
1827}
1828
1829//===----------------------------------------------------------------------===//
1830// Comdat Reference/Resolution Routines.
1831//===----------------------------------------------------------------------===//
1832
1833Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1834 // Look this name up in the comdat symbol table.
1835 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1836 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1837 if (I != ComdatSymTab.end())
1838 return &I->second;
1839
1840 // Otherwise, create a new forward reference for this value and remember it.
1841 Comdat *C = M->getOrInsertComdat(Name);
1842 ForwardRefComdats[Name] = Loc;
1843 return C;
1844}
1845
1846//===----------------------------------------------------------------------===//
1847// Helper Routines.
1848//===----------------------------------------------------------------------===//
1849
1850/// parseToken - If the current token has the specified kind, eat it and return
1851/// success. Otherwise, emit the specified error and return failure.
1852bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1853 if (Lex.getKind() != T)
1854 return tokError(ErrMsg);
1855 Lex.Lex();
1856 return false;
1857}
1858
1859/// parseStringConstant
1860/// ::= StringConstant
1861bool LLParser::parseStringConstant(std::string &Result) {
1862 if (Lex.getKind() != lltok::StringConstant)
1863 return tokError("expected string constant");
1864 Result = Lex.getStrVal();
1865 Lex.Lex();
1866 return false;
1867}
1868
1869/// parseUInt32
1870/// ::= uint32
1871bool LLParser::parseUInt32(uint32_t &Val) {
1872 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1873 return tokError("expected integer");
1874 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1875 if (Val64 != unsigned(Val64))
1876 return tokError("expected 32-bit integer (too large)");
1877 Val = Val64;
1878 Lex.Lex();
1879 return false;
1880}
1881
1882/// parseUInt64
1883/// ::= uint64
1884bool LLParser::parseUInt64(uint64_t &Val) {
1885 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1886 return tokError("expected integer");
1887 Val = Lex.getAPSIntVal().getLimitedValue();
1888 Lex.Lex();
1889 return false;
1890}
1891
1892/// parseTLSModel
1893/// := 'localdynamic'
1894/// := 'initialexec'
1895/// := 'localexec'
1896bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1897 switch (Lex.getKind()) {
1898 default:
1899 return tokError("expected localdynamic, initialexec or localexec");
1902 break;
1905 break;
1908 break;
1909 }
1910
1911 Lex.Lex();
1912 return false;
1913}
1914
1915/// parseOptionalThreadLocal
1916/// := /*empty*/
1917/// := 'thread_local'
1918/// := 'thread_local' '(' tlsmodel ')'
1919bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1921 if (!EatIfPresent(lltok::kw_thread_local))
1922 return false;
1923
1925 if (Lex.getKind() == lltok::lparen) {
1926 Lex.Lex();
1927 return parseTLSModel(TLM) ||
1928 parseToken(lltok::rparen, "expected ')' after thread local model");
1929 }
1930 return false;
1931}
1932
1933/// parseOptionalAddrSpace
1934/// := /*empty*/
1935/// := 'addrspace' '(' uint32 ')'
1936bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1937 AddrSpace = DefaultAS;
1938 if (!EatIfPresent(lltok::kw_addrspace))
1939 return false;
1940
1941 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1942 if (Lex.getKind() == lltok::StringConstant) {
1943 auto AddrSpaceStr = Lex.getStrVal();
1944 if (AddrSpaceStr == "A") {
1945 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1946 } else if (AddrSpaceStr == "G") {
1947 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1948 } else if (AddrSpaceStr == "P") {
1949 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1950 } else {
1951 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1952 }
1953 Lex.Lex();
1954 return false;
1955 }
1956 if (Lex.getKind() != lltok::APSInt)
1957 return tokError("expected integer or string constant");
1958 SMLoc Loc = Lex.getLoc();
1959 if (parseUInt32(AddrSpace))
1960 return true;
1961 if (!isUInt<24>(AddrSpace))
1962 return error(Loc, "invalid address space, must be a 24-bit integer");
1963 return false;
1964 };
1965
1966 return parseToken(lltok::lparen, "expected '(' in address space") ||
1967 ParseAddrspaceValue(AddrSpace) ||
1968 parseToken(lltok::rparen, "expected ')' in address space");
1969}
1970
1971/// parseStringAttribute
1972/// := StringConstant
1973/// := StringConstant '=' StringConstant
1974bool LLParser::parseStringAttribute(AttrBuilder &B) {
1975 std::string Attr = Lex.getStrVal();
1976 Lex.Lex();
1977 std::string Val;
1978 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1979 return true;
1980 B.addAttribute(Attr, Val);
1981 return false;
1982}
1983
1984/// Parse a potentially empty list of parameter or return attributes.
1985bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1986 bool HaveError = false;
1987
1988 B.clear();
1989
1990 while (true) {
1991 lltok::Kind Token = Lex.getKind();
1992 if (Token == lltok::StringConstant) {
1993 if (parseStringAttribute(B))
1994 return true;
1995 continue;
1996 }
1997
1998 if (Token == lltok::kw_nocapture) {
1999 Lex.Lex();
2000 B.addCapturesAttr(CaptureInfo::none());
2001 continue;
2002 }
2003
2004 SMLoc Loc = Lex.getLoc();
2006 if (Attr == Attribute::None)
2007 return HaveError;
2008
2009 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2010 return true;
2011
2012 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2013 HaveError |= error(Loc, "this attribute does not apply to parameters");
2014 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2015 HaveError |= error(Loc, "this attribute does not apply to return values");
2016 }
2017}
2018
2019static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2020 HasLinkage = true;
2021 switch (Kind) {
2022 default:
2023 HasLinkage = false;
2025 case lltok::kw_private:
2027 case lltok::kw_internal:
2029 case lltok::kw_weak:
2031 case lltok::kw_weak_odr:
2033 case lltok::kw_linkonce:
2041 case lltok::kw_common:
2045 case lltok::kw_external:
2047 }
2048}
2049
2050/// parseOptionalLinkage
2051/// ::= /*empty*/
2052/// ::= 'private'
2053/// ::= 'internal'
2054/// ::= 'weak'
2055/// ::= 'weak_odr'
2056/// ::= 'linkonce'
2057/// ::= 'linkonce_odr'
2058/// ::= 'available_externally'
2059/// ::= 'appending'
2060/// ::= 'common'
2061/// ::= 'extern_weak'
2062/// ::= 'external'
2063bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2064 unsigned &Visibility,
2065 unsigned &DLLStorageClass, bool &DSOLocal) {
2066 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2067 if (HasLinkage)
2068 Lex.Lex();
2069 parseOptionalDSOLocal(DSOLocal);
2070 parseOptionalVisibility(Visibility);
2071 parseOptionalDLLStorageClass(DLLStorageClass);
2072
2073 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2074 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2075 }
2076
2077 return false;
2078}
2079
2080void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2081 switch (Lex.getKind()) {
2082 default:
2083 DSOLocal = false;
2084 break;
2086 DSOLocal = true;
2087 Lex.Lex();
2088 break;
2090 DSOLocal = false;
2091 Lex.Lex();
2092 break;
2093 }
2094}
2095
2096/// parseOptionalVisibility
2097/// ::= /*empty*/
2098/// ::= 'default'
2099/// ::= 'hidden'
2100/// ::= 'protected'
2101///
2102void LLParser::parseOptionalVisibility(unsigned &Res) {
2103 switch (Lex.getKind()) {
2104 default:
2106 return;
2107 case lltok::kw_default:
2109 break;
2110 case lltok::kw_hidden:
2112 break;
2115 break;
2116 }
2117 Lex.Lex();
2118}
2119
2120bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2122 switch (Kind) {
2123 default:
2124 return tokError("unknown import kind. Expect definition or declaration.");
2127 return false;
2130 return false;
2131 }
2132}
2133
2134/// parseOptionalDLLStorageClass
2135/// ::= /*empty*/
2136/// ::= 'dllimport'
2137/// ::= 'dllexport'
2138///
2139void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2140 switch (Lex.getKind()) {
2141 default:
2143 return;
2146 break;
2149 break;
2150 }
2151 Lex.Lex();
2152}
2153
2154/// parseOptionalCallingConv
2155/// ::= /*empty*/
2156/// ::= 'ccc'
2157/// ::= 'fastcc'
2158/// ::= 'intel_ocl_bicc'
2159/// ::= 'coldcc'
2160/// ::= 'cfguard_checkcc'
2161/// ::= 'x86_stdcallcc'
2162/// ::= 'x86_fastcallcc'
2163/// ::= 'x86_thiscallcc'
2164/// ::= 'x86_vectorcallcc'
2165/// ::= 'arm_apcscc'
2166/// ::= 'arm_aapcscc'
2167/// ::= 'arm_aapcs_vfpcc'
2168/// ::= 'aarch64_vector_pcs'
2169/// ::= 'aarch64_sve_vector_pcs'
2170/// ::= 'aarch64_sme_preservemost_from_x0'
2171/// ::= 'aarch64_sme_preservemost_from_x1'
2172/// ::= 'aarch64_sme_preservemost_from_x2'
2173/// ::= 'msp430_intrcc'
2174/// ::= 'avr_intrcc'
2175/// ::= 'avr_signalcc'
2176/// ::= 'ptx_kernel'
2177/// ::= 'ptx_device'
2178/// ::= 'spir_func'
2179/// ::= 'spir_kernel'
2180/// ::= 'x86_64_sysvcc'
2181/// ::= 'win64cc'
2182/// ::= 'anyregcc'
2183/// ::= 'preserve_mostcc'
2184/// ::= 'preserve_allcc'
2185/// ::= 'preserve_nonecc'
2186/// ::= 'ghccc'
2187/// ::= 'swiftcc'
2188/// ::= 'swifttailcc'
2189/// ::= 'x86_intrcc'
2190/// ::= 'hhvmcc'
2191/// ::= 'hhvm_ccc'
2192/// ::= 'cxx_fast_tlscc'
2193/// ::= 'amdgpu_vs'
2194/// ::= 'amdgpu_ls'
2195/// ::= 'amdgpu_hs'
2196/// ::= 'amdgpu_es'
2197/// ::= 'amdgpu_gs'
2198/// ::= 'amdgpu_ps'
2199/// ::= 'amdgpu_cs'
2200/// ::= 'amdgpu_cs_chain'
2201/// ::= 'amdgpu_cs_chain_preserve'
2202/// ::= 'amdgpu_kernel'
2203/// ::= 'tailcc'
2204/// ::= 'm68k_rtdcc'
2205/// ::= 'graalcc'
2206/// ::= 'riscv_vector_cc'
2207/// ::= 'riscv_vls_cc'
2208/// ::= 'cc' UINT
2209///
2210bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2211 switch (Lex.getKind()) {
2212 default: CC = CallingConv::C; return false;
2213 case lltok::kw_ccc: CC = CallingConv::C; break;
2214 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2215 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2228 break;
2231 break;
2234 break;
2237 break;
2247 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2248 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2252 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2253 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2256 case lltok::kw_hhvmcc:
2258 break;
2259 case lltok::kw_hhvm_ccc:
2261 break;
2273 break;
2276 break;
2280 break;
2281 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2283 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2286 break;
2288 // Default ABI_VLEN
2290 Lex.Lex();
2291 if (!EatIfPresent(lltok::lparen))
2292 break;
2293 uint32_t ABIVlen;
2294 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2295 return true;
2296 switch (ABIVlen) {
2297 default:
2298 return tokError("unknown RISC-V ABI VLEN");
2299#define CC_VLS_CASE(ABIVlen) \
2300 case ABIVlen: \
2301 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2302 break;
2303 CC_VLS_CASE(32)
2304 CC_VLS_CASE(64)
2305 CC_VLS_CASE(128)
2306 CC_VLS_CASE(256)
2307 CC_VLS_CASE(512)
2308 CC_VLS_CASE(1024)
2309 CC_VLS_CASE(2048)
2310 CC_VLS_CASE(4096)
2311 CC_VLS_CASE(8192)
2312 CC_VLS_CASE(16384)
2313 CC_VLS_CASE(32768)
2314 CC_VLS_CASE(65536)
2315#undef CC_VLS_CASE
2316 }
2317 return false;
2320 break;
2323 break;
2326 break;
2327 case lltok::kw_cc: {
2328 Lex.Lex();
2329 return parseUInt32(CC);
2330 }
2331 }
2332
2333 Lex.Lex();
2334 return false;
2335}
2336
2337/// parseMetadataAttachment
2338/// ::= !dbg !42
2339bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2340 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2341
2342 std::string Name = Lex.getStrVal();
2343 Kind = M->getMDKindID(Name);
2344 Lex.Lex();
2345
2346 return parseMDNode(MD);
2347}
2348
2349/// parseInstructionMetadata
2350/// ::= !dbg !42 (',' !dbg !57)*
2351bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2352 do {
2353 if (Lex.getKind() != lltok::MetadataVar)
2354 return tokError("expected metadata after comma");
2355
2356 unsigned MDK;
2357 MDNode *N;
2358 if (parseMetadataAttachment(MDK, N))
2359 return true;
2360
2361 if (MDK == LLVMContext::MD_DIAssignID)
2362 TempDIAssignIDAttachments[N].push_back(&Inst);
2363 else
2364 Inst.setMetadata(MDK, N);
2365
2366 if (MDK == LLVMContext::MD_tbaa)
2367 InstsWithTBAATag.push_back(&Inst);
2368
2369 // If this is the end of the list, we're done.
2370 } while (EatIfPresent(lltok::comma));
2371 return false;
2372}
2373
2374/// parseGlobalObjectMetadataAttachment
2375/// ::= !dbg !57
2376bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2377 unsigned MDK;
2378 MDNode *N;
2379 if (parseMetadataAttachment(MDK, N))
2380 return true;
2381
2382 GO.addMetadata(MDK, *N);
2383 return false;
2384}
2385
2386/// parseOptionalFunctionMetadata
2387/// ::= (!dbg !57)*
2388bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2389 while (Lex.getKind() == lltok::MetadataVar)
2390 if (parseGlobalObjectMetadataAttachment(F))
2391 return true;
2392 return false;
2393}
2394
2395/// parseOptionalAlignment
2396/// ::= /* empty */
2397/// ::= 'align' 4
2398bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2399 Alignment = std::nullopt;
2400 if (!EatIfPresent(lltok::kw_align))
2401 return false;
2402 LocTy AlignLoc = Lex.getLoc();
2403 uint64_t Value = 0;
2404
2405 LocTy ParenLoc = Lex.getLoc();
2406 bool HaveParens = false;
2407 if (AllowParens) {
2408 if (EatIfPresent(lltok::lparen))
2409 HaveParens = true;
2410 }
2411
2412 if (parseUInt64(Value))
2413 return true;
2414
2415 if (HaveParens && !EatIfPresent(lltok::rparen))
2416 return error(ParenLoc, "expected ')'");
2417
2418 if (!isPowerOf2_64(Value))
2419 return error(AlignLoc, "alignment is not a power of two");
2421 return error(AlignLoc, "huge alignments are not supported yet");
2422 Alignment = Align(Value);
2423 return false;
2424}
2425
2426/// parseOptionalCodeModel
2427/// ::= /* empty */
2428/// ::= 'code_model' "large"
2429bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2430 Lex.Lex();
2431 auto StrVal = Lex.getStrVal();
2432 auto ErrMsg = "expected global code model string";
2433 if (StrVal == "tiny")
2434 model = CodeModel::Tiny;
2435 else if (StrVal == "small")
2436 model = CodeModel::Small;
2437 else if (StrVal == "kernel")
2438 model = CodeModel::Kernel;
2439 else if (StrVal == "medium")
2440 model = CodeModel::Medium;
2441 else if (StrVal == "large")
2442 model = CodeModel::Large;
2443 else
2444 return tokError(ErrMsg);
2445 if (parseToken(lltok::StringConstant, ErrMsg))
2446 return true;
2447 return false;
2448}
2449
2450/// parseOptionalDerefAttrBytes
2451/// ::= /* empty */
2452/// ::= AttrKind '(' 4 ')'
2453///
2454/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2455bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2456 uint64_t &Bytes) {
2457 assert((AttrKind == lltok::kw_dereferenceable ||
2458 AttrKind == lltok::kw_dereferenceable_or_null) &&
2459 "contract!");
2460
2461 Bytes = 0;
2462 if (!EatIfPresent(AttrKind))
2463 return false;
2464 LocTy ParenLoc = Lex.getLoc();
2465 if (!EatIfPresent(lltok::lparen))
2466 return error(ParenLoc, "expected '('");
2467 LocTy DerefLoc = Lex.getLoc();
2468 if (parseUInt64(Bytes))
2469 return true;
2470 ParenLoc = Lex.getLoc();
2471 if (!EatIfPresent(lltok::rparen))
2472 return error(ParenLoc, "expected ')'");
2473 if (!Bytes)
2474 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2475 return false;
2476}
2477
2478bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2479 Lex.Lex();
2481 if (!EatIfPresent(lltok::lparen))
2482 return false;
2483 LocTy KindLoc = Lex.getLoc();
2484 if (Lex.getKind() == lltok::kw_sync)
2486 else if (Lex.getKind() == lltok::kw_async)
2488 else
2489 return error(KindLoc, "expected unwind table kind");
2490 Lex.Lex();
2491 return parseToken(lltok::rparen, "expected ')'");
2492}
2493
2494bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2495 Lex.Lex();
2496 LocTy ParenLoc = Lex.getLoc();
2497 if (!EatIfPresent(lltok::lparen))
2498 return error(ParenLoc, "expected '('");
2499 LocTy KindLoc = Lex.getLoc();
2500 std::string Arg;
2501 if (parseStringConstant(Arg))
2502 return error(KindLoc, "expected allockind value");
2503 for (StringRef A : llvm::split(Arg, ",")) {
2504 if (A == "alloc") {
2506 } else if (A == "realloc") {
2508 } else if (A == "free") {
2510 } else if (A == "uninitialized") {
2512 } else if (A == "zeroed") {
2514 } else if (A == "aligned") {
2516 } else {
2517 return error(KindLoc, Twine("unknown allockind ") + A);
2518 }
2519 }
2520 ParenLoc = Lex.getLoc();
2521 if (!EatIfPresent(lltok::rparen))
2522 return error(ParenLoc, "expected ')'");
2523 if (Kind == AllocFnKind::Unknown)
2524 return error(KindLoc, "expected allockind value");
2525 return false;
2526}
2527
2528static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2529 switch (Tok) {
2530 case lltok::kw_argmem:
2531 return IRMemLocation::ArgMem;
2534 case lltok::kw_errnomem:
2536 default:
2537 return std::nullopt;
2538 }
2539}
2540
2541static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2542 switch (Tok) {
2543 case lltok::kw_none:
2544 return ModRefInfo::NoModRef;
2545 case lltok::kw_read:
2546 return ModRefInfo::Ref;
2547 case lltok::kw_write:
2548 return ModRefInfo::Mod;
2550 return ModRefInfo::ModRef;
2551 default:
2552 return std::nullopt;
2553 }
2554}
2555
2556std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2558
2559 // We use syntax like memory(argmem: read), so the colon should not be
2560 // interpreted as a label terminator.
2561 Lex.setIgnoreColonInIdentifiers(true);
2562 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2563
2564 Lex.Lex();
2565 if (!EatIfPresent(lltok::lparen)) {
2566 tokError("expected '('");
2567 return std::nullopt;
2568 }
2569
2570 bool SeenLoc = false;
2571 do {
2572 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2573 if (Loc) {
2574 Lex.Lex();
2575 if (!EatIfPresent(lltok::colon)) {
2576 tokError("expected ':' after location");
2577 return std::nullopt;
2578 }
2579 }
2580
2581 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2582 if (!MR) {
2583 if (!Loc)
2584 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2585 "or access kind (none, read, write, readwrite)");
2586 else
2587 tokError("expected access kind (none, read, write, readwrite)");
2588 return std::nullopt;
2589 }
2590
2591 Lex.Lex();
2592 if (Loc) {
2593 SeenLoc = true;
2594 ME = ME.getWithModRef(*Loc, *MR);
2595 } else {
2596 if (SeenLoc) {
2597 tokError("default access kind must be specified first");
2598 return std::nullopt;
2599 }
2600 ME = MemoryEffects(*MR);
2601 }
2602
2603 if (EatIfPresent(lltok::rparen))
2604 return ME;
2605 } while (EatIfPresent(lltok::comma));
2606
2607 tokError("unterminated memory attribute");
2608 return std::nullopt;
2609}
2610
2611static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2612 switch (Tok) {
2613 case lltok::kw_all:
2614 return fcAllFlags;
2615 case lltok::kw_nan:
2616 return fcNan;
2617 case lltok::kw_snan:
2618 return fcSNan;
2619 case lltok::kw_qnan:
2620 return fcQNan;
2621 case lltok::kw_inf:
2622 return fcInf;
2623 case lltok::kw_ninf:
2624 return fcNegInf;
2625 case lltok::kw_pinf:
2626 return fcPosInf;
2627 case lltok::kw_norm:
2628 return fcNormal;
2629 case lltok::kw_nnorm:
2630 return fcNegNormal;
2631 case lltok::kw_pnorm:
2632 return fcPosNormal;
2633 case lltok::kw_sub:
2634 return fcSubnormal;
2635 case lltok::kw_nsub:
2636 return fcNegSubnormal;
2637 case lltok::kw_psub:
2638 return fcPosSubnormal;
2639 case lltok::kw_zero:
2640 return fcZero;
2641 case lltok::kw_nzero:
2642 return fcNegZero;
2643 case lltok::kw_pzero:
2644 return fcPosZero;
2645 default:
2646 return 0;
2647 }
2648}
2649
2650unsigned LLParser::parseNoFPClassAttr() {
2651 unsigned Mask = fcNone;
2652
2653 Lex.Lex();
2654 if (!EatIfPresent(lltok::lparen)) {
2655 tokError("expected '('");
2656 return 0;
2657 }
2658
2659 do {
2660 uint64_t Value = 0;
2661 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2662 if (TestMask != 0) {
2663 Mask |= TestMask;
2664 // TODO: Disallow overlapping masks to avoid copy paste errors
2665 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2666 !parseUInt64(Value)) {
2667 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2668 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2669 return 0;
2670 }
2671
2672 if (!EatIfPresent(lltok::rparen)) {
2673 error(Lex.getLoc(), "expected ')'");
2674 return 0;
2675 }
2676
2677 return Value;
2678 } else {
2679 error(Lex.getLoc(), "expected nofpclass test mask");
2680 return 0;
2681 }
2682
2683 Lex.Lex();
2684 if (EatIfPresent(lltok::rparen))
2685 return Mask;
2686 } while (1);
2687
2688 llvm_unreachable("unterminated nofpclass attribute");
2689}
2690
2691/// parseOptionalCommaAlign
2692/// ::=
2693/// ::= ',' align 4
2694///
2695/// This returns with AteExtraComma set to true if it ate an excess comma at the
2696/// end.
2697bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2698 bool &AteExtraComma) {
2699 AteExtraComma = false;
2700 while (EatIfPresent(lltok::comma)) {
2701 // Metadata at the end is an early exit.
2702 if (Lex.getKind() == lltok::MetadataVar) {
2703 AteExtraComma = true;
2704 return false;
2705 }
2706
2707 if (Lex.getKind() != lltok::kw_align)
2708 return error(Lex.getLoc(), "expected metadata or 'align'");
2709
2710 if (parseOptionalAlignment(Alignment))
2711 return true;
2712 }
2713
2714 return false;
2715}
2716
2717/// parseOptionalCommaAddrSpace
2718/// ::=
2719/// ::= ',' addrspace(1)
2720///
2721/// This returns with AteExtraComma set to true if it ate an excess comma at the
2722/// end.
2723bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2724 bool &AteExtraComma) {
2725 AteExtraComma = false;
2726 while (EatIfPresent(lltok::comma)) {
2727 // Metadata at the end is an early exit.
2728 if (Lex.getKind() == lltok::MetadataVar) {
2729 AteExtraComma = true;
2730 return false;
2731 }
2732
2733 Loc = Lex.getLoc();
2734 if (Lex.getKind() != lltok::kw_addrspace)
2735 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2736
2737 if (parseOptionalAddrSpace(AddrSpace))
2738 return true;
2739 }
2740
2741 return false;
2742}
2743
2744bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2745 std::optional<unsigned> &HowManyArg) {
2746 Lex.Lex();
2747
2748 auto StartParen = Lex.getLoc();
2749 if (!EatIfPresent(lltok::lparen))
2750 return error(StartParen, "expected '('");
2751
2752 if (parseUInt32(BaseSizeArg))
2753 return true;
2754
2755 if (EatIfPresent(lltok::comma)) {
2756 auto HowManyAt = Lex.getLoc();
2757 unsigned HowMany;
2758 if (parseUInt32(HowMany))
2759 return true;
2760 if (HowMany == BaseSizeArg)
2761 return error(HowManyAt,
2762 "'allocsize' indices can't refer to the same parameter");
2763 HowManyArg = HowMany;
2764 } else
2765 HowManyArg = std::nullopt;
2766
2767 auto EndParen = Lex.getLoc();
2768 if (!EatIfPresent(lltok::rparen))
2769 return error(EndParen, "expected ')'");
2770 return false;
2771}
2772
2773bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2774 unsigned &MaxValue) {
2775 Lex.Lex();
2776
2777 auto StartParen = Lex.getLoc();
2778 if (!EatIfPresent(lltok::lparen))
2779 return error(StartParen, "expected '('");
2780
2781 if (parseUInt32(MinValue))
2782 return true;
2783
2784 if (EatIfPresent(lltok::comma)) {
2785 if (parseUInt32(MaxValue))
2786 return true;
2787 } else
2788 MaxValue = MinValue;
2789
2790 auto EndParen = Lex.getLoc();
2791 if (!EatIfPresent(lltok::rparen))
2792 return error(EndParen, "expected ')'");
2793 return false;
2794}
2795
2796/// parseScopeAndOrdering
2797/// if isAtomic: ::= SyncScope? AtomicOrdering
2798/// else: ::=
2799///
2800/// This sets Scope and Ordering to the parsed values.
2801bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2802 AtomicOrdering &Ordering) {
2803 if (!IsAtomic)
2804 return false;
2805
2806 return parseScope(SSID) || parseOrdering(Ordering);
2807}
2808
2809/// parseScope
2810/// ::= syncscope("singlethread" | "<target scope>")?
2811///
2812/// This sets synchronization scope ID to the ID of the parsed value.
2813bool LLParser::parseScope(SyncScope::ID &SSID) {
2814 SSID = SyncScope::System;
2815 if (EatIfPresent(lltok::kw_syncscope)) {
2816 auto StartParenAt = Lex.getLoc();
2817 if (!EatIfPresent(lltok::lparen))
2818 return error(StartParenAt, "Expected '(' in syncscope");
2819
2820 std::string SSN;
2821 auto SSNAt = Lex.getLoc();
2822 if (parseStringConstant(SSN))
2823 return error(SSNAt, "Expected synchronization scope name");
2824
2825 auto EndParenAt = Lex.getLoc();
2826 if (!EatIfPresent(lltok::rparen))
2827 return error(EndParenAt, "Expected ')' in syncscope");
2828
2829 SSID = Context.getOrInsertSyncScopeID(SSN);
2830 }
2831
2832 return false;
2833}
2834
2835/// parseOrdering
2836/// ::= AtomicOrdering
2837///
2838/// This sets Ordering to the parsed value.
2839bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2840 switch (Lex.getKind()) {
2841 default:
2842 return tokError("Expected ordering on atomic instruction");
2845 // Not specified yet:
2846 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2850 case lltok::kw_seq_cst:
2852 break;
2853 }
2854 Lex.Lex();
2855 return false;
2856}
2857
2858/// parseOptionalStackAlignment
2859/// ::= /* empty */
2860/// ::= 'alignstack' '(' 4 ')'
2861bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2862 Alignment = 0;
2863 if (!EatIfPresent(lltok::kw_alignstack))
2864 return false;
2865 LocTy ParenLoc = Lex.getLoc();
2866 if (!EatIfPresent(lltok::lparen))
2867 return error(ParenLoc, "expected '('");
2868 LocTy AlignLoc = Lex.getLoc();
2869 if (parseUInt32(Alignment))
2870 return true;
2871 ParenLoc = Lex.getLoc();
2872 if (!EatIfPresent(lltok::rparen))
2873 return error(ParenLoc, "expected ')'");
2874 if (!isPowerOf2_32(Alignment))
2875 return error(AlignLoc, "stack alignment is not a power of two");
2876 return false;
2877}
2878
2879/// parseIndexList - This parses the index list for an insert/extractvalue
2880/// instruction. This sets AteExtraComma in the case where we eat an extra
2881/// comma at the end of the line and find that it is followed by metadata.
2882/// Clients that don't allow metadata can call the version of this function that
2883/// only takes one argument.
2884///
2885/// parseIndexList
2886/// ::= (',' uint32)+
2887///
2888bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2889 bool &AteExtraComma) {
2890 AteExtraComma = false;
2891
2892 if (Lex.getKind() != lltok::comma)
2893 return tokError("expected ',' as start of index list");
2894
2895 while (EatIfPresent(lltok::comma)) {
2896 if (Lex.getKind() == lltok::MetadataVar) {
2897 if (Indices.empty())
2898 return tokError("expected index");
2899 AteExtraComma = true;
2900 return false;
2901 }
2902 unsigned Idx = 0;
2903 if (parseUInt32(Idx))
2904 return true;
2905 Indices.push_back(Idx);
2906 }
2907
2908 return false;
2909}
2910
2911//===----------------------------------------------------------------------===//
2912// Type Parsing.
2913//===----------------------------------------------------------------------===//
2914
2915/// parseType - parse a type.
2916bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2917 SMLoc TypeLoc = Lex.getLoc();
2918 switch (Lex.getKind()) {
2919 default:
2920 return tokError(Msg);
2921 case lltok::Type:
2922 // Type ::= 'float' | 'void' (etc)
2923 Result = Lex.getTyVal();
2924 Lex.Lex();
2925
2926 // Handle "ptr" opaque pointer type.
2927 //
2928 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2929 if (Result->isPointerTy()) {
2930 unsigned AddrSpace;
2931 if (parseOptionalAddrSpace(AddrSpace))
2932 return true;
2933 Result = PointerType::get(getContext(), AddrSpace);
2934
2935 // Give a nice error for 'ptr*'.
2936 if (Lex.getKind() == lltok::star)
2937 return tokError("ptr* is invalid - use ptr instead");
2938
2939 // Fall through to parsing the type suffixes only if this 'ptr' is a
2940 // function return. Otherwise, return success, implicitly rejecting other
2941 // suffixes.
2942 if (Lex.getKind() != lltok::lparen)
2943 return false;
2944 }
2945 break;
2946 case lltok::kw_target: {
2947 // Type ::= TargetExtType
2948 if (parseTargetExtType(Result))
2949 return true;
2950 break;
2951 }
2952 case lltok::lbrace:
2953 // Type ::= StructType
2954 if (parseAnonStructType(Result, false))
2955 return true;
2956 break;
2957 case lltok::lsquare:
2958 // Type ::= '[' ... ']'
2959 Lex.Lex(); // eat the lsquare.
2960 if (parseArrayVectorType(Result, false))
2961 return true;
2962 break;
2963 case lltok::less: // Either vector or packed struct.
2964 // Type ::= '<' ... '>'
2965 Lex.Lex();
2966 if (Lex.getKind() == lltok::lbrace) {
2967 if (parseAnonStructType(Result, true) ||
2968 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2969 return true;
2970 } else if (parseArrayVectorType(Result, true))
2971 return true;
2972 break;
2973 case lltok::LocalVar: {
2974 // Type ::= %foo
2975 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2976
2977 // If the type hasn't been defined yet, create a forward definition and
2978 // remember where that forward def'n was seen (in case it never is defined).
2979 if (!Entry.first) {
2980 Entry.first = StructType::create(Context, Lex.getStrVal());
2981 Entry.second = Lex.getLoc();
2982 }
2983 Result = Entry.first;
2984 Lex.Lex();
2985 break;
2986 }
2987
2988 case lltok::LocalVarID: {
2989 // Type ::= %4
2990 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2991
2992 // If the type hasn't been defined yet, create a forward definition and
2993 // remember where that forward def'n was seen (in case it never is defined).
2994 if (!Entry.first) {
2995 Entry.first = StructType::create(Context);
2996 Entry.second = Lex.getLoc();
2997 }
2998 Result = Entry.first;
2999 Lex.Lex();
3000 break;
3001 }
3002 }
3003
3004 // parse the type suffixes.
3005 while (true) {
3006 switch (Lex.getKind()) {
3007 // End of type.
3008 default:
3009 if (!AllowVoid && Result->isVoidTy())
3010 return error(TypeLoc, "void type only allowed for function results");
3011 return false;
3012
3013 // Type ::= Type '*'
3014 case lltok::star:
3015 if (Result->isLabelTy())
3016 return tokError("basic block pointers are invalid");
3017 if (Result->isVoidTy())
3018 return tokError("pointers to void are invalid - use i8* instead");
3020 return tokError("pointer to this type is invalid");
3021 Result = PointerType::getUnqual(Context);
3022 Lex.Lex();
3023 break;
3024
3025 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3026 case lltok::kw_addrspace: {
3027 if (Result->isLabelTy())
3028 return tokError("basic block pointers are invalid");
3029 if (Result->isVoidTy())
3030 return tokError("pointers to void are invalid; use i8* instead");
3032 return tokError("pointer to this type is invalid");
3033 unsigned AddrSpace;
3034 if (parseOptionalAddrSpace(AddrSpace) ||
3035 parseToken(lltok::star, "expected '*' in address space"))
3036 return true;
3037
3038 Result = PointerType::get(Context, AddrSpace);
3039 break;
3040 }
3041
3042 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3043 case lltok::lparen:
3044 if (parseFunctionType(Result))
3045 return true;
3046 break;
3047 }
3048 }
3049}
3050
3051/// parseParameterList
3052/// ::= '(' ')'
3053/// ::= '(' Arg (',' Arg)* ')'
3054/// Arg
3055/// ::= Type OptionalAttributes Value OptionalAttributes
3056bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3057 PerFunctionState &PFS, bool IsMustTailCall,
3058 bool InVarArgsFunc) {
3059 if (parseToken(lltok::lparen, "expected '(' in call"))
3060 return true;
3061
3062 while (Lex.getKind() != lltok::rparen) {
3063 // If this isn't the first argument, we need a comma.
3064 if (!ArgList.empty() &&
3065 parseToken(lltok::comma, "expected ',' in argument list"))
3066 return true;
3067
3068 // parse an ellipsis if this is a musttail call in a variadic function.
3069 if (Lex.getKind() == lltok::dotdotdot) {
3070 const char *Msg = "unexpected ellipsis in argument list for ";
3071 if (!IsMustTailCall)
3072 return tokError(Twine(Msg) + "non-musttail call");
3073 if (!InVarArgsFunc)
3074 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3075 Lex.Lex(); // Lex the '...', it is purely for readability.
3076 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3077 }
3078
3079 // parse the argument.
3080 LocTy ArgLoc;
3081 Type *ArgTy = nullptr;
3082 Value *V;
3083 if (parseType(ArgTy, ArgLoc))
3084 return true;
3086 return error(ArgLoc, "invalid type for function argument");
3087
3088 AttrBuilder ArgAttrs(M->getContext());
3089
3090 if (ArgTy->isMetadataTy()) {
3091 if (parseMetadataAsValue(V, PFS))
3092 return true;
3093 } else {
3094 // Otherwise, handle normal operands.
3095 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3096 return true;
3097 }
3098 ArgList.push_back(ParamInfo(
3099 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3100 }
3101
3102 if (IsMustTailCall && InVarArgsFunc)
3103 return tokError("expected '...' at end of argument list for musttail call "
3104 "in varargs function");
3105
3106 Lex.Lex(); // Lex the ')'.
3107 return false;
3108}
3109
3110/// parseRequiredTypeAttr
3111/// ::= attrname(<ty>)
3112bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3113 Attribute::AttrKind AttrKind) {
3114 Type *Ty = nullptr;
3115 if (!EatIfPresent(AttrToken))
3116 return true;
3117 if (!EatIfPresent(lltok::lparen))
3118 return error(Lex.getLoc(), "expected '('");
3119 if (parseType(Ty))
3120 return true;
3121 if (!EatIfPresent(lltok::rparen))
3122 return error(Lex.getLoc(), "expected ')'");
3123
3124 B.addTypeAttr(AttrKind, Ty);
3125 return false;
3126}
3127
3128/// parseRangeAttr
3129/// ::= range(<ty> <n>,<n>)
3130bool LLParser::parseRangeAttr(AttrBuilder &B) {
3131 Lex.Lex();
3132
3133 APInt Lower;
3134 APInt Upper;
3135 Type *Ty = nullptr;
3136 LocTy TyLoc;
3137
3138 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3139 if (Lex.getKind() != lltok::APSInt)
3140 return tokError("expected integer");
3141 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3142 return tokError(
3143 "integer is too large for the bit width of specified type");
3144 Val = Lex.getAPSIntVal().extend(BitWidth);
3145 Lex.Lex();
3146 return false;
3147 };
3148
3149 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3150 return true;
3151 if (!Ty->isIntegerTy())
3152 return error(TyLoc, "the range must have integer type!");
3153
3154 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3155
3156 if (ParseAPSInt(BitWidth, Lower) ||
3157 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3158 return true;
3159 if (Lower == Upper && !Lower.isZero())
3160 return tokError("the range represent the empty set but limits aren't 0!");
3161
3162 if (parseToken(lltok::rparen, "expected ')'"))
3163 return true;
3164
3165 B.addRangeAttr(ConstantRange(Lower, Upper));
3166 return false;
3167}
3168
3169/// parseInitializesAttr
3170/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3171bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3172 Lex.Lex();
3173
3174 auto ParseAPSInt = [&](APInt &Val) {
3175 if (Lex.getKind() != lltok::APSInt)
3176 return tokError("expected integer");
3177 Val = Lex.getAPSIntVal().extend(64);
3178 Lex.Lex();
3179 return false;
3180 };
3181
3182 if (parseToken(lltok::lparen, "expected '('"))
3183 return true;
3184
3186 // Parse each constant range.
3187 do {
3188 APInt Lower, Upper;
3189 if (parseToken(lltok::lparen, "expected '('"))
3190 return true;
3191
3192 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3193 ParseAPSInt(Upper))
3194 return true;
3195
3196 if (Lower == Upper)
3197 return tokError("the range should not represent the full or empty set!");
3198
3199 if (parseToken(lltok::rparen, "expected ')'"))
3200 return true;
3201
3202 RangeList.push_back(ConstantRange(Lower, Upper));
3203 } while (EatIfPresent(lltok::comma));
3204
3205 if (parseToken(lltok::rparen, "expected ')'"))
3206 return true;
3207
3208 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3209 if (!CRLOrNull.has_value())
3210 return tokError("Invalid (unordered or overlapping) range list");
3211 B.addInitializesAttr(*CRLOrNull);
3212 return false;
3213}
3214
3215bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3217 std::optional<CaptureComponents> Ret;
3218
3219 // We use syntax like captures(ret: address, provenance), so the colon
3220 // should not be interpreted as a label terminator.
3221 Lex.setIgnoreColonInIdentifiers(true);
3222 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3223
3224 Lex.Lex();
3225 if (parseToken(lltok::lparen, "expected '('"))
3226 return true;
3227
3228 CaptureComponents *Current = &Other;
3229 bool SeenComponent = false;
3230 while (true) {
3231 if (EatIfPresent(lltok::kw_ret)) {
3232 if (parseToken(lltok::colon, "expected ':'"))
3233 return true;
3234 if (Ret)
3235 return tokError("duplicate 'ret' location");
3237 Current = &*Ret;
3238 SeenComponent = false;
3239 }
3240
3241 if (EatIfPresent(lltok::kw_none)) {
3242 if (SeenComponent)
3243 return tokError("cannot use 'none' with other component");
3244 *Current = CaptureComponents::None;
3245 } else {
3246 if (SeenComponent && capturesNothing(*Current))
3247 return tokError("cannot use 'none' with other component");
3248
3249 if (EatIfPresent(lltok::kw_address_is_null))
3251 else if (EatIfPresent(lltok::kw_address))
3252 *Current |= CaptureComponents::Address;
3253 else if (EatIfPresent(lltok::kw_provenance))
3255 else if (EatIfPresent(lltok::kw_read_provenance))
3257 else
3258 return tokError("expected one of 'none', 'address', 'address_is_null', "
3259 "'provenance' or 'read_provenance'");
3260 }
3261
3262 SeenComponent = true;
3263 if (EatIfPresent(lltok::rparen))
3264 break;
3265
3266 if (parseToken(lltok::comma, "expected ',' or ')'"))
3267 return true;
3268 }
3269
3270 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3271 return false;
3272}
3273
3274/// parseOptionalOperandBundles
3275/// ::= /*empty*/
3276/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3277///
3278/// OperandBundle
3279/// ::= bundle-tag '(' ')'
3280/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3281///
3282/// bundle-tag ::= String Constant
3283bool LLParser::parseOptionalOperandBundles(
3284 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3285 LocTy BeginLoc = Lex.getLoc();
3286 if (!EatIfPresent(lltok::lsquare))
3287 return false;
3288
3289 while (Lex.getKind() != lltok::rsquare) {
3290 // If this isn't the first operand bundle, we need a comma.
3291 if (!BundleList.empty() &&
3292 parseToken(lltok::comma, "expected ',' in input list"))
3293 return true;
3294
3295 std::string Tag;
3296 if (parseStringConstant(Tag))
3297 return true;
3298
3299 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3300 return true;
3301
3302 std::vector<Value *> Inputs;
3303 while (Lex.getKind() != lltok::rparen) {
3304 // If this isn't the first input, we need a comma.
3305 if (!Inputs.empty() &&
3306 parseToken(lltok::comma, "expected ',' in input list"))
3307 return true;
3308
3309 Type *Ty = nullptr;
3310 Value *Input = nullptr;
3311 if (parseType(Ty))
3312 return true;
3313 if (Ty->isMetadataTy()) {
3314 if (parseMetadataAsValue(Input, PFS))
3315 return true;
3316 } else if (parseValue(Ty, Input, PFS)) {
3317 return true;
3318 }
3319 Inputs.push_back(Input);
3320 }
3321
3322 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3323
3324 Lex.Lex(); // Lex the ')'.
3325 }
3326
3327 if (BundleList.empty())
3328 return error(BeginLoc, "operand bundle set must not be empty");
3329
3330 Lex.Lex(); // Lex the ']'.
3331 return false;
3332}
3333
3334bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3335 unsigned NextID, unsigned ID) {
3336 if (ID < NextID)
3337 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3338 Twine(NextID) + "' or greater");
3339
3340 return false;
3341}
3342
3343/// parseArgumentList - parse the argument list for a function type or function
3344/// prototype.
3345/// ::= '(' ArgTypeListI ')'
3346/// ArgTypeListI
3347/// ::= /*empty*/
3348/// ::= '...'
3349/// ::= ArgTypeList ',' '...'
3350/// ::= ArgType (',' ArgType)*
3351///
3352bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3353 SmallVectorImpl<unsigned> &UnnamedArgNums,
3354 bool &IsVarArg) {
3355 unsigned CurValID = 0;
3356 IsVarArg = false;
3357 assert(Lex.getKind() == lltok::lparen);
3358 Lex.Lex(); // eat the (.
3359
3360 if (Lex.getKind() != lltok::rparen) {
3361 do {
3362 // Handle ... at end of arg list.
3363 if (EatIfPresent(lltok::dotdotdot)) {
3364 IsVarArg = true;
3365 break;
3366 }
3367
3368 // Otherwise must be an argument type.
3369 LocTy TypeLoc = Lex.getLoc();
3370 Type *ArgTy = nullptr;
3371 AttrBuilder Attrs(M->getContext());
3372 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3373 return true;
3374
3375 if (ArgTy->isVoidTy())
3376 return error(TypeLoc, "argument can not have void type");
3377
3378 std::string Name;
3379 if (Lex.getKind() == lltok::LocalVar) {
3380 Name = Lex.getStrVal();
3381 Lex.Lex();
3382 } else {
3383 unsigned ArgID;
3384 if (Lex.getKind() == lltok::LocalVarID) {
3385 ArgID = Lex.getUIntVal();
3386 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3387 return true;
3388 Lex.Lex();
3389 } else {
3390 ArgID = CurValID;
3391 }
3392 UnnamedArgNums.push_back(ArgID);
3393 CurValID = ArgID + 1;
3394 }
3395
3397 return error(TypeLoc, "invalid type for function argument");
3398
3399 ArgList.emplace_back(TypeLoc, ArgTy,
3400 AttributeSet::get(ArgTy->getContext(), Attrs),
3401 std::move(Name));
3402 } while (EatIfPresent(lltok::comma));
3403 }
3404
3405 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3406}
3407
3408/// parseFunctionType
3409/// ::= Type ArgumentList OptionalAttrs
3410bool LLParser::parseFunctionType(Type *&Result) {
3411 assert(Lex.getKind() == lltok::lparen);
3412
3414 return tokError("invalid function return type");
3415
3417 bool IsVarArg;
3418 SmallVector<unsigned> UnnamedArgNums;
3419 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3420 return true;
3421
3422 // Reject names on the arguments lists.
3423 for (const ArgInfo &Arg : ArgList) {
3424 if (!Arg.Name.empty())
3425 return error(Arg.Loc, "argument name invalid in function type");
3426 if (Arg.Attrs.hasAttributes())
3427 return error(Arg.Loc, "argument attributes invalid in function type");
3428 }
3429
3430 SmallVector<Type*, 16> ArgListTy;
3431 for (const ArgInfo &Arg : ArgList)
3432 ArgListTy.push_back(Arg.Ty);
3433
3434 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3435 return false;
3436}
3437
3438/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3439/// other structs.
3440bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3442 if (parseStructBody(Elts))
3443 return true;
3444
3445 Result = StructType::get(Context, Elts, Packed);
3446 return false;
3447}
3448
3449/// parseStructDefinition - parse a struct in a 'type' definition.
3450bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3451 std::pair<Type *, LocTy> &Entry,
3452 Type *&ResultTy) {
3453 // If the type was already defined, diagnose the redefinition.
3454 if (Entry.first && !Entry.second.isValid())
3455 return error(TypeLoc, "redefinition of type");
3456
3457 // If we have opaque, just return without filling in the definition for the
3458 // struct. This counts as a definition as far as the .ll file goes.
3459 if (EatIfPresent(lltok::kw_opaque)) {
3460 // This type is being defined, so clear the location to indicate this.
3461 Entry.second = SMLoc();
3462
3463 // If this type number has never been uttered, create it.
3464 if (!Entry.first)
3465 Entry.first = StructType::create(Context, Name);
3466 ResultTy = Entry.first;
3467 return false;
3468 }
3469
3470 // If the type starts with '<', then it is either a packed struct or a vector.
3471 bool isPacked = EatIfPresent(lltok::less);
3472
3473 // If we don't have a struct, then we have a random type alias, which we
3474 // accept for compatibility with old files. These types are not allowed to be
3475 // forward referenced and not allowed to be recursive.
3476 if (Lex.getKind() != lltok::lbrace) {
3477 if (Entry.first)
3478 return error(TypeLoc, "forward references to non-struct type");
3479
3480 ResultTy = nullptr;
3481 if (isPacked)
3482 return parseArrayVectorType(ResultTy, true);
3483 return parseType(ResultTy);
3484 }
3485
3486 // This type is being defined, so clear the location to indicate this.
3487 Entry.second = SMLoc();
3488
3489 // If this type number has never been uttered, create it.
3490 if (!Entry.first)
3491 Entry.first = StructType::create(Context, Name);
3492
3493 StructType *STy = cast<StructType>(Entry.first);
3494
3496 if (parseStructBody(Body) ||
3497 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3498 return true;
3499
3500 if (auto E = STy->setBodyOrError(Body, isPacked))
3501 return tokError(toString(std::move(E)));
3502
3503 ResultTy = STy;
3504 return false;
3505}
3506
3507/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3508/// StructType
3509/// ::= '{' '}'
3510/// ::= '{' Type (',' Type)* '}'
3511/// ::= '<' '{' '}' '>'
3512/// ::= '<' '{' Type (',' Type)* '}' '>'
3513bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3514 assert(Lex.getKind() == lltok::lbrace);
3515 Lex.Lex(); // Consume the '{'
3516
3517 // Handle the empty struct.
3518 if (EatIfPresent(lltok::rbrace))
3519 return false;
3520
3521 LocTy EltTyLoc = Lex.getLoc();
3522 Type *Ty = nullptr;
3523 if (parseType(Ty))
3524 return true;
3525 Body.push_back(Ty);
3526
3528 return error(EltTyLoc, "invalid element type for struct");
3529
3530 while (EatIfPresent(lltok::comma)) {
3531 EltTyLoc = Lex.getLoc();
3532 if (parseType(Ty))
3533 return true;
3534
3536 return error(EltTyLoc, "invalid element type for struct");
3537
3538 Body.push_back(Ty);
3539 }
3540
3541 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3542}
3543
3544/// parseArrayVectorType - parse an array or vector type, assuming the first
3545/// token has already been consumed.
3546/// Type
3547/// ::= '[' APSINTVAL 'x' Types ']'
3548/// ::= '<' APSINTVAL 'x' Types '>'
3549/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3550bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3551 bool Scalable = false;
3552
3553 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3554 Lex.Lex(); // consume the 'vscale'
3555 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3556 return true;
3557
3558 Scalable = true;
3559 }
3560
3561 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3562 Lex.getAPSIntVal().getBitWidth() > 64)
3563 return tokError("expected number in address space");
3564
3565 LocTy SizeLoc = Lex.getLoc();
3566 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3567 Lex.Lex();
3568
3569 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3570 return true;
3571
3572 LocTy TypeLoc = Lex.getLoc();
3573 Type *EltTy = nullptr;
3574 if (parseType(EltTy))
3575 return true;
3576
3577 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3578 "expected end of sequential type"))
3579 return true;
3580
3581 if (IsVector) {
3582 if (Size == 0)
3583 return error(SizeLoc, "zero element vector is illegal");
3584 if ((unsigned)Size != Size)
3585 return error(SizeLoc, "size too large for vector");
3587 return error(TypeLoc, "invalid vector element type");
3588 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3589 } else {
3591 return error(TypeLoc, "invalid array element type");
3592 Result = ArrayType::get(EltTy, Size);
3593 }
3594 return false;
3595}
3596
3597/// parseTargetExtType - handle target extension type syntax
3598/// TargetExtType
3599/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3600///
3601/// TargetExtTypeParams
3602/// ::= /*empty*/
3603/// ::= ',' Type TargetExtTypeParams
3604///
3605/// TargetExtIntParams
3606/// ::= /*empty*/
3607/// ::= ',' uint32 TargetExtIntParams
3608bool LLParser::parseTargetExtType(Type *&Result) {
3609 Lex.Lex(); // Eat the 'target' keyword.
3610
3611 // Get the mandatory type name.
3612 std::string TypeName;
3613 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3614 parseStringConstant(TypeName))
3615 return true;
3616
3617 // Parse all of the integer and type parameters at the same time; the use of
3618 // SeenInt will allow us to catch cases where type parameters follow integer
3619 // parameters.
3620 SmallVector<Type *> TypeParams;
3621 SmallVector<unsigned> IntParams;
3622 bool SeenInt = false;
3623 while (Lex.getKind() == lltok::comma) {
3624 Lex.Lex(); // Eat the comma.
3625
3626 if (Lex.getKind() == lltok::APSInt) {
3627 SeenInt = true;
3628 unsigned IntVal;
3629 if (parseUInt32(IntVal))
3630 return true;
3631 IntParams.push_back(IntVal);
3632 } else if (SeenInt) {
3633 // The only other kind of parameter we support is type parameters, which
3634 // must precede the integer parameters. This is therefore an error.
3635 return tokError("expected uint32 param");
3636 } else {
3637 Type *TypeParam;
3638 if (parseType(TypeParam, /*AllowVoid=*/true))
3639 return true;
3640 TypeParams.push_back(TypeParam);
3641 }
3642 }
3643
3644 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3645 return true;
3646
3647 auto TTy =
3648 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3649 if (auto E = TTy.takeError())
3650 return tokError(toString(std::move(E)));
3651
3652 Result = *TTy;
3653 return false;
3654}
3655
3656//===----------------------------------------------------------------------===//
3657// Function Semantic Analysis.
3658//===----------------------------------------------------------------------===//
3659
3660LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3661 int functionNumber,
3662 ArrayRef<unsigned> UnnamedArgNums)
3663 : P(p), F(f), FunctionNumber(functionNumber) {
3664
3665 // Insert unnamed arguments into the NumberedVals list.
3666 auto It = UnnamedArgNums.begin();
3667 for (Argument &A : F.args()) {
3668 if (!A.hasName()) {
3669 unsigned ArgNum = *It++;
3670 NumberedVals.add(ArgNum, &A);
3671 }
3672 }
3673}
3674
3675LLParser::PerFunctionState::~PerFunctionState() {
3676 // If there were any forward referenced non-basicblock values, delete them.
3677
3678 for (const auto &P : ForwardRefVals) {
3679 if (isa<BasicBlock>(P.second.first))
3680 continue;
3681 P.second.first->replaceAllUsesWith(
3682 PoisonValue::get(P.second.first->getType()));
3683 P.second.first->deleteValue();
3684 }
3685
3686 for (const auto &P : ForwardRefValIDs) {
3687 if (isa<BasicBlock>(P.second.first))
3688 continue;
3689 P.second.first->replaceAllUsesWith(
3690 PoisonValue::get(P.second.first->getType()));
3691 P.second.first->deleteValue();
3692 }
3693}
3694
3695bool LLParser::PerFunctionState::finishFunction() {
3696 if (!ForwardRefVals.empty())
3697 return P.error(ForwardRefVals.begin()->second.second,
3698 "use of undefined value '%" + ForwardRefVals.begin()->first +
3699 "'");
3700 if (!ForwardRefValIDs.empty())
3701 return P.error(ForwardRefValIDs.begin()->second.second,
3702 "use of undefined value '%" +
3703 Twine(ForwardRefValIDs.begin()->first) + "'");
3704 return false;
3705}
3706
3707/// getVal - Get a value with the specified name or ID, creating a
3708/// forward reference record if needed. This can return null if the value
3709/// exists but does not have the right type.
3710Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3711 LocTy Loc) {
3712 // Look this name up in the normal function symbol table.
3713 Value *Val = F.getValueSymbolTable()->lookup(Name);
3714
3715 // If this is a forward reference for the value, see if we already created a
3716 // forward ref record.
3717 if (!Val) {
3718 auto I = ForwardRefVals.find(Name);
3719 if (I != ForwardRefVals.end())
3720 Val = I->second.first;
3721 }
3722
3723 // If we have the value in the symbol table or fwd-ref table, return it.
3724 if (Val)
3725 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3726
3727 // Don't make placeholders with invalid type.
3728 if (!Ty->isFirstClassType()) {
3729 P.error(Loc, "invalid use of a non-first-class type");
3730 return nullptr;
3731 }
3732
3733 // Otherwise, create a new forward reference for this value and remember it.
3734 Value *FwdVal;
3735 if (Ty->isLabelTy()) {
3736 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3737 } else {
3738 FwdVal = new Argument(Ty, Name);
3739 }
3740 if (FwdVal->getName() != Name) {
3741 P.error(Loc, "name is too long which can result in name collisions, "
3742 "consider making the name shorter or "
3743 "increasing -non-global-value-max-name-size");
3744 return nullptr;
3745 }
3746
3747 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3748 return FwdVal;
3749}
3750
3751Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3752 // Look this name up in the normal function symbol table.
3753 Value *Val = NumberedVals.get(ID);
3754
3755 // If this is a forward reference for the value, see if we already created a
3756 // forward ref record.
3757 if (!Val) {
3758 auto I = ForwardRefValIDs.find(ID);
3759 if (I != ForwardRefValIDs.end())
3760 Val = I->second.first;
3761 }
3762
3763 // If we have the value in the symbol table or fwd-ref table, return it.
3764 if (Val)
3765 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3766
3767 if (!Ty->isFirstClassType()) {
3768 P.error(Loc, "invalid use of a non-first-class type");
3769 return nullptr;
3770 }
3771
3772 // Otherwise, create a new forward reference for this value and remember it.
3773 Value *FwdVal;
3774 if (Ty->isLabelTy()) {
3775 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3776 } else {
3777 FwdVal = new Argument(Ty);
3778 }
3779
3780 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3781 return FwdVal;
3782}
3783
3784/// setInstName - After an instruction is parsed and inserted into its
3785/// basic block, this installs its name.
3786bool LLParser::PerFunctionState::setInstName(int NameID,
3787 const std::string &NameStr,
3788 LocTy NameLoc, Instruction *Inst) {
3789 // If this instruction has void type, it cannot have a name or ID specified.
3790 if (Inst->getType()->isVoidTy()) {
3791 if (NameID != -1 || !NameStr.empty())
3792 return P.error(NameLoc, "instructions returning void cannot have a name");
3793 return false;
3794 }
3795
3796 // If this was a numbered instruction, verify that the instruction is the
3797 // expected value and resolve any forward references.
3798 if (NameStr.empty()) {
3799 // If neither a name nor an ID was specified, just use the next ID.
3800 if (NameID == -1)
3801 NameID = NumberedVals.getNext();
3802
3803 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3804 NameID))
3805 return true;
3806
3807 auto FI = ForwardRefValIDs.find(NameID);
3808 if (FI != ForwardRefValIDs.end()) {
3809 Value *Sentinel = FI->second.first;
3810 if (Sentinel->getType() != Inst->getType())
3811 return P.error(NameLoc, "instruction forward referenced with type '" +
3812 getTypeString(FI->second.first->getType()) +
3813 "'");
3814
3815 Sentinel->replaceAllUsesWith(Inst);
3816 Sentinel->deleteValue();
3817 ForwardRefValIDs.erase(FI);
3818 }
3819
3820 NumberedVals.add(NameID, Inst);
3821 return false;
3822 }
3823
3824 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3825 auto FI = ForwardRefVals.find(NameStr);
3826 if (FI != ForwardRefVals.end()) {
3827 Value *Sentinel = FI->second.first;
3828 if (Sentinel->getType() != Inst->getType())
3829 return P.error(NameLoc, "instruction forward referenced with type '" +
3830 getTypeString(FI->second.first->getType()) +
3831 "'");
3832
3833 Sentinel->replaceAllUsesWith(Inst);
3834 Sentinel->deleteValue();
3835 ForwardRefVals.erase(FI);
3836 }
3837
3838 // Set the name on the instruction.
3839 Inst->setName(NameStr);
3840
3841 if (Inst->getName() != NameStr)
3842 return P.error(NameLoc, "multiple definition of local value named '" +
3843 NameStr + "'");
3844 return false;
3845}
3846
3847/// getBB - Get a basic block with the specified name or ID, creating a
3848/// forward reference record if needed.
3849BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3850 LocTy Loc) {
3852 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3853}
3854
3855BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3857 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3858}
3859
3860/// defineBB - Define the specified basic block, which is either named or
3861/// unnamed. If there is an error, this returns null otherwise it returns
3862/// the block being defined.
3863BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3864 int NameID, LocTy Loc) {
3865 BasicBlock *BB;
3866 if (Name.empty()) {
3867 if (NameID != -1) {
3868 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3869 return nullptr;
3870 } else {
3871 NameID = NumberedVals.getNext();
3872 }
3873 BB = getBB(NameID, Loc);
3874 if (!BB) {
3875 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3876 return nullptr;
3877 }
3878 } else {
3879 BB = getBB(Name, Loc);
3880 if (!BB) {
3881 P.error(Loc, "unable to create block named '" + Name + "'");
3882 return nullptr;
3883 }
3884 }
3885
3886 // Move the block to the end of the function. Forward ref'd blocks are
3887 // inserted wherever they happen to be referenced.
3888 F.splice(F.end(), &F, BB->getIterator());
3889
3890 // Remove the block from forward ref sets.
3891 if (Name.empty()) {
3892 ForwardRefValIDs.erase(NameID);
3893 NumberedVals.add(NameID, BB);
3894 } else {
3895 // BB forward references are already in the function symbol table.
3896 ForwardRefVals.erase(Name);
3897 }
3898
3899 return BB;
3900}
3901
3902//===----------------------------------------------------------------------===//
3903// Constants.
3904//===----------------------------------------------------------------------===//
3905
3906/// parseValID - parse an abstract value that doesn't necessarily have a
3907/// type implied. For example, if we parse "4" we don't know what integer type
3908/// it has. The value will later be combined with its type and checked for
3909/// basic correctness. PFS is used to convert function-local operands of
3910/// metadata (since metadata operands are not just parsed here but also
3911/// converted to values). PFS can be null when we are not parsing metadata
3912/// values inside a function.
3913bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3914 ID.Loc = Lex.getLoc();
3915 switch (Lex.getKind()) {
3916 default:
3917 return tokError("expected value token");
3918 case lltok::GlobalID: // @42
3919 ID.UIntVal = Lex.getUIntVal();
3920 ID.Kind = ValID::t_GlobalID;
3921 break;
3922 case lltok::GlobalVar: // @foo
3923 ID.StrVal = Lex.getStrVal();
3924 ID.Kind = ValID::t_GlobalName;
3925 break;
3926 case lltok::LocalVarID: // %42
3927 ID.UIntVal = Lex.getUIntVal();
3928 ID.Kind = ValID::t_LocalID;
3929 break;
3930 case lltok::LocalVar: // %foo
3931 ID.StrVal = Lex.getStrVal();
3932 ID.Kind = ValID::t_LocalName;
3933 break;
3934 case lltok::APSInt:
3935 ID.APSIntVal = Lex.getAPSIntVal();
3936 ID.Kind = ValID::t_APSInt;
3937 break;
3938 case lltok::APFloat:
3939 ID.APFloatVal = Lex.getAPFloatVal();
3940 ID.Kind = ValID::t_APFloat;
3941 break;
3942 case lltok::kw_true:
3943 ID.ConstantVal = ConstantInt::getTrue(Context);
3944 ID.Kind = ValID::t_Constant;
3945 break;
3946 case lltok::kw_false:
3947 ID.ConstantVal = ConstantInt::getFalse(Context);
3948 ID.Kind = ValID::t_Constant;
3949 break;
3950 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3951 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3952 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3953 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3954 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3955
3956 case lltok::lbrace: {
3957 // ValID ::= '{' ConstVector '}'
3958 Lex.Lex();
3960 if (parseGlobalValueVector(Elts) ||
3961 parseToken(lltok::rbrace, "expected end of struct constant"))
3962 return true;
3963
3964 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3965 ID.UIntVal = Elts.size();
3966 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3967 Elts.size() * sizeof(Elts[0]));
3969 return false;
3970 }
3971 case lltok::less: {
3972 // ValID ::= '<' ConstVector '>' --> Vector.
3973 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3974 Lex.Lex();
3975 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3976
3978 LocTy FirstEltLoc = Lex.getLoc();
3979 if (parseGlobalValueVector(Elts) ||
3980 (isPackedStruct &&
3981 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3982 parseToken(lltok::greater, "expected end of constant"))
3983 return true;
3984
3985 if (isPackedStruct) {
3986 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3987 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3988 Elts.size() * sizeof(Elts[0]));
3989 ID.UIntVal = Elts.size();
3991 return false;
3992 }
3993
3994 if (Elts.empty())
3995 return error(ID.Loc, "constant vector must not be empty");
3996
3997 if (!Elts[0]->getType()->isIntegerTy() &&
3998 !Elts[0]->getType()->isFloatingPointTy() &&
3999 !Elts[0]->getType()->isPointerTy())
4000 return error(
4001 FirstEltLoc,
4002 "vector elements must have integer, pointer or floating point type");
4003
4004 // Verify that all the vector elements have the same type.
4005 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4006 if (Elts[i]->getType() != Elts[0]->getType())
4007 return error(FirstEltLoc, "vector element #" + Twine(i) +
4008 " is not of type '" +
4009 getTypeString(Elts[0]->getType()));
4010
4011 ID.ConstantVal = ConstantVector::get(Elts);
4012 ID.Kind = ValID::t_Constant;
4013 return false;
4014 }
4015 case lltok::lsquare: { // Array Constant
4016 Lex.Lex();
4018 LocTy FirstEltLoc = Lex.getLoc();
4019 if (parseGlobalValueVector(Elts) ||
4020 parseToken(lltok::rsquare, "expected end of array constant"))
4021 return true;
4022
4023 // Handle empty element.
4024 if (Elts.empty()) {
4025 // Use undef instead of an array because it's inconvenient to determine
4026 // the element type at this point, there being no elements to examine.
4027 ID.Kind = ValID::t_EmptyArray;
4028 return false;
4029 }
4030
4031 if (!Elts[0]->getType()->isFirstClassType())
4032 return error(FirstEltLoc, "invalid array element type: " +
4033 getTypeString(Elts[0]->getType()));
4034
4035 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4036
4037 // Verify all elements are correct type!
4038 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4039 if (Elts[i]->getType() != Elts[0]->getType())
4040 return error(FirstEltLoc, "array element #" + Twine(i) +
4041 " is not of type '" +
4042 getTypeString(Elts[0]->getType()));
4043 }
4044
4045 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4046 ID.Kind = ValID::t_Constant;
4047 return false;
4048 }
4049 case lltok::kw_c: // c "foo"
4050 Lex.Lex();
4051 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4052 false);
4053 if (parseToken(lltok::StringConstant, "expected string"))
4054 return true;
4055 ID.Kind = ValID::t_Constant;
4056 return false;
4057
4058 case lltok::kw_asm: {
4059 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4060 // STRINGCONSTANT
4061 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4062 Lex.Lex();
4063 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4064 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4065 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4066 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4067 parseStringConstant(ID.StrVal) ||
4068 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4069 parseToken(lltok::StringConstant, "expected constraint string"))
4070 return true;
4071 ID.StrVal2 = Lex.getStrVal();
4072 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4073 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4074 ID.Kind = ValID::t_InlineAsm;
4075 return false;
4076 }
4077
4079 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4080 Lex.Lex();
4081
4082 ValID Fn, Label;
4083
4084 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4085 parseValID(Fn, PFS) ||
4086 parseToken(lltok::comma,
4087 "expected comma in block address expression") ||
4088 parseValID(Label, PFS) ||
4089 parseToken(lltok::rparen, "expected ')' in block address expression"))
4090 return true;
4091
4093 return error(Fn.Loc, "expected function name in blockaddress");
4094 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4095 return error(Label.Loc, "expected basic block name in blockaddress");
4096
4097 // Try to find the function (but skip it if it's forward-referenced).
4098 GlobalValue *GV = nullptr;
4099 if (Fn.Kind == ValID::t_GlobalID) {
4100 GV = NumberedVals.get(Fn.UIntVal);
4101 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4102 GV = M->getNamedValue(Fn.StrVal);
4103 }
4104 Function *F = nullptr;
4105 if (GV) {
4106 // Confirm that it's actually a function with a definition.
4107 if (!isa<Function>(GV))
4108 return error(Fn.Loc, "expected function name in blockaddress");
4109 F = cast<Function>(GV);
4110 if (F->isDeclaration())
4111 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4112 }
4113
4114 if (!F) {
4115 // Make a global variable as a placeholder for this reference.
4116 GlobalValue *&FwdRef =
4117 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4118 if (!FwdRef) {
4119 unsigned FwdDeclAS;
4120 if (ExpectedTy) {
4121 // If we know the type that the blockaddress is being assigned to,
4122 // we can use the address space of that type.
4123 if (!ExpectedTy->isPointerTy())
4124 return error(ID.Loc,
4125 "type of blockaddress must be a pointer and not '" +
4126 getTypeString(ExpectedTy) + "'");
4127 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4128 } else if (PFS) {
4129 // Otherwise, we default the address space of the current function.
4130 FwdDeclAS = PFS->getFunction().getAddressSpace();
4131 } else {
4132 llvm_unreachable("Unknown address space for blockaddress");
4133 }
4134 FwdRef = new GlobalVariable(
4135 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4136 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4137 }
4138
4139 ID.ConstantVal = FwdRef;
4140 ID.Kind = ValID::t_Constant;
4141 return false;
4142 }
4143
4144 // We found the function; now find the basic block. Don't use PFS, since we
4145 // might be inside a constant expression.
4146 BasicBlock *BB;
4147 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4148 if (Label.Kind == ValID::t_LocalID)
4149 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4150 else
4151 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4152 if (!BB)
4153 return error(Label.Loc, "referenced value is not a basic block");
4154 } else {
4155 if (Label.Kind == ValID::t_LocalID)
4156 return error(Label.Loc, "cannot take address of numeric label after "
4157 "the function is defined");
4159 F->getValueSymbolTable()->lookup(Label.StrVal));
4160 if (!BB)
4161 return error(Label.Loc, "referenced value is not a basic block");
4162 }
4163
4164 ID.ConstantVal = BlockAddress::get(F, BB);
4165 ID.Kind = ValID::t_Constant;
4166 return false;
4167 }
4168
4170 // ValID ::= 'dso_local_equivalent' @foo
4171 Lex.Lex();
4172
4173 ValID Fn;
4174
4175 if (parseValID(Fn, PFS))
4176 return true;
4177
4179 return error(Fn.Loc,
4180 "expected global value name in dso_local_equivalent");
4181
4182 // Try to find the function (but skip it if it's forward-referenced).
4183 GlobalValue *GV = nullptr;
4184 if (Fn.Kind == ValID::t_GlobalID) {
4185 GV = NumberedVals.get(Fn.UIntVal);
4186 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4187 GV = M->getNamedValue(Fn.StrVal);
4188 }
4189
4190 if (!GV) {
4191 // Make a placeholder global variable as a placeholder for this reference.
4192 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4193 ? ForwardRefDSOLocalEquivalentIDs
4194 : ForwardRefDSOLocalEquivalentNames;
4195 GlobalValue *&FwdRef = FwdRefMap[Fn];
4196 if (!FwdRef) {
4197 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4198 GlobalValue::InternalLinkage, nullptr, "",
4200 }
4201
4202 ID.ConstantVal = FwdRef;
4203 ID.Kind = ValID::t_Constant;
4204 return false;
4205 }
4206
4207 if (!GV->getValueType()->isFunctionTy())
4208 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4209 "in dso_local_equivalent");
4210
4211 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4212 ID.Kind = ValID::t_Constant;
4213 return false;
4214 }
4215
4216 case lltok::kw_no_cfi: {
4217 // ValID ::= 'no_cfi' @foo
4218 Lex.Lex();
4219
4220 if (parseValID(ID, PFS))
4221 return true;
4222
4223 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4224 return error(ID.Loc, "expected global value name in no_cfi");
4225
4226 ID.NoCFI = true;
4227 return false;
4228 }
4229 case lltok::kw_ptrauth: {
4230 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4231 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4232 Lex.Lex();
4233
4234 Constant *Ptr, *Key;
4235 Constant *Disc = nullptr, *AddrDisc = nullptr;
4236
4237 if (parseToken(lltok::lparen,
4238 "expected '(' in constant ptrauth expression") ||
4239 parseGlobalTypeAndValue(Ptr) ||
4240 parseToken(lltok::comma,
4241 "expected comma in constant ptrauth expression") ||
4242 parseGlobalTypeAndValue(Key))
4243 return true;
4244 // If present, parse the optional disc/addrdisc.
4245 if (EatIfPresent(lltok::comma))
4246 if (parseGlobalTypeAndValue(Disc) ||
4247 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4248 return true;
4249 if (parseToken(lltok::rparen,
4250 "expected ')' in constant ptrauth expression"))
4251 return true;
4252
4253 if (!Ptr->getType()->isPointerTy())
4254 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4255
4256 auto *KeyC = dyn_cast<ConstantInt>(Key);
4257 if (!KeyC || KeyC->getBitWidth() != 32)
4258 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4259
4260 ConstantInt *DiscC = nullptr;
4261 if (Disc) {
4262 DiscC = dyn_cast<ConstantInt>(Disc);
4263 if (!DiscC || DiscC->getBitWidth() != 64)
4264 return error(
4265 ID.Loc,
4266 "constant ptrauth integer discriminator must be i64 constant");
4267 } else {
4268 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4269 }
4270
4271 if (AddrDisc) {
4272 if (!AddrDisc->getType()->isPointerTy())
4273 return error(
4274 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4275 } else {
4276 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4277 }
4278
4279 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4280 ID.Kind = ValID::t_Constant;
4281 return false;
4282 }
4283
4284 case lltok::kw_trunc:
4285 case lltok::kw_bitcast:
4287 case lltok::kw_inttoptr:
4289 case lltok::kw_ptrtoint: {
4290 unsigned Opc = Lex.getUIntVal();
4291 Type *DestTy = nullptr;
4292 Constant *SrcVal;
4293 Lex.Lex();
4294 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4295 parseGlobalTypeAndValue(SrcVal) ||
4296 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4297 parseType(DestTy) ||
4298 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4299 return true;
4300 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4301 return error(ID.Loc, "invalid cast opcode for cast from '" +
4302 getTypeString(SrcVal->getType()) + "' to '" +
4303 getTypeString(DestTy) + "'");
4305 SrcVal, DestTy);
4306 ID.Kind = ValID::t_Constant;
4307 return false;
4308 }
4310 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4312 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4313 case lltok::kw_udiv:
4314 return error(ID.Loc, "udiv constexprs are no longer supported");
4315 case lltok::kw_sdiv:
4316 return error(ID.Loc, "sdiv constexprs are no longer supported");
4317 case lltok::kw_urem:
4318 return error(ID.Loc, "urem constexprs are no longer supported");
4319 case lltok::kw_srem:
4320 return error(ID.Loc, "srem constexprs are no longer supported");
4321 case lltok::kw_fadd:
4322 return error(ID.Loc, "fadd constexprs are no longer supported");
4323 case lltok::kw_fsub:
4324 return error(ID.Loc, "fsub constexprs are no longer supported");
4325 case lltok::kw_fmul:
4326 return error(ID.Loc, "fmul constexprs are no longer supported");
4327 case lltok::kw_fdiv:
4328 return error(ID.Loc, "fdiv constexprs are no longer supported");
4329 case lltok::kw_frem:
4330 return error(ID.Loc, "frem constexprs are no longer supported");
4331 case lltok::kw_and:
4332 return error(ID.Loc, "and constexprs are no longer supported");
4333 case lltok::kw_or:
4334 return error(ID.Loc, "or constexprs are no longer supported");
4335 case lltok::kw_lshr:
4336 return error(ID.Loc, "lshr constexprs are no longer supported");
4337 case lltok::kw_ashr:
4338 return error(ID.Loc, "ashr constexprs are no longer supported");
4339 case lltok::kw_shl:
4340 return error(ID.Loc, "shl constexprs are no longer supported");
4341 case lltok::kw_mul:
4342 return error(ID.Loc, "mul constexprs are no longer supported");
4343 case lltok::kw_fneg:
4344 return error(ID.Loc, "fneg constexprs are no longer supported");
4345 case lltok::kw_select:
4346 return error(ID.Loc, "select constexprs are no longer supported");
4347 case lltok::kw_zext:
4348 return error(ID.Loc, "zext constexprs are no longer supported");
4349 case lltok::kw_sext:
4350 return error(ID.Loc, "sext constexprs are no longer supported");
4351 case lltok::kw_fptrunc:
4352 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4353 case lltok::kw_fpext:
4354 return error(ID.Loc, "fpext constexprs are no longer supported");
4355 case lltok::kw_uitofp:
4356 return error(ID.Loc, "uitofp constexprs are no longer supported");
4357 case lltok::kw_sitofp:
4358 return error(ID.Loc, "sitofp constexprs are no longer supported");
4359 case lltok::kw_fptoui:
4360 return error(ID.Loc, "fptoui constexprs are no longer supported");
4361 case lltok::kw_fptosi:
4362 return error(ID.Loc, "fptosi constexprs are no longer supported");
4363 case lltok::kw_icmp:
4364 return error(ID.Loc, "icmp constexprs are no longer supported");
4365 case lltok::kw_fcmp:
4366 return error(ID.Loc, "fcmp constexprs are no longer supported");
4367
4368 // Binary Operators.
4369 case lltok::kw_add:
4370 case lltok::kw_sub:
4371 case lltok::kw_xor: {
4372 bool NUW = false;
4373 bool NSW = false;
4374 unsigned Opc = Lex.getUIntVal();
4375 Constant *Val0, *Val1;
4376 Lex.Lex();
4377 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4378 Opc == Instruction::Mul) {
4379 if (EatIfPresent(lltok::kw_nuw))
4380 NUW = true;
4381 if (EatIfPresent(lltok::kw_nsw)) {
4382 NSW = true;
4383 if (EatIfPresent(lltok::kw_nuw))
4384 NUW = true;
4385 }
4386 }
4387 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4388 parseGlobalTypeAndValue(Val0) ||
4389 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4390 parseGlobalTypeAndValue(Val1) ||
4391 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4392 return true;
4393 if (Val0->getType() != Val1->getType())
4394 return error(ID.Loc, "operands of constexpr must have same type");
4395 // Check that the type is valid for the operator.
4396 if (!Val0->getType()->isIntOrIntVectorTy())
4397 return error(ID.Loc,
4398 "constexpr requires integer or integer vector operands");
4399 unsigned Flags = 0;
4402 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4403 ID.Kind = ValID::t_Constant;
4404 return false;
4405 }
4406
4407 case lltok::kw_splat: {
4408 Lex.Lex();
4409 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4410 return true;
4411 Constant *C;
4412 if (parseGlobalTypeAndValue(C))
4413 return true;
4414 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4415 return true;
4416
4417 ID.ConstantVal = C;
4419 return false;
4420 }
4421
4426 unsigned Opc = Lex.getUIntVal();
4428 GEPNoWrapFlags NW;
4429 bool HasInRange = false;
4430 APSInt InRangeStart;
4431 APSInt InRangeEnd;
4432 Type *Ty;
4433 Lex.Lex();
4434
4435 if (Opc == Instruction::GetElementPtr) {
4436 while (true) {
4437 if (EatIfPresent(lltok::kw_inbounds))
4439 else if (EatIfPresent(lltok::kw_nusw))
4441 else if (EatIfPresent(lltok::kw_nuw))
4443 else
4444 break;
4445 }
4446
4447 if (EatIfPresent(lltok::kw_inrange)) {
4448 if (parseToken(lltok::lparen, "expected '('"))
4449 return true;
4450 if (Lex.getKind() != lltok::APSInt)
4451 return tokError("expected integer");
4452 InRangeStart = Lex.getAPSIntVal();
4453 Lex.Lex();
4454 if (parseToken(lltok::comma, "expected ','"))
4455 return true;
4456 if (Lex.getKind() != lltok::APSInt)
4457 return tokError("expected integer");
4458 InRangeEnd = Lex.getAPSIntVal();
4459 Lex.Lex();
4460 if (parseToken(lltok::rparen, "expected ')'"))
4461 return true;
4462 HasInRange = true;
4463 }
4464 }
4465
4466 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4467 return true;
4468
4469 if (Opc == Instruction::GetElementPtr) {
4470 if (parseType(Ty) ||
4471 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4472 return true;
4473 }
4474
4475 if (parseGlobalValueVector(Elts) ||
4476 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4477 return true;
4478
4479 if (Opc == Instruction::GetElementPtr) {
4480 if (Elts.size() == 0 ||
4481 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4482 return error(ID.Loc, "base of getelementptr must be a pointer");
4483
4484 Type *BaseType = Elts[0]->getType();
4485 std::optional<ConstantRange> InRange;
4486 if (HasInRange) {
4487 unsigned IndexWidth =
4488 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4489 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4490 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4491 if (InRangeStart.sge(InRangeEnd))
4492 return error(ID.Loc, "expected end to be larger than start");
4493 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4494 }
4495
4496 unsigned GEPWidth =
4497 BaseType->isVectorTy()
4498 ? cast<FixedVectorType>(BaseType)->getNumElements()
4499 : 0;
4500
4501 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4502 for (Constant *Val : Indices) {
4503 Type *ValTy = Val->getType();
4504 if (!ValTy->isIntOrIntVectorTy())
4505 return error(ID.Loc, "getelementptr index must be an integer");
4506 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4507 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4508 if (GEPWidth && (ValNumEl != GEPWidth))
4509 return error(
4510 ID.Loc,
4511 "getelementptr vector index has a wrong number of elements");
4512 // GEPWidth may have been unknown because the base is a scalar,
4513 // but it is known now.
4514 GEPWidth = ValNumEl;
4515 }
4516 }
4517
4518 SmallPtrSet<Type*, 4> Visited;
4519 if (!Indices.empty() && !Ty->isSized(&Visited))
4520 return error(ID.Loc, "base element of getelementptr must be sized");
4521
4522 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4523 return error(ID.Loc, "invalid getelementptr indices");
4524
4525 ID.ConstantVal =
4526 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4527 } else if (Opc == Instruction::ShuffleVector) {
4528 if (Elts.size() != 3)
4529 return error(ID.Loc, "expected three operands to shufflevector");
4530 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4531 return error(ID.Loc, "invalid operands to shufflevector");
4532 SmallVector<int, 16> Mask;
4534 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4535 } else if (Opc == Instruction::ExtractElement) {
4536 if (Elts.size() != 2)
4537 return error(ID.Loc, "expected two operands to extractelement");
4538 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4539 return error(ID.Loc, "invalid extractelement operands");
4540 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4541 } else {
4542 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4543 if (Elts.size() != 3)
4544 return error(ID.Loc, "expected three operands to insertelement");
4545 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4546 return error(ID.Loc, "invalid insertelement operands");
4547 ID.ConstantVal =
4548 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4549 }
4550
4551 ID.Kind = ValID::t_Constant;
4552 return false;
4553 }
4554 }
4555
4556 Lex.Lex();
4557 return false;
4558}
4559
4560/// parseGlobalValue - parse a global value with the specified type.
4561bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4562 C = nullptr;
4563 ValID ID;
4564 Value *V = nullptr;
4565 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4566 convertValIDToValue(Ty, ID, V, nullptr);
4567 if (V && !(C = dyn_cast<Constant>(V)))
4568 return error(ID.Loc, "global values must be constants");
4569 return Parsed;
4570}
4571
4572bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4573 Type *Ty = nullptr;
4574 return parseType(Ty) || parseGlobalValue(Ty, V);
4575}
4576
4577bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4578 C = nullptr;
4579
4580 LocTy KwLoc = Lex.getLoc();
4581 if (!EatIfPresent(lltok::kw_comdat))
4582 return false;
4583
4584 if (EatIfPresent(lltok::lparen)) {
4585 if (Lex.getKind() != lltok::ComdatVar)
4586 return tokError("expected comdat variable");
4587 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4588 Lex.Lex();
4589 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4590 return true;
4591 } else {
4592 if (GlobalName.empty())
4593 return tokError("comdat cannot be unnamed");
4594 C = getComdat(std::string(GlobalName), KwLoc);
4595 }
4596
4597 return false;
4598}
4599
4600/// parseGlobalValueVector
4601/// ::= /*empty*/
4602/// ::= TypeAndValue (',' TypeAndValue)*
4603bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4604 // Empty list.
4605 if (Lex.getKind() == lltok::rbrace ||
4606 Lex.getKind() == lltok::rsquare ||
4607 Lex.getKind() == lltok::greater ||
4608 Lex.getKind() == lltok::rparen)
4609 return false;
4610
4611 do {
4612 // Let the caller deal with inrange.
4613 if (Lex.getKind() == lltok::kw_inrange)
4614 return false;
4615
4616 Constant *C;
4617 if (parseGlobalTypeAndValue(C))
4618 return true;
4619 Elts.push_back(C);
4620 } while (EatIfPresent(lltok::comma));
4621
4622 return false;
4623}
4624
4625bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4627 if (parseMDNodeVector(Elts))
4628 return true;
4629
4630 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4631 return false;
4632}
4633
4634/// MDNode:
4635/// ::= !{ ... }
4636/// ::= !7
4637/// ::= !DILocation(...)
4638bool LLParser::parseMDNode(MDNode *&N) {
4639 if (Lex.getKind() == lltok::MetadataVar)
4640 return parseSpecializedMDNode(N);
4641
4642 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4643}
4644
4645bool LLParser::parseMDNodeTail(MDNode *&N) {
4646 // !{ ... }
4647 if (Lex.getKind() == lltok::lbrace)
4648 return parseMDTuple(N);
4649
4650 // !42
4651 return parseMDNodeID(N);
4652}
4653
4654namespace {
4655
4656/// Structure to represent an optional metadata field.
4657template <class FieldTy> struct MDFieldImpl {
4658 typedef MDFieldImpl ImplTy;
4659 FieldTy Val;
4660 bool Seen;
4661
4662 void assign(FieldTy Val) {
4663 Seen = true;
4664 this->Val = std::move(Val);
4665 }
4666
4667 explicit MDFieldImpl(FieldTy Default)
4668 : Val(std::move(Default)), Seen(false) {}
4669};
4670
4671/// Structure to represent an optional metadata field that
4672/// can be of either type (A or B) and encapsulates the
4673/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4674/// to reimplement the specifics for representing each Field.
4675template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4676 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4677 FieldTypeA A;
4678 FieldTypeB B;
4679 bool Seen;
4680
4681 enum {
4682 IsInvalid = 0,
4683 IsTypeA = 1,
4684 IsTypeB = 2
4685 } WhatIs;
4686
4687 void assign(FieldTypeA A) {
4688 Seen = true;
4689 this->A = std::move(A);
4690 WhatIs = IsTypeA;
4691 }
4692
4693 void assign(FieldTypeB B) {
4694 Seen = true;
4695 this->B = std::move(B);
4696 WhatIs = IsTypeB;
4697 }
4698
4699 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4700 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4701 WhatIs(IsInvalid) {}
4702};
4703
4704struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4705 uint64_t Max;
4706
4707 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4708 : ImplTy(Default), Max(Max) {}
4709};
4710
4711struct LineField : public MDUnsignedField {
4712 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4713};
4714
4715struct ColumnField : public MDUnsignedField {
4716 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4717};
4718
4719struct DwarfTagField : public MDUnsignedField {
4720 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4721 DwarfTagField(dwarf::Tag DefaultTag)
4722 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4723};
4724
4725struct DwarfMacinfoTypeField : public MDUnsignedField {
4726 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4727 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4728 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4729};
4730
4731struct DwarfAttEncodingField : public MDUnsignedField {
4732 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4733};
4734
4735struct DwarfVirtualityField : public MDUnsignedField {
4736 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4737};
4738
4739struct DwarfLangField : public MDUnsignedField {
4740 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4741};
4742
4743struct DwarfSourceLangNameField : public MDUnsignedField {
4744 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4745};
4746
4747struct DwarfCCField : public MDUnsignedField {
4748 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4749};
4750
4751struct DwarfEnumKindField : public MDUnsignedField {
4752 DwarfEnumKindField()
4753 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4754 dwarf::DW_APPLE_ENUM_KIND_max) {}
4755};
4756
4757struct EmissionKindField : public MDUnsignedField {
4758 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4759};
4760
4761struct FixedPointKindField : public MDUnsignedField {
4762 FixedPointKindField()
4763 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4764};
4765
4766struct NameTableKindField : public MDUnsignedField {
4767 NameTableKindField()
4768 : MDUnsignedField(
4769 0, (unsigned)
4770 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4771};
4772
4773struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4774 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4775};
4776
4777struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4778 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4779};
4780
4781struct MDAPSIntField : public MDFieldImpl<APSInt> {
4782 MDAPSIntField() : ImplTy(APSInt()) {}
4783};
4784
4785struct MDSignedField : public MDFieldImpl<int64_t> {
4786 int64_t Min = INT64_MIN;
4787 int64_t Max = INT64_MAX;
4788
4789 MDSignedField(int64_t Default = 0)
4790 : ImplTy(Default) {}
4791 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4792 : ImplTy(Default), Min(Min), Max(Max) {}
4793};
4794
4795struct MDBoolField : public MDFieldImpl<bool> {
4796 MDBoolField(bool Default = false) : ImplTy(Default) {}
4797};
4798
4799struct MDField : public MDFieldImpl<Metadata *> {
4800 bool AllowNull;
4801
4802 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4803};
4804
4805struct MDStringField : public MDFieldImpl<MDString *> {
4806 enum class EmptyIs {
4807 Null, //< Allow empty input string, map to nullptr
4808 Empty, //< Allow empty input string, map to an empty MDString
4809 Error, //< Disallow empty string, map to an error
4810 } EmptyIs;
4811 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
4812 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4813};
4814
4815struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4816 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4817};
4818
4819struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4820 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4821};
4822
4823struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4824 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4825 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4826
4827 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4828 bool AllowNull = true)
4829 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4830
4831 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4832 bool isMDField() const { return WhatIs == IsTypeB; }
4833 int64_t getMDSignedValue() const {
4834 assert(isMDSignedField() && "Wrong field type");
4835 return A.Val;
4836 }
4837 Metadata *getMDFieldValue() const {
4838 assert(isMDField() && "Wrong field type");
4839 return B.Val;
4840 }
4841};
4842
4843struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4844 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
4845 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
4846
4847 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
4848 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
4849
4850 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
4851 bool isMDField() const { return WhatIs == IsTypeB; }
4852 uint64_t getMDUnsignedValue() const {
4853 assert(isMDUnsignedField() && "Wrong field type");
4854 return A.Val;
4855 }
4856 Metadata *getMDFieldValue() const {
4857 assert(isMDField() && "Wrong field type");
4858 return B.Val;
4859 }
4860
4861 Metadata *getValueAsMetadata(LLVMContext &Context) const {
4862 if (isMDUnsignedField())
4864 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
4865 if (isMDField())
4866 return getMDFieldValue();
4867 return nullptr;
4868 }
4869};
4870
4871} // end anonymous namespace
4872
4873namespace llvm {
4874
4875template <>
4876bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4877 if (Lex.getKind() != lltok::APSInt)
4878 return tokError("expected integer");
4879
4880 Result.assign(Lex.getAPSIntVal());
4881 Lex.Lex();
4882 return false;
4883}
4884
4885template <>
4886bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4887 MDUnsignedField &Result) {
4888 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4889 return tokError("expected unsigned integer");
4890
4891 auto &U = Lex.getAPSIntVal();
4892 if (U.ugt(Result.Max))
4893 return tokError("value for '" + Name + "' too large, limit is " +
4894 Twine(Result.Max));
4895 Result.assign(U.getZExtValue());
4896 assert(Result.Val <= Result.Max && "Expected value in range");
4897 Lex.Lex();
4898 return false;
4899}
4900
4901template <>
4902bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4903 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4904}
4905template <>
4906bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4907 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4908}
4909
4910template <>
4911bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4912 if (Lex.getKind() == lltok::APSInt)
4913 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4914
4915 if (Lex.getKind() != lltok::DwarfTag)
4916 return tokError("expected DWARF tag");
4917
4918 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4920 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4921 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4922
4923 Result.assign(Tag);
4924 Lex.Lex();
4925 return false;
4926}
4927
4928template <>
4929bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4930 DwarfMacinfoTypeField &Result) {
4931 if (Lex.getKind() == lltok::APSInt)
4932 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4933
4934 if (Lex.getKind() != lltok::DwarfMacinfo)
4935 return tokError("expected DWARF macinfo type");
4936
4937 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4938 if (Macinfo == dwarf::DW_MACINFO_invalid)
4939 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4940 Lex.getStrVal() + "'");
4941 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4942
4943 Result.assign(Macinfo);
4944 Lex.Lex();
4945 return false;
4946}
4947
4948template <>
4949bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4950 DwarfVirtualityField &Result) {
4951 if (Lex.getKind() == lltok::APSInt)
4952 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4953
4954 if (Lex.getKind() != lltok::DwarfVirtuality)
4955 return tokError("expected DWARF virtuality code");
4956
4957 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4958 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4959 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4960 Lex.getStrVal() + "'");
4961 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4962 Result.assign(Virtuality);
4963 Lex.Lex();
4964 return false;
4965}
4966
4967template <>
4968bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4969 DwarfEnumKindField &Result) {
4970 if (Lex.getKind() == lltok::APSInt)
4971 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4972
4973 if (Lex.getKind() != lltok::DwarfEnumKind)
4974 return tokError("expected DWARF enum kind code");
4975
4976 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
4977 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
4978 return tokError("invalid DWARF enum kind code" + Twine(" '") +
4979 Lex.getStrVal() + "'");
4980 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
4981 Result.assign(EnumKind);
4982 Lex.Lex();
4983 return false;
4984}
4985
4986template <>
4987bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4988 if (Lex.getKind() == lltok::APSInt)
4989 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4990
4991 if (Lex.getKind() != lltok::DwarfLang)
4992 return tokError("expected DWARF language");
4993
4994 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4995 if (!Lang)
4996 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4997 "'");
4998 assert(Lang <= Result.Max && "Expected valid DWARF language");
4999 Result.assign(Lang);
5000 Lex.Lex();
5001 return false;
5002}
5003
5004template <>
5005bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5006 DwarfSourceLangNameField &Result) {
5007 if (Lex.getKind() == lltok::APSInt)
5008 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5009
5010 if (Lex.getKind() != lltok::DwarfSourceLangName)
5011 return tokError("expected DWARF source language name");
5012
5013 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5014 if (!Lang)
5015 return tokError("invalid DWARF source language name" + Twine(" '") +
5016 Lex.getStrVal() + "'");
5017 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5018 Result.assign(Lang);
5019 Lex.Lex();
5020 return false;
5021}
5022
5023template <>
5024bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5025 if (Lex.getKind() == lltok::APSInt)
5026 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5027
5028 if (Lex.getKind() != lltok::DwarfCC)
5029 return tokError("expected DWARF calling convention");
5030
5031 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5032 if (!CC)
5033 return tokError("invalid DWARF calling convention" + Twine(" '") +
5034 Lex.getStrVal() + "'");
5035 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5036 Result.assign(CC);
5037 Lex.Lex();
5038 return false;
5039}
5040
5041template <>
5042bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5043 EmissionKindField &Result) {
5044 if (Lex.getKind() == lltok::APSInt)
5045 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5046
5047 if (Lex.getKind() != lltok::EmissionKind)
5048 return tokError("expected emission kind");
5049
5050 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5051 if (!Kind)
5052 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5053 "'");
5054 assert(*Kind <= Result.Max && "Expected valid emission kind");
5055 Result.assign(*Kind);
5056 Lex.Lex();
5057 return false;
5058}
5059
5060template <>
5061bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5062 FixedPointKindField &Result) {
5063 if (Lex.getKind() == lltok::APSInt)
5064 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5065
5066 if (Lex.getKind() != lltok::FixedPointKind)
5067 return tokError("expected fixed-point kind");
5068
5069 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5070 if (!Kind)
5071 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5072 "'");
5073 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5074 Result.assign(*Kind);
5075 Lex.Lex();
5076 return false;
5077}
5078
5079template <>
5080bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5081 NameTableKindField &Result) {
5082 if (Lex.getKind() == lltok::APSInt)
5083 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5084
5085 if (Lex.getKind() != lltok::NameTableKind)
5086 return tokError("expected nameTable kind");
5087
5088 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5089 if (!Kind)
5090 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5091 "'");
5092 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5093 Result.assign((unsigned)*Kind);
5094 Lex.Lex();
5095 return false;
5096}
5097
5098template <>
5099bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5100 DwarfAttEncodingField &Result) {
5101 if (Lex.getKind() == lltok::APSInt)
5102 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5103
5104 if (Lex.getKind() != lltok::DwarfAttEncoding)
5105 return tokError("expected DWARF type attribute encoding");
5106
5107 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5108 if (!Encoding)
5109 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5110 Lex.getStrVal() + "'");
5111 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5112 Result.assign(Encoding);
5113 Lex.Lex();
5114 return false;
5115}
5116
5117/// DIFlagField
5118/// ::= uint32
5119/// ::= DIFlagVector
5120/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5121template <>
5122bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5123
5124 // parser for a single flag.
5125 auto parseFlag = [&](DINode::DIFlags &Val) {
5126 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5127 uint32_t TempVal = static_cast<uint32_t>(Val);
5128 bool Res = parseUInt32(TempVal);
5129 Val = static_cast<DINode::DIFlags>(TempVal);
5130 return Res;
5131 }
5132
5133 if (Lex.getKind() != lltok::DIFlag)
5134 return tokError("expected debug info flag");
5135
5136 Val = DINode::getFlag(Lex.getStrVal());
5137 if (!Val)
5138 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5139 "'");
5140 Lex.Lex();
5141 return false;
5142 };
5143
5144 // parse the flags and combine them together.
5145 DINode::DIFlags Combined = DINode::FlagZero;
5146 do {
5147 DINode::DIFlags Val;
5148 if (parseFlag(Val))
5149 return true;
5150 Combined |= Val;
5151 } while (EatIfPresent(lltok::bar));
5152
5153 Result.assign(Combined);
5154 return false;
5155}
5156
5157/// DISPFlagField
5158/// ::= uint32
5159/// ::= DISPFlagVector
5160/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5161template <>
5162bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5163
5164 // parser for a single flag.
5165 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5166 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5167 uint32_t TempVal = static_cast<uint32_t>(Val);
5168 bool Res = parseUInt32(TempVal);
5169 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5170 return Res;
5171 }
5172
5173 if (Lex.getKind() != lltok::DISPFlag)
5174 return tokError("expected debug info flag");
5175
5176 Val = DISubprogram::getFlag(Lex.getStrVal());
5177 if (!Val)
5178 return tokError(Twine("invalid subprogram debug info flag '") +
5179 Lex.getStrVal() + "'");
5180 Lex.Lex();
5181 return false;
5182 };
5183
5184 // parse the flags and combine them together.
5185 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5186 do {
5188 if (parseFlag(Val))
5189 return true;
5190 Combined |= Val;
5191 } while (EatIfPresent(lltok::bar));
5192
5193 Result.assign(Combined);
5194 return false;
5195}
5196
5197template <>
5198bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5199 if (Lex.getKind() != lltok::APSInt)
5200 return tokError("expected signed integer");
5201
5202 auto &S = Lex.getAPSIntVal();
5203 if (S < Result.Min)
5204 return tokError("value for '" + Name + "' too small, limit is " +
5205 Twine(Result.Min));
5206 if (S > Result.Max)
5207 return tokError("value for '" + Name + "' too large, limit is " +
5208 Twine(Result.Max));
5209 Result.assign(S.getExtValue());
5210 assert(Result.Val >= Result.Min && "Expected value in range");
5211 assert(Result.Val <= Result.Max && "Expected value in range");
5212 Lex.Lex();
5213 return false;
5214}
5215
5216template <>
5217bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5218 switch (Lex.getKind()) {
5219 default:
5220 return tokError("expected 'true' or 'false'");
5221 case lltok::kw_true:
5222 Result.assign(true);
5223 break;
5224 case lltok::kw_false:
5225 Result.assign(false);
5226 break;
5227 }
5228 Lex.Lex();
5229 return false;
5230}
5231
5232template <>
5233bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5234 if (Lex.getKind() == lltok::kw_null) {
5235 if (!Result.AllowNull)
5236 return tokError("'" + Name + "' cannot be null");
5237 Lex.Lex();
5238 Result.assign(nullptr);
5239 return false;
5240 }
5241
5242 Metadata *MD;
5243 if (parseMetadata(MD, nullptr))
5244 return true;
5245
5246 Result.assign(MD);
5247 return false;
5248}
5249
5250template <>
5251bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5252 MDSignedOrMDField &Result) {
5253 // Try to parse a signed int.
5254 if (Lex.getKind() == lltok::APSInt) {
5255 MDSignedField Res = Result.A;
5256 if (!parseMDField(Loc, Name, Res)) {
5257 Result.assign(Res);
5258 return false;
5259 }
5260 return true;
5261 }
5262
5263 // Otherwise, try to parse as an MDField.
5264 MDField Res = Result.B;
5265 if (!parseMDField(Loc, Name, Res)) {
5266 Result.assign(Res);
5267 return false;
5268 }
5269
5270 return true;
5271}
5272
5273template <>
5274bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5275 MDUnsignedOrMDField &Result) {
5276 // Try to parse an unsigned int.
5277 if (Lex.getKind() == lltok::APSInt) {
5278 MDUnsignedField Res = Result.A;
5279 if (!parseMDField(Loc, Name, Res)) {
5280 Result.assign(Res);
5281 return false;
5282 }
5283 return true;
5284 }
5285
5286 // Otherwise, try to parse as an MDField.
5287 MDField Res = Result.B;
5288 if (!parseMDField(Loc, Name, Res)) {
5289 Result.assign(Res);
5290 return false;
5291 }
5292
5293 return true;
5294}
5295
5296template <>
5297bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5298 LocTy ValueLoc = Lex.getLoc();
5299 std::string S;
5300 if (parseStringConstant(S))
5301 return true;
5302
5303 if (S.empty()) {
5304 switch (Result.EmptyIs) {
5305 case MDStringField::EmptyIs::Null:
5306 Result.assign(nullptr);
5307 return false;
5308 case MDStringField::EmptyIs::Empty:
5309 break;
5310 case MDStringField::EmptyIs::Error:
5311 return error(ValueLoc, "'" + Name + "' cannot be empty");
5312 }
5313 }
5314
5315 Result.assign(MDString::get(Context, S));
5316 return false;
5317}
5318
5319template <>
5320bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5322 if (parseMDNodeVector(MDs))
5323 return true;
5324
5325 Result.assign(std::move(MDs));
5326 return false;
5327}
5328
5329template <>
5330bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5331 ChecksumKindField &Result) {
5332 std::optional<DIFile::ChecksumKind> CSKind =
5333 DIFile::getChecksumKind(Lex.getStrVal());
5334
5335 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5336 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5337 "'");
5338
5339 Result.assign(*CSKind);
5340 Lex.Lex();
5341 return false;
5342}
5343
5344} // end namespace llvm
5345
5346template <class ParserTy>
5347bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5348 do {
5349 if (Lex.getKind() != lltok::LabelStr)
5350 return tokError("expected field label here");
5351
5352 if (ParseField())
5353 return true;
5354 } while (EatIfPresent(lltok::comma));
5355
5356 return false;
5357}
5358
5359template <class ParserTy>
5360bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5361 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5362 Lex.Lex();
5363
5364 if (parseToken(lltok::lparen, "expected '(' here"))
5365 return true;
5366 if (Lex.getKind() != lltok::rparen)
5367 if (parseMDFieldsImplBody(ParseField))
5368 return true;
5369
5370 ClosingLoc = Lex.getLoc();
5371 return parseToken(lltok::rparen, "expected ')' here");
5372}
5373
5374template <class FieldTy>
5375bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5376 if (Result.Seen)
5377 return tokError("field '" + Name + "' cannot be specified more than once");
5378
5379 LocTy Loc = Lex.getLoc();
5380 Lex.Lex();
5381 return parseMDField(Loc, Name, Result);
5382}
5383
5384bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5385 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5386
5387#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5388 if (Lex.getStrVal() == #CLASS) \
5389 return parse##CLASS(N, IsDistinct);
5390#include "llvm/IR/Metadata.def"
5391
5392 return tokError("expected metadata type");
5393}
5394
5395#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5396#define NOP_FIELD(NAME, TYPE, INIT)
5397#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5398 if (!NAME.Seen) \
5399 return error(ClosingLoc, "missing required field '" #NAME "'");
5400#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5401 if (Lex.getStrVal() == #NAME) \
5402 return parseMDField(#NAME, NAME);
5403#define PARSE_MD_FIELDS() \
5404 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5405 do { \
5406 LocTy ClosingLoc; \
5407 if (parseMDFieldsImpl( \
5408 [&]() -> bool { \
5409 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5410 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5411 "'"); \
5412 }, \
5413 ClosingLoc)) \
5414 return true; \
5415 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5416 } while (false)
5417#define GET_OR_DISTINCT(CLASS, ARGS) \
5418 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5419
5420/// parseDILocationFields:
5421/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5422/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5423bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5424#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5425 OPTIONAL(line, LineField, ); \
5426 OPTIONAL(column, ColumnField, ); \
5427 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5428 OPTIONAL(inlinedAt, MDField, ); \
5429 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5430 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5431 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5433#undef VISIT_MD_FIELDS
5434
5435 Result = GET_OR_DISTINCT(
5436 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5437 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5438 return false;
5439}
5440
5441/// parseDIAssignID:
5442/// ::= distinct !DIAssignID()
5443bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5444 if (!IsDistinct)
5445 return tokError("missing 'distinct', required for !DIAssignID()");
5446
5447 Lex.Lex();
5448
5449 // Now eat the parens.
5450 if (parseToken(lltok::lparen, "expected '(' here"))
5451 return true;
5452 if (parseToken(lltok::rparen, "expected ')' here"))
5453 return true;
5454
5456 return false;
5457}
5458
5459/// parseGenericDINode:
5460/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5461bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5462#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5463 REQUIRED(tag, DwarfTagField, ); \
5464 OPTIONAL(header, MDStringField, ); \
5465 OPTIONAL(operands, MDFieldList, );
5467#undef VISIT_MD_FIELDS
5468
5469 Result = GET_OR_DISTINCT(GenericDINode,
5470 (Context, tag.Val, header.Val, operands.Val));
5471 return false;
5472}
5473
5474/// parseDISubrangeType:
5475/// ::= !DISubrangeType(name: "whatever", file: !0,
5476/// line: 7, scope: !1, baseType: !2, size: 32,
5477/// align: 32, flags: 0, lowerBound: !3
5478/// upperBound: !4, stride: !5, bias: !6)
5479bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5480#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5481 OPTIONAL(name, MDStringField, ); \
5482 OPTIONAL(file, MDField, ); \
5483 OPTIONAL(line, LineField, ); \
5484 OPTIONAL(scope, MDField, ); \
5485 OPTIONAL(baseType, MDField, ); \
5486 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5487 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5488 OPTIONAL(flags, DIFlagField, ); \
5489 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5490 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5491 OPTIONAL(stride, MDSignedOrMDField, ); \
5492 OPTIONAL(bias, MDSignedOrMDField, );
5494#undef VISIT_MD_FIELDS
5495
5496 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5497 if (Bound.isMDSignedField())
5499 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5500 if (Bound.isMDField())
5501 return Bound.getMDFieldValue();
5502 return nullptr;
5503 };
5504
5505 Metadata *LowerBound = convToMetadata(lowerBound);
5506 Metadata *UpperBound = convToMetadata(upperBound);
5507 Metadata *Stride = convToMetadata(stride);
5508 Metadata *Bias = convToMetadata(bias);
5509
5511 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5512 size.getValueAsMetadata(Context), align.Val, flags.Val,
5513 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5514
5515 return false;
5516}
5517
5518/// parseDISubrange:
5519/// ::= !DISubrange(count: 30, lowerBound: 2)
5520/// ::= !DISubrange(count: !node, lowerBound: 2)
5521/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5522bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5523#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5524 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5525 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5526 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5527 OPTIONAL(stride, MDSignedOrMDField, );
5529#undef VISIT_MD_FIELDS
5530
5531 Metadata *Count = nullptr;
5532 Metadata *LowerBound = nullptr;
5533 Metadata *UpperBound = nullptr;
5534 Metadata *Stride = nullptr;
5535
5536 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5537 if (Bound.isMDSignedField())
5539 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5540 if (Bound.isMDField())
5541 return Bound.getMDFieldValue();
5542 return nullptr;
5543 };
5544
5545 Count = convToMetadata(count);
5546 LowerBound = convToMetadata(lowerBound);
5547 UpperBound = convToMetadata(upperBound);
5548 Stride = convToMetadata(stride);
5549
5550 Result = GET_OR_DISTINCT(DISubrange,
5551 (Context, Count, LowerBound, UpperBound, Stride));
5552
5553 return false;
5554}
5555
5556/// parseDIGenericSubrange:
5557/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5558/// !node3)
5559bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5560#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5561 OPTIONAL(count, MDSignedOrMDField, ); \
5562 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5563 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5564 OPTIONAL(stride, MDSignedOrMDField, );
5566#undef VISIT_MD_FIELDS
5567
5568 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5569 if (Bound.isMDSignedField())
5570 return DIExpression::get(
5571 Context, {dwarf::DW_OP_consts,
5572 static_cast<uint64_t>(Bound.getMDSignedValue())});
5573 if (Bound.isMDField())
5574 return Bound.getMDFieldValue();
5575 return nullptr;
5576 };
5577
5578 Metadata *Count = ConvToMetadata(count);
5579 Metadata *LowerBound = ConvToMetadata(lowerBound);
5580 Metadata *UpperBound = ConvToMetadata(upperBound);
5581 Metadata *Stride = ConvToMetadata(stride);
5582
5583 Result = GET_OR_DISTINCT(DIGenericSubrange,
5584 (Context, Count, LowerBound, UpperBound, Stride));
5585
5586 return false;
5587}
5588
5589/// parseDIEnumerator:
5590/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5591bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5592#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5593 REQUIRED(name, MDStringField, ); \
5594 REQUIRED(value, MDAPSIntField, ); \
5595 OPTIONAL(isUnsigned, MDBoolField, (false));
5597#undef VISIT_MD_FIELDS
5598
5599 if (isUnsigned.Val && value.Val.isNegative())
5600 return tokError("unsigned enumerator with negative value");
5601
5602 APSInt Value(value.Val);
5603 // Add a leading zero so that unsigned values with the msb set are not
5604 // mistaken for negative values when used for signed enumerators.
5605 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5606 Value = Value.zext(Value.getBitWidth() + 1);
5607
5608 Result =
5609 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5610
5611 return false;
5612}
5613
5614/// parseDIBasicType:
5615/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5616/// encoding: DW_ATE_encoding, flags: 0)
5617bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5618#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5619 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5620 OPTIONAL(name, MDStringField, ); \
5621 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5622 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5623 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5624 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5625 OPTIONAL(flags, DIFlagField, );
5627#undef VISIT_MD_FIELDS
5628
5629 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val,
5630 size.getValueAsMetadata(Context),
5631 align.Val, encoding.Val,
5632 num_extra_inhabitants.Val, flags.Val));
5633 return false;
5634}
5635
5636/// parseDIFixedPointType:
5637/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5638/// align: 32, encoding: DW_ATE_signed_fixed,
5639/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5640/// denominator: 8)
5641bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5642#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5643 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5644 OPTIONAL(name, MDStringField, ); \
5645 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5646 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5647 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5648 OPTIONAL(flags, DIFlagField, ); \
5649 OPTIONAL(kind, FixedPointKindField, ); \
5650 OPTIONAL(factor, MDSignedField, ); \
5651 OPTIONAL(numerator, MDAPSIntField, ); \
5652 OPTIONAL(denominator, MDAPSIntField, );
5654#undef VISIT_MD_FIELDS
5655
5656 Result = GET_OR_DISTINCT(DIFixedPointType,
5657 (Context, tag.Val, name.Val,
5658 size.getValueAsMetadata(Context), align.Val,
5659 encoding.Val, flags.Val, kind.Val, factor.Val,
5660 numerator.Val, denominator.Val));
5661 return false;
5662}
5663
5664/// parseDIStringType:
5665/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5666bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5667#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5668 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5669 OPTIONAL(name, MDStringField, ); \
5670 OPTIONAL(stringLength, MDField, ); \
5671 OPTIONAL(stringLengthExpression, MDField, ); \
5672 OPTIONAL(stringLocationExpression, MDField, ); \
5673 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5674 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5675 OPTIONAL(encoding, DwarfAttEncodingField, );
5677#undef VISIT_MD_FIELDS
5678
5680 DIStringType,
5681 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5682 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5683 align.Val, encoding.Val));
5684 return false;
5685}
5686
5687/// parseDIDerivedType:
5688/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5689/// line: 7, scope: !1, baseType: !2, size: 32,
5690/// align: 32, offset: 0, flags: 0, extraData: !3,
5691/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5692/// ptrAuthIsAddressDiscriminated: true,
5693/// ptrAuthExtraDiscriminator: 0x1234,
5694/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5695/// )
5696bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5698 REQUIRED(tag, DwarfTagField, ); \
5699 OPTIONAL(name, MDStringField, ); \
5700 OPTIONAL(file, MDField, ); \
5701 OPTIONAL(line, LineField, ); \
5702 OPTIONAL(scope, MDField, ); \
5703 REQUIRED(baseType, MDField, ); \
5704 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5705 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5706 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5707 OPTIONAL(flags, DIFlagField, ); \
5708 OPTIONAL(extraData, MDField, ); \
5709 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5710 OPTIONAL(annotations, MDField, ); \
5711 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5712 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5713 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5714 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5715 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5717#undef VISIT_MD_FIELDS
5718
5719 std::optional<unsigned> DWARFAddressSpace;
5720 if (dwarfAddressSpace.Val != UINT32_MAX)
5721 DWARFAddressSpace = dwarfAddressSpace.Val;
5722 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5723 if (ptrAuthKey.Val)
5724 PtrAuthData.emplace(
5725 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5726 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5727 ptrAuthAuthenticatesNullValues.Val);
5728
5730 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5731 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5732 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5733 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5734 return false;
5735}
5736
5737bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5738#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5739 REQUIRED(tag, DwarfTagField, ); \
5740 OPTIONAL(name, MDStringField, ); \
5741 OPTIONAL(file, MDField, ); \
5742 OPTIONAL(line, LineField, ); \
5743 OPTIONAL(scope, MDField, ); \
5744 OPTIONAL(baseType, MDField, ); \
5745 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5746 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5747 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5748 OPTIONAL(flags, DIFlagField, ); \
5749 OPTIONAL(elements, MDField, ); \
5750 OPTIONAL(runtimeLang, DwarfLangField, ); \
5751 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5752 OPTIONAL(vtableHolder, MDField, ); \
5753 OPTIONAL(templateParams, MDField, ); \
5754 OPTIONAL(identifier, MDStringField, ); \
5755 OPTIONAL(discriminator, MDField, ); \
5756 OPTIONAL(dataLocation, MDField, ); \
5757 OPTIONAL(associated, MDField, ); \
5758 OPTIONAL(allocated, MDField, ); \
5759 OPTIONAL(rank, MDSignedOrMDField, ); \
5760 OPTIONAL(annotations, MDField, ); \
5761 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5762 OPTIONAL(specification, MDField, ); \
5763 OPTIONAL(bitStride, MDField, );
5765#undef VISIT_MD_FIELDS
5766
5767 Metadata *Rank = nullptr;
5768 if (rank.isMDSignedField())
5770 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5771 else if (rank.isMDField())
5772 Rank = rank.getMDFieldValue();
5773
5774 std::optional<unsigned> EnumKind;
5775 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5776 EnumKind = enumKind.Val;
5777
5778 // If this has an identifier try to build an ODR type.
5779 if (identifier.Val)
5780 if (auto *CT = DICompositeType::buildODRType(
5781 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5782 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
5783 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5784 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5785 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5786 dataLocation.Val, associated.Val, allocated.Val, Rank,
5787 annotations.Val, bitStride.Val)) {
5788 Result = CT;
5789 return false;
5790 }
5791
5792 // Create a new node, and save it in the context if it belongs in the type
5793 // map.
5795 DICompositeType,
5796 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5797 size.getValueAsMetadata(Context), align.Val,
5798 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5799 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5800 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5801 allocated.Val, Rank, annotations.Val, specification.Val,
5802 num_extra_inhabitants.Val, bitStride.Val));
5803 return false;
5804}
5805
5806bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5807#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5808 OPTIONAL(flags, DIFlagField, ); \
5809 OPTIONAL(cc, DwarfCCField, ); \
5810 REQUIRED(types, MDField, );
5812#undef VISIT_MD_FIELDS
5813
5814 Result = GET_OR_DISTINCT(DISubroutineType,
5815 (Context, flags.Val, cc.Val, types.Val));
5816 return false;
5817}
5818
5819/// parseDIFileType:
5820/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5821/// checksumkind: CSK_MD5,
5822/// checksum: "000102030405060708090a0b0c0d0e0f",
5823/// source: "source file contents")
5824bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5825 // The default constructed value for checksumkind is required, but will never
5826 // be used, as the parser checks if the field was actually Seen before using
5827 // the Val.
5828#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5829 REQUIRED(filename, MDStringField, ); \
5830 REQUIRED(directory, MDStringField, ); \
5831 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5832 OPTIONAL(checksum, MDStringField, ); \
5833 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5835#undef VISIT_MD_FIELDS
5836
5837 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5838 if (checksumkind.Seen && checksum.Seen)
5839 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5840 else if (checksumkind.Seen || checksum.Seen)
5841 return tokError("'checksumkind' and 'checksum' must be provided together");
5842
5843 MDString *Source = nullptr;
5844 if (source.Seen)
5845 Source = source.Val;
5847 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5848 return false;
5849}
5850
5851/// parseDICompileUnit:
5852/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5853/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5854/// splitDebugFilename: "abc.debug",
5855/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5856/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5857/// sysroot: "/", sdk: "MacOSX.sdk")
5858bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5859 if (!IsDistinct)
5860 return tokError("missing 'distinct', required for !DICompileUnit");
5861
5862 LocTy Loc = Lex.getLoc();
5863
5864#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5865 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5866 OPTIONAL(language, DwarfLangField, ); \
5867 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
5868 OPTIONAL(producer, MDStringField, ); \
5869 OPTIONAL(isOptimized, MDBoolField, ); \
5870 OPTIONAL(flags, MDStringField, ); \
5871 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5872 OPTIONAL(splitDebugFilename, MDStringField, ); \
5873 OPTIONAL(emissionKind, EmissionKindField, ); \
5874 OPTIONAL(enums, MDField, ); \
5875 OPTIONAL(retainedTypes, MDField, ); \
5876 OPTIONAL(globals, MDField, ); \
5877 OPTIONAL(imports, MDField, ); \
5878 OPTIONAL(macros, MDField, ); \
5879 OPTIONAL(dwoId, MDUnsignedField, ); \
5880 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5881 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5882 OPTIONAL(nameTableKind, NameTableKindField, ); \
5883 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5884 OPTIONAL(sysroot, MDStringField, ); \
5885 OPTIONAL(sdk, MDStringField, );
5887#undef VISIT_MD_FIELDS
5888
5889 if (!language.Seen && !sourceLanguageName.Seen)
5890 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
5891 "required for !DICompileUnit");
5892
5893 if (language.Seen && sourceLanguageName.Seen)
5894 return error(Loc, "can only specify one of 'language' and "
5895 "'sourceLanguageName' on !DICompileUnit");
5896
5898 Context,
5899 language.Seen ? DISourceLanguageName(language.Val)
5900 : DISourceLanguageName(sourceLanguageName.Val, 0),
5901 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
5902 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
5903 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
5904 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
5905 sysroot.Val, sdk.Val);
5906 return false;
5907}
5908
5909/// parseDISubprogram:
5910/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5911/// file: !1, line: 7, type: !2, isLocal: false,
5912/// isDefinition: true, scopeLine: 8, containingType: !3,
5913/// virtuality: DW_VIRTUALTIY_pure_virtual,
5914/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5915/// spFlags: 10, isOptimized: false, templateParams: !4,
5916/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5917/// annotations: !8)
5918bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5919 auto Loc = Lex.getLoc();
5920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5921 OPTIONAL(scope, MDField, ); \
5922 OPTIONAL(name, MDStringField, ); \
5923 OPTIONAL(linkageName, MDStringField, ); \
5924 OPTIONAL(file, MDField, ); \
5925 OPTIONAL(line, LineField, ); \
5926 OPTIONAL(type, MDField, ); \
5927 OPTIONAL(isLocal, MDBoolField, ); \
5928 OPTIONAL(isDefinition, MDBoolField, (true)); \
5929 OPTIONAL(scopeLine, LineField, ); \
5930 OPTIONAL(containingType, MDField, ); \
5931 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5932 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5933 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5934 OPTIONAL(flags, DIFlagField, ); \
5935 OPTIONAL(spFlags, DISPFlagField, ); \
5936 OPTIONAL(isOptimized, MDBoolField, ); \
5937 OPTIONAL(unit, MDField, ); \
5938 OPTIONAL(templateParams, MDField, ); \
5939 OPTIONAL(declaration, MDField, ); \
5940 OPTIONAL(retainedNodes, MDField, ); \
5941 OPTIONAL(thrownTypes, MDField, ); \
5942 OPTIONAL(annotations, MDField, ); \
5943 OPTIONAL(targetFuncName, MDStringField, ); \
5944 OPTIONAL(keyInstructions, MDBoolField, );
5946#undef VISIT_MD_FIELDS
5947
5948 // An explicit spFlags field takes precedence over individual fields in
5949 // older IR versions.
5950 DISubprogram::DISPFlags SPFlags =
5951 spFlags.Seen ? spFlags.Val
5952 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5953 isOptimized.Val, virtuality.Val);
5954 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5955 return error(
5956 Loc,
5957 "missing 'distinct', required for !DISubprogram that is a Definition");
5959 DISubprogram,
5960 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5961 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5962 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5963 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5964 targetFuncName.Val, keyInstructions.Val));
5965 return false;
5966}
5967
5968/// parseDILexicalBlock:
5969/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5970bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5971#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5972 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5973 OPTIONAL(file, MDField, ); \
5974 OPTIONAL(line, LineField, ); \
5975 OPTIONAL(column, ColumnField, );
5977#undef VISIT_MD_FIELDS
5978
5980 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5981 return false;
5982}
5983
5984/// parseDILexicalBlockFile:
5985/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5986bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5987#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5988 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5989 OPTIONAL(file, MDField, ); \
5990 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5992#undef VISIT_MD_FIELDS
5993
5994 Result = GET_OR_DISTINCT(DILexicalBlockFile,
5995 (Context, scope.Val, file.Val, discriminator.Val));
5996 return false;
5997}
5998
5999/// parseDICommonBlock:
6000/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6001bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6003 REQUIRED(scope, MDField, ); \
6004 OPTIONAL(declaration, MDField, ); \
6005 OPTIONAL(name, MDStringField, ); \
6006 OPTIONAL(file, MDField, ); \
6007 OPTIONAL(line, LineField, );
6009#undef VISIT_MD_FIELDS
6010
6011 Result = GET_OR_DISTINCT(DICommonBlock,
6012 (Context, scope.Val, declaration.Val, name.Val,
6013 file.Val, line.Val));
6014 return false;
6015}
6016
6017/// parseDINamespace:
6018/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6019bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6020#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6021 REQUIRED(scope, MDField, ); \
6022 OPTIONAL(name, MDStringField, ); \
6023 OPTIONAL(exportSymbols, MDBoolField, );
6025#undef VISIT_MD_FIELDS
6026
6027 Result = GET_OR_DISTINCT(DINamespace,
6028 (Context, scope.Val, name.Val, exportSymbols.Val));
6029 return false;
6030}
6031
6032/// parseDIMacro:
6033/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6034/// "SomeValue")
6035bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6036#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6037 REQUIRED(type, DwarfMacinfoTypeField, ); \
6038 OPTIONAL(line, LineField, ); \
6039 REQUIRED(name, MDStringField, ); \
6040 OPTIONAL(value, MDStringField, );
6042#undef VISIT_MD_FIELDS
6043
6044 Result = GET_OR_DISTINCT(DIMacro,
6045 (Context, type.Val, line.Val, name.Val, value.Val));
6046 return false;
6047}
6048
6049/// parseDIMacroFile:
6050/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6051bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6052#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6053 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6054 OPTIONAL(line, LineField, ); \
6055 REQUIRED(file, MDField, ); \
6056 OPTIONAL(nodes, MDField, );
6058#undef VISIT_MD_FIELDS
6059
6060 Result = GET_OR_DISTINCT(DIMacroFile,
6061 (Context, type.Val, line.Val, file.Val, nodes.Val));
6062 return false;
6063}
6064
6065/// parseDIModule:
6066/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6067/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6068/// file: !1, line: 4, isDecl: false)
6069bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6070#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6071 REQUIRED(scope, MDField, ); \
6072 REQUIRED(name, MDStringField, ); \
6073 OPTIONAL(configMacros, MDStringField, ); \
6074 OPTIONAL(includePath, MDStringField, ); \
6075 OPTIONAL(apinotes, MDStringField, ); \
6076 OPTIONAL(file, MDField, ); \
6077 OPTIONAL(line, LineField, ); \
6078 OPTIONAL(isDecl, MDBoolField, );
6080#undef VISIT_MD_FIELDS
6081
6082 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6083 configMacros.Val, includePath.Val,
6084 apinotes.Val, line.Val, isDecl.Val));
6085 return false;
6086}
6087
6088/// parseDITemplateTypeParameter:
6089/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6090bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6091#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6092 OPTIONAL(name, MDStringField, ); \
6093 REQUIRED(type, MDField, ); \
6094 OPTIONAL(defaulted, MDBoolField, );
6096#undef VISIT_MD_FIELDS
6097
6098 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6099 (Context, name.Val, type.Val, defaulted.Val));
6100 return false;
6101}
6102
6103/// parseDITemplateValueParameter:
6104/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6105/// name: "V", type: !1, defaulted: false,
6106/// value: i32 7)
6107bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6108#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6109 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6110 OPTIONAL(name, MDStringField, ); \
6111 OPTIONAL(type, MDField, ); \
6112 OPTIONAL(defaulted, MDBoolField, ); \
6113 REQUIRED(value, MDField, );
6114
6116#undef VISIT_MD_FIELDS
6117
6119 DITemplateValueParameter,
6120 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6121 return false;
6122}
6123
6124/// parseDIGlobalVariable:
6125/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6126/// file: !1, line: 7, type: !2, isLocal: false,
6127/// isDefinition: true, templateParams: !3,
6128/// declaration: !4, align: 8)
6129bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6130#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6131 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6132 OPTIONAL(scope, MDField, ); \
6133 OPTIONAL(linkageName, MDStringField, ); \
6134 OPTIONAL(file, MDField, ); \
6135 OPTIONAL(line, LineField, ); \
6136 OPTIONAL(type, MDField, ); \
6137 OPTIONAL(isLocal, MDBoolField, ); \
6138 OPTIONAL(isDefinition, MDBoolField, (true)); \
6139 OPTIONAL(templateParams, MDField, ); \
6140 OPTIONAL(declaration, MDField, ); \
6141 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6142 OPTIONAL(annotations, MDField, );
6144#undef VISIT_MD_FIELDS
6145
6146 Result =
6147 GET_OR_DISTINCT(DIGlobalVariable,
6148 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6149 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6150 declaration.Val, templateParams.Val, align.Val,
6151 annotations.Val));
6152 return false;
6153}
6154
6155/// parseDILocalVariable:
6156/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6157/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6158/// align: 8)
6159/// ::= !DILocalVariable(scope: !0, name: "foo",
6160/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6161/// align: 8)
6162bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6163#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6164 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6165 OPTIONAL(name, MDStringField, ); \
6166 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6167 OPTIONAL(file, MDField, ); \
6168 OPTIONAL(line, LineField, ); \
6169 OPTIONAL(type, MDField, ); \
6170 OPTIONAL(flags, DIFlagField, ); \
6171 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6172 OPTIONAL(annotations, MDField, );
6174#undef VISIT_MD_FIELDS
6175
6176 Result = GET_OR_DISTINCT(DILocalVariable,
6177 (Context, scope.Val, name.Val, file.Val, line.Val,
6178 type.Val, arg.Val, flags.Val, align.Val,
6179 annotations.Val));
6180 return false;
6181}
6182
6183/// parseDILabel:
6184/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6185bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6186#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6187 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6188 REQUIRED(name, MDStringField, ); \
6189 REQUIRED(file, MDField, ); \
6190 REQUIRED(line, LineField, ); \
6191 OPTIONAL(column, ColumnField, ); \
6192 OPTIONAL(isArtificial, MDBoolField, ); \
6193 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6195#undef VISIT_MD_FIELDS
6196
6197 std::optional<unsigned> CoroSuspendIdx =
6198 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6199 : std::nullopt;
6200
6201 Result = GET_OR_DISTINCT(DILabel,
6202 (Context, scope.Val, name.Val, file.Val, line.Val,
6203 column.Val, isArtificial.Val, CoroSuspendIdx));
6204 return false;
6205}
6206
6207/// parseDIExpressionBody:
6208/// ::= (0, 7, -1)
6209bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6210 if (parseToken(lltok::lparen, "expected '(' here"))
6211 return true;
6212
6213 SmallVector<uint64_t, 8> Elements;
6214 if (Lex.getKind() != lltok::rparen)
6215 do {
6216 if (Lex.getKind() == lltok::DwarfOp) {
6217 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6218 Lex.Lex();
6219 Elements.push_back(Op);
6220 continue;
6221 }
6222 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6223 }
6224
6225 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6226 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6227 Lex.Lex();
6228 Elements.push_back(Op);
6229 continue;
6230 }
6231 return tokError(Twine("invalid DWARF attribute encoding '") +
6232 Lex.getStrVal() + "'");
6233 }
6234
6235 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6236 return tokError("expected unsigned integer");
6237
6238 auto &U = Lex.getAPSIntVal();
6239 if (U.ugt(UINT64_MAX))
6240 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6241 Elements.push_back(U.getZExtValue());
6242 Lex.Lex();
6243 } while (EatIfPresent(lltok::comma));
6244
6245 if (parseToken(lltok::rparen, "expected ')' here"))
6246 return true;
6247
6248 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6249 return false;
6250}
6251
6252/// parseDIExpression:
6253/// ::= !DIExpression(0, 7, -1)
6254bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6255 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6256 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6257 Lex.Lex();
6258
6259 return parseDIExpressionBody(Result, IsDistinct);
6260}
6261
6262/// ParseDIArgList:
6263/// ::= !DIArgList(i32 7, i64 %0)
6264bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6265 assert(PFS && "Expected valid function state");
6266 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6267 Lex.Lex();
6268
6269 if (parseToken(lltok::lparen, "expected '(' here"))
6270 return true;
6271
6273 if (Lex.getKind() != lltok::rparen)
6274 do {
6275 Metadata *MD;
6276 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6277 return true;
6278 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6279 } while (EatIfPresent(lltok::comma));
6280
6281 if (parseToken(lltok::rparen, "expected ')' here"))
6282 return true;
6283
6284 MD = DIArgList::get(Context, Args);
6285 return false;
6286}
6287
6288/// parseDIGlobalVariableExpression:
6289/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6290bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6291 bool IsDistinct) {
6292#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6293 REQUIRED(var, MDField, ); \
6294 REQUIRED(expr, MDField, );
6296#undef VISIT_MD_FIELDS
6297
6298 Result =
6299 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6300 return false;
6301}
6302
6303/// parseDIObjCProperty:
6304/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6305/// getter: "getFoo", attributes: 7, type: !2)
6306bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6307#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6308 OPTIONAL(name, MDStringField, ); \
6309 OPTIONAL(file, MDField, ); \
6310 OPTIONAL(line, LineField, ); \
6311 OPTIONAL(setter, MDStringField, ); \
6312 OPTIONAL(getter, MDStringField, ); \
6313 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6314 OPTIONAL(type, MDField, );
6316#undef VISIT_MD_FIELDS
6317
6318 Result = GET_OR_DISTINCT(DIObjCProperty,
6319 (Context, name.Val, file.Val, line.Val, setter.Val,
6320 getter.Val, attributes.Val, type.Val));
6321 return false;
6322}
6323
6324/// parseDIImportedEntity:
6325/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6326/// line: 7, name: "foo", elements: !2)
6327bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6328#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6329 REQUIRED(tag, DwarfTagField, ); \
6330 REQUIRED(scope, MDField, ); \
6331 OPTIONAL(entity, MDField, ); \
6332 OPTIONAL(file, MDField, ); \
6333 OPTIONAL(line, LineField, ); \
6334 OPTIONAL(name, MDStringField, ); \
6335 OPTIONAL(elements, MDField, );
6337#undef VISIT_MD_FIELDS
6338
6339 Result = GET_OR_DISTINCT(DIImportedEntity,
6340 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6341 line.Val, name.Val, elements.Val));
6342 return false;
6343}
6344
6345#undef PARSE_MD_FIELD
6346#undef NOP_FIELD
6347#undef REQUIRE_FIELD
6348#undef DECLARE_FIELD
6349
6350/// parseMetadataAsValue
6351/// ::= metadata i32 %local
6352/// ::= metadata i32 @global
6353/// ::= metadata i32 7
6354/// ::= metadata !0
6355/// ::= metadata !{...}
6356/// ::= metadata !"string"
6357bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6358 // Note: the type 'metadata' has already been parsed.
6359 Metadata *MD;
6360 if (parseMetadata(MD, &PFS))
6361 return true;
6362
6363 V = MetadataAsValue::get(Context, MD);
6364 return false;
6365}
6366
6367/// parseValueAsMetadata
6368/// ::= i32 %local
6369/// ::= i32 @global
6370/// ::= i32 7
6371bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6372 PerFunctionState *PFS) {
6373 Type *Ty;
6374 LocTy Loc;
6375 if (parseType(Ty, TypeMsg, Loc))
6376 return true;
6377 if (Ty->isMetadataTy())
6378 return error(Loc, "invalid metadata-value-metadata roundtrip");
6379
6380 Value *V;
6381 if (parseValue(Ty, V, PFS))
6382 return true;
6383
6384 MD = ValueAsMetadata::get(V);
6385 return false;
6386}
6387
6388/// parseMetadata
6389/// ::= i32 %local
6390/// ::= i32 @global
6391/// ::= i32 7
6392/// ::= !42
6393/// ::= !{...}
6394/// ::= !"string"
6395/// ::= !DILocation(...)
6396bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6397 if (Lex.getKind() == lltok::MetadataVar) {
6398 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6399 // so parsing this requires a Function State.
6400 if (Lex.getStrVal() == "DIArgList") {
6401 Metadata *AL;
6402 if (parseDIArgList(AL, PFS))
6403 return true;
6404 MD = AL;
6405 return false;
6406 }
6407 MDNode *N;
6408 if (parseSpecializedMDNode(N)) {
6409 return true;
6410 }
6411 MD = N;
6412 return false;
6413 }
6414
6415 // ValueAsMetadata:
6416 // <type> <value>
6417 if (Lex.getKind() != lltok::exclaim)
6418 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6419
6420 // '!'.
6421 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6422 Lex.Lex();
6423
6424 // MDString:
6425 // ::= '!' STRINGCONSTANT
6426 if (Lex.getKind() == lltok::StringConstant) {
6427 MDString *S;
6428 if (parseMDString(S))
6429 return true;
6430 MD = S;
6431 return false;
6432 }
6433
6434 // MDNode:
6435 // !{ ... }
6436 // !7
6437 MDNode *N;
6438 if (parseMDNodeTail(N))
6439 return true;
6440 MD = N;
6441 return false;
6442}
6443
6444//===----------------------------------------------------------------------===//
6445// Function Parsing.
6446//===----------------------------------------------------------------------===//
6447
6448bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6449 PerFunctionState *PFS) {
6450 if (Ty->isFunctionTy())
6451 return error(ID.Loc, "functions are not values, refer to them as pointers");
6452
6453 switch (ID.Kind) {
6454 case ValID::t_LocalID:
6455 if (!PFS)
6456 return error(ID.Loc, "invalid use of function-local name");
6457 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6458 return V == nullptr;
6459 case ValID::t_LocalName:
6460 if (!PFS)
6461 return error(ID.Loc, "invalid use of function-local name");
6462 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6463 return V == nullptr;
6464 case ValID::t_InlineAsm: {
6465 if (!ID.FTy)
6466 return error(ID.Loc, "invalid type for inline asm constraint string");
6467 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6468 return error(ID.Loc, toString(std::move(Err)));
6469 V = InlineAsm::get(
6470 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6471 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6472 return false;
6473 }
6475 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6476 if (V && ID.NoCFI)
6478 return V == nullptr;
6479 case ValID::t_GlobalID:
6480 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6481 if (V && ID.NoCFI)
6483 return V == nullptr;
6484 case ValID::t_APSInt:
6485 if (!Ty->isIntegerTy())
6486 return error(ID.Loc, "integer constant must have integer type");
6487 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6488 V = ConstantInt::get(Context, ID.APSIntVal);
6489 return false;
6490 case ValID::t_APFloat:
6491 if (!Ty->isFloatingPointTy() ||
6492 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6493 return error(ID.Loc, "floating point constant invalid for type");
6494
6495 // The lexer has no type info, so builds all half, bfloat, float, and double
6496 // FP constants as double. Fix this here. Long double does not need this.
6497 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6498 // Check for signaling before potentially converting and losing that info.
6499 bool IsSNAN = ID.APFloatVal.isSignaling();
6500 bool Ignored;
6501 if (Ty->isHalfTy())
6503 &Ignored);
6504 else if (Ty->isBFloatTy())
6505 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6506 &Ignored);
6507 else if (Ty->isFloatTy())
6509 &Ignored);
6510 if (IsSNAN) {
6511 // The convert call above may quiet an SNaN, so manufacture another
6512 // SNaN. The bitcast works because the payload (significand) parameter
6513 // is truncated to fit.
6514 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6515 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6516 ID.APFloatVal.isNegative(), &Payload);
6517 }
6518 }
6519 V = ConstantFP::get(Context, ID.APFloatVal);
6520
6521 if (V->getType() != Ty)
6522 return error(ID.Loc, "floating point constant does not have type '" +
6523 getTypeString(Ty) + "'");
6524
6525 return false;
6526 case ValID::t_Null:
6527 if (!Ty->isPointerTy())
6528 return error(ID.Loc, "null must be a pointer type");
6530 return false;
6531 case ValID::t_Undef:
6532 // FIXME: LabelTy should not be a first-class type.
6533 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6534 return error(ID.Loc, "invalid type for undef constant");
6535 V = UndefValue::get(Ty);
6536 return false;
6538 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6539 return error(ID.Loc, "invalid empty array initializer");
6540 V = PoisonValue::get(Ty);
6541 return false;
6542 case ValID::t_Zero:
6543 // FIXME: LabelTy should not be a first-class type.
6544 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6545 return error(ID.Loc, "invalid type for null constant");
6546 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6547 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6548 return error(ID.Loc, "invalid type for null constant");
6550 return false;
6551 case ValID::t_None:
6552 if (!Ty->isTokenTy())
6553 return error(ID.Loc, "invalid type for none constant");
6555 return false;
6556 case ValID::t_Poison:
6557 // FIXME: LabelTy should not be a first-class type.
6558 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6559 return error(ID.Loc, "invalid type for poison constant");
6560 V = PoisonValue::get(Ty);
6561 return false;
6562 case ValID::t_Constant:
6563 if (ID.ConstantVal->getType() != Ty)
6564 return error(ID.Loc, "constant expression type mismatch: got type '" +
6565 getTypeString(ID.ConstantVal->getType()) +
6566 "' but expected '" + getTypeString(Ty) + "'");
6567 V = ID.ConstantVal;
6568 return false;
6570 if (!Ty->isVectorTy())
6571 return error(ID.Loc, "vector constant must have vector type");
6572 if (ID.ConstantVal->getType() != Ty->getScalarType())
6573 return error(ID.Loc, "constant expression type mismatch: got type '" +
6574 getTypeString(ID.ConstantVal->getType()) +
6575 "' but expected '" +
6576 getTypeString(Ty->getScalarType()) + "'");
6577 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6578 ID.ConstantVal);
6579 return false;
6582 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6583 if (ST->getNumElements() != ID.UIntVal)
6584 return error(ID.Loc,
6585 "initializer with struct type has wrong # elements");
6586 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6587 return error(ID.Loc, "packed'ness of initializer and type don't match");
6588
6589 // Verify that the elements are compatible with the structtype.
6590 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6591 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6592 return error(
6593 ID.Loc,
6594 "element " + Twine(i) +
6595 " of struct initializer doesn't match struct element type");
6596
6598 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6599 } else
6600 return error(ID.Loc, "constant expression type mismatch");
6601 return false;
6602 }
6603 llvm_unreachable("Invalid ValID");
6604}
6605
6606bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6607 C = nullptr;
6608 ValID ID;
6609 auto Loc = Lex.getLoc();
6610 if (parseValID(ID, /*PFS=*/nullptr))
6611 return true;
6612 switch (ID.Kind) {
6613 case ValID::t_APSInt:
6614 case ValID::t_APFloat:
6615 case ValID::t_Undef:
6616 case ValID::t_Poison:
6617 case ValID::t_Zero:
6618 case ValID::t_Constant:
6622 Value *V;
6623 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6624 return true;
6625 assert(isa<Constant>(V) && "Expected a constant value");
6626 C = cast<Constant>(V);
6627 return false;
6628 }
6629 case ValID::t_Null:
6631 return false;
6632 default:
6633 return error(Loc, "expected a constant value");
6634 }
6635}
6636
6637bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6638 V = nullptr;
6639 ValID ID;
6640 return parseValID(ID, PFS, Ty) ||
6641 convertValIDToValue(Ty, ID, V, PFS);
6642}
6643
6644bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6645 Type *Ty = nullptr;
6646 return parseType(Ty) || parseValue(Ty, V, PFS);
6647}
6648
6649bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6650 PerFunctionState &PFS) {
6651 Value *V;
6652 Loc = Lex.getLoc();
6653 if (parseTypeAndValue(V, PFS))
6654 return true;
6655 if (!isa<BasicBlock>(V))
6656 return error(Loc, "expected a basic block");
6657 BB = cast<BasicBlock>(V);
6658 return false;
6659}
6660
6662 // Exit early for the common (non-debug-intrinsic) case.
6663 // We can make this the only check when we begin supporting all "llvm.dbg"
6664 // intrinsics in the new debug info format.
6665 if (!Name.starts_with("llvm.dbg."))
6666 return false;
6668 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6669 FnID == Intrinsic::dbg_assign;
6670}
6671
6672/// FunctionHeader
6673/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6674/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6675/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6676/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6677bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6678 unsigned &FunctionNumber,
6679 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6680 // parse the linkage.
6681 LocTy LinkageLoc = Lex.getLoc();
6682 unsigned Linkage;
6683 unsigned Visibility;
6684 unsigned DLLStorageClass;
6685 bool DSOLocal;
6686 AttrBuilder RetAttrs(M->getContext());
6687 unsigned CC;
6688 bool HasLinkage;
6689 Type *RetType = nullptr;
6690 LocTy RetTypeLoc = Lex.getLoc();
6691 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6692 DSOLocal) ||
6693 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6694 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6695 return true;
6696
6697 // Verify that the linkage is ok.
6700 break; // always ok.
6702 if (IsDefine)
6703 return error(LinkageLoc, "invalid linkage for function definition");
6704 break;
6712 if (!IsDefine)
6713 return error(LinkageLoc, "invalid linkage for function declaration");
6714 break;
6717 return error(LinkageLoc, "invalid function linkage type");
6718 }
6719
6720 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6721 return error(LinkageLoc,
6722 "symbol with local linkage must have default visibility");
6723
6724 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6725 return error(LinkageLoc,
6726 "symbol with local linkage cannot have a DLL storage class");
6727
6728 if (!FunctionType::isValidReturnType(RetType))
6729 return error(RetTypeLoc, "invalid function return type");
6730
6731 LocTy NameLoc = Lex.getLoc();
6732
6733 std::string FunctionName;
6734 if (Lex.getKind() == lltok::GlobalVar) {
6735 FunctionName = Lex.getStrVal();
6736 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6737 FunctionNumber = Lex.getUIntVal();
6738 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6739 FunctionNumber))
6740 return true;
6741 } else {
6742 return tokError("expected function name");
6743 }
6744
6745 Lex.Lex();
6746
6747 if (Lex.getKind() != lltok::lparen)
6748 return tokError("expected '(' in function argument list");
6749
6751 bool IsVarArg;
6752 AttrBuilder FuncAttrs(M->getContext());
6753 std::vector<unsigned> FwdRefAttrGrps;
6754 LocTy BuiltinLoc;
6755 std::string Section;
6756 std::string Partition;
6757 MaybeAlign Alignment;
6758 std::string GC;
6760 unsigned AddrSpace = 0;
6761 Constant *Prefix = nullptr;
6762 Constant *Prologue = nullptr;
6763 Constant *PersonalityFn = nullptr;
6764 Comdat *C;
6765
6766 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6767 parseOptionalUnnamedAddr(UnnamedAddr) ||
6768 parseOptionalProgramAddrSpace(AddrSpace) ||
6769 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6770 BuiltinLoc) ||
6771 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6772 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6773 parseOptionalComdat(FunctionName, C) ||
6774 parseOptionalAlignment(Alignment) ||
6775 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6776 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6777 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6778 (EatIfPresent(lltok::kw_personality) &&
6779 parseGlobalTypeAndValue(PersonalityFn)))
6780 return true;
6781
6782 if (FuncAttrs.contains(Attribute::Builtin))
6783 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6784
6785 // If the alignment was parsed as an attribute, move to the alignment field.
6786 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6787 Alignment = A;
6788 FuncAttrs.removeAttribute(Attribute::Alignment);
6789 }
6790
6791 // Okay, if we got here, the function is syntactically valid. Convert types
6792 // and do semantic checks.
6793 std::vector<Type*> ParamTypeList;
6795
6796 for (const ArgInfo &Arg : ArgList) {
6797 ParamTypeList.push_back(Arg.Ty);
6798 Attrs.push_back(Arg.Attrs);
6799 }
6800
6801 AttributeList PAL =
6802 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6803 AttributeSet::get(Context, RetAttrs), Attrs);
6804
6805 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6806 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6807
6808 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6809 PointerType *PFT = PointerType::get(Context, AddrSpace);
6810
6811 Fn = nullptr;
6812 GlobalValue *FwdFn = nullptr;
6813 if (!FunctionName.empty()) {
6814 // If this was a definition of a forward reference, remove the definition
6815 // from the forward reference table and fill in the forward ref.
6816 auto FRVI = ForwardRefVals.find(FunctionName);
6817 if (FRVI != ForwardRefVals.end()) {
6818 FwdFn = FRVI->second.first;
6819 if (FwdFn->getType() != PFT)
6820 return error(FRVI->second.second,
6821 "invalid forward reference to "
6822 "function '" +
6823 FunctionName +
6824 "' with wrong type: "
6825 "expected '" +
6826 getTypeString(PFT) + "' but was '" +
6827 getTypeString(FwdFn->getType()) + "'");
6828 ForwardRefVals.erase(FRVI);
6829 } else if ((Fn = M->getFunction(FunctionName))) {
6830 // Reject redefinitions.
6831 return error(NameLoc,
6832 "invalid redefinition of function '" + FunctionName + "'");
6833 } else if (M->getNamedValue(FunctionName)) {
6834 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6835 }
6836
6837 } else {
6838 // Handle @"", where a name is syntactically specified, but semantically
6839 // missing.
6840 if (FunctionNumber == (unsigned)-1)
6841 FunctionNumber = NumberedVals.getNext();
6842
6843 // If this is a definition of a forward referenced function, make sure the
6844 // types agree.
6845 auto I = ForwardRefValIDs.find(FunctionNumber);
6846 if (I != ForwardRefValIDs.end()) {
6847 FwdFn = I->second.first;
6848 if (FwdFn->getType() != PFT)
6849 return error(NameLoc, "type of definition and forward reference of '@" +
6850 Twine(FunctionNumber) +
6851 "' disagree: "
6852 "expected '" +
6853 getTypeString(PFT) + "' but was '" +
6854 getTypeString(FwdFn->getType()) + "'");
6855 ForwardRefValIDs.erase(I);
6856 }
6857 }
6858
6860 FunctionName, M);
6861
6862 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6863
6864 if (FunctionName.empty())
6865 NumberedVals.add(FunctionNumber, Fn);
6866
6868 maybeSetDSOLocal(DSOLocal, *Fn);
6871 Fn->setCallingConv(CC);
6872 Fn->setAttributes(PAL);
6873 Fn->setUnnamedAddr(UnnamedAddr);
6874 if (Alignment)
6875 Fn->setAlignment(*Alignment);
6876 Fn->setSection(Section);
6877 Fn->setPartition(Partition);
6878 Fn->setComdat(C);
6879 Fn->setPersonalityFn(PersonalityFn);
6880 if (!GC.empty()) Fn->setGC(GC);
6881 Fn->setPrefixData(Prefix);
6882 Fn->setPrologueData(Prologue);
6883 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6884
6885 // Add all of the arguments we parsed to the function.
6886 Function::arg_iterator ArgIt = Fn->arg_begin();
6887 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6888 // If the argument has a name, insert it into the argument symbol table.
6889 if (ArgList[i].Name.empty()) continue;
6890
6891 // Set the name, if it conflicted, it will be auto-renamed.
6892 ArgIt->setName(ArgList[i].Name);
6893
6894 if (ArgIt->getName() != ArgList[i].Name)
6895 return error(ArgList[i].Loc,
6896 "redefinition of argument '%" + ArgList[i].Name + "'");
6897 }
6898
6899 if (FwdFn) {
6900 FwdFn->replaceAllUsesWith(Fn);
6901 FwdFn->eraseFromParent();
6902 }
6903
6904 if (IsDefine)
6905 return false;
6906
6907 // Check the declaration has no block address forward references.
6908 ValID ID;
6909 if (FunctionName.empty()) {
6910 ID.Kind = ValID::t_GlobalID;
6911 ID.UIntVal = FunctionNumber;
6912 } else {
6913 ID.Kind = ValID::t_GlobalName;
6914 ID.StrVal = FunctionName;
6915 }
6916 auto Blocks = ForwardRefBlockAddresses.find(ID);
6917 if (Blocks != ForwardRefBlockAddresses.end())
6918 return error(Blocks->first.Loc,
6919 "cannot take blockaddress inside a declaration");
6920 return false;
6921}
6922
6923bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6924 ValID ID;
6925 if (FunctionNumber == -1) {
6926 ID.Kind = ValID::t_GlobalName;
6927 ID.StrVal = std::string(F.getName());
6928 } else {
6929 ID.Kind = ValID::t_GlobalID;
6930 ID.UIntVal = FunctionNumber;
6931 }
6932
6933 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6934 if (Blocks == P.ForwardRefBlockAddresses.end())
6935 return false;
6936
6937 for (const auto &I : Blocks->second) {
6938 const ValID &BBID = I.first;
6939 GlobalValue *GV = I.second;
6940
6941 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6942 "Expected local id or name");
6943 BasicBlock *BB;
6944 if (BBID.Kind == ValID::t_LocalName)
6945 BB = getBB(BBID.StrVal, BBID.Loc);
6946 else
6947 BB = getBB(BBID.UIntVal, BBID.Loc);
6948 if (!BB)
6949 return P.error(BBID.Loc, "referenced value is not a basic block");
6950
6951 Value *ResolvedVal = BlockAddress::get(&F, BB);
6952 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6953 ResolvedVal);
6954 if (!ResolvedVal)
6955 return true;
6956 GV->replaceAllUsesWith(ResolvedVal);
6957 GV->eraseFromParent();
6958 }
6959
6960 P.ForwardRefBlockAddresses.erase(Blocks);
6961 return false;
6962}
6963
6964/// parseFunctionBody
6965/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6966bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6967 ArrayRef<unsigned> UnnamedArgNums) {
6968 if (Lex.getKind() != lltok::lbrace)
6969 return tokError("expected '{' in function body");
6970 Lex.Lex(); // eat the {.
6971
6972 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6973
6974 // Resolve block addresses and allow basic blocks to be forward-declared
6975 // within this function.
6976 if (PFS.resolveForwardRefBlockAddresses())
6977 return true;
6978 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6979
6980 // We need at least one basic block.
6981 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6982 return tokError("function body requires at least one basic block");
6983
6984 while (Lex.getKind() != lltok::rbrace &&
6985 Lex.getKind() != lltok::kw_uselistorder)
6986 if (parseBasicBlock(PFS))
6987 return true;
6988
6989 while (Lex.getKind() != lltok::rbrace)
6990 if (parseUseListOrder(&PFS))
6991 return true;
6992
6993 // Eat the }.
6994 Lex.Lex();
6995
6996 // Verify function is ok.
6997 return PFS.finishFunction();
6998}
6999
7000/// parseBasicBlock
7001/// ::= (LabelStr|LabelID)? Instruction*
7002bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7003 // If this basic block starts out with a name, remember it.
7004 std::string Name;
7005 int NameID = -1;
7006 LocTy NameLoc = Lex.getLoc();
7007 if (Lex.getKind() == lltok::LabelStr) {
7008 Name = Lex.getStrVal();
7009 Lex.Lex();
7010 } else if (Lex.getKind() == lltok::LabelID) {
7011 NameID = Lex.getUIntVal();
7012 Lex.Lex();
7013 }
7014
7015 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7016 if (!BB)
7017 return true;
7018
7019 std::string NameStr;
7020
7021 // Parse the instructions and debug values in this block until we get a
7022 // terminator.
7023 Instruction *Inst;
7024 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7025 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7026 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7027 do {
7028 // Handle debug records first - there should always be an instruction
7029 // following the debug records, i.e. they cannot appear after the block
7030 // terminator.
7031 while (Lex.getKind() == lltok::hash) {
7032 if (SeenOldDbgInfoFormat)
7033 return error(Lex.getLoc(), "debug record should not appear in a module "
7034 "containing debug info intrinsics");
7035 SeenNewDbgInfoFormat = true;
7036 Lex.Lex();
7037
7038 DbgRecord *DR;
7039 if (parseDebugRecord(DR, PFS))
7040 return true;
7041 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7042 }
7043
7044 // This instruction may have three possibilities for a name: a) none
7045 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7046 LocTy NameLoc = Lex.getLoc();
7047 int NameID = -1;
7048 NameStr = "";
7049
7050 if (Lex.getKind() == lltok::LocalVarID) {
7051 NameID = Lex.getUIntVal();
7052 Lex.Lex();
7053 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7054 return true;
7055 } else if (Lex.getKind() == lltok::LocalVar) {
7056 NameStr = Lex.getStrVal();
7057 Lex.Lex();
7058 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7059 return true;
7060 }
7061
7062 switch (parseInstruction(Inst, BB, PFS)) {
7063 default:
7064 llvm_unreachable("Unknown parseInstruction result!");
7065 case InstError: return true;
7066 case InstNormal:
7067 Inst->insertInto(BB, BB->end());
7068
7069 // With a normal result, we check to see if the instruction is followed by
7070 // a comma and metadata.
7071 if (EatIfPresent(lltok::comma))
7072 if (parseInstructionMetadata(*Inst))
7073 return true;
7074 break;
7075 case InstExtraComma:
7076 Inst->insertInto(BB, BB->end());
7077
7078 // If the instruction parser ate an extra comma at the end of it, it
7079 // *must* be followed by metadata.
7080 if (parseInstructionMetadata(*Inst))
7081 return true;
7082 break;
7083 }
7084
7085 // Set the name on the instruction.
7086 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7087 return true;
7088
7089 // Attach any preceding debug values to this instruction.
7090 for (DbgRecordPtr &DR : TrailingDbgRecord)
7091 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7092 TrailingDbgRecord.clear();
7093 } while (!Inst->isTerminator());
7094
7095 assert(TrailingDbgRecord.empty() &&
7096 "All debug values should have been attached to an instruction.");
7097
7098 return false;
7099}
7100
7101/// parseDebugRecord
7102/// ::= #dbg_label '(' MDNode ')'
7103/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7104/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7105bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7106 using RecordKind = DbgRecord::Kind;
7107 using LocType = DbgVariableRecord::LocationType;
7108 LocTy DVRLoc = Lex.getLoc();
7109 if (Lex.getKind() != lltok::DbgRecordType)
7110 return error(DVRLoc, "expected debug record type here");
7111 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7112 .Case("declare", RecordKind::ValueKind)
7113 .Case("value", RecordKind::ValueKind)
7114 .Case("assign", RecordKind::ValueKind)
7115 .Case("label", RecordKind::LabelKind);
7116
7117 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7118 // full DbgVariableRecord processing stage.
7119 if (RecordType == RecordKind::LabelKind) {
7120 Lex.Lex();
7121 if (parseToken(lltok::lparen, "Expected '(' here"))
7122 return true;
7123 MDNode *Label;
7124 if (parseMDNode(Label))
7125 return true;
7126 if (parseToken(lltok::comma, "Expected ',' here"))
7127 return true;
7128 MDNode *DbgLoc;
7129 if (parseMDNode(DbgLoc))
7130 return true;
7131 if (parseToken(lltok::rparen, "Expected ')' here"))
7132 return true;
7134 return false;
7135 }
7136
7137 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7138 .Case("declare", LocType::Declare)
7139 .Case("value", LocType::Value)
7140 .Case("assign", LocType::Assign);
7141
7142 Lex.Lex();
7143 if (parseToken(lltok::lparen, "Expected '(' here"))
7144 return true;
7145
7146 // Parse Value field.
7147 Metadata *ValLocMD;
7148 if (parseMetadata(ValLocMD, &PFS))
7149 return true;
7150 if (parseToken(lltok::comma, "Expected ',' here"))
7151 return true;
7152
7153 // Parse Variable field.
7154 MDNode *Variable;
7155 if (parseMDNode(Variable))
7156 return true;
7157 if (parseToken(lltok::comma, "Expected ',' here"))
7158 return true;
7159
7160 // Parse Expression field.
7161 MDNode *Expression;
7162 if (parseMDNode(Expression))
7163 return true;
7164 if (parseToken(lltok::comma, "Expected ',' here"))
7165 return true;
7166
7167 // Parse additional fields for #dbg_assign.
7168 MDNode *AssignID = nullptr;
7169 Metadata *AddressLocation = nullptr;
7170 MDNode *AddressExpression = nullptr;
7171 if (ValueType == LocType::Assign) {
7172 // Parse DIAssignID.
7173 if (parseMDNode(AssignID))
7174 return true;
7175 if (parseToken(lltok::comma, "Expected ',' here"))
7176 return true;
7177
7178 // Parse address ValueAsMetadata.
7179 if (parseMetadata(AddressLocation, &PFS))
7180 return true;
7181 if (parseToken(lltok::comma, "Expected ',' here"))
7182 return true;
7183
7184 // Parse address DIExpression.
7185 if (parseMDNode(AddressExpression))
7186 return true;
7187 if (parseToken(lltok::comma, "Expected ',' here"))
7188 return true;
7189 }
7190
7191 /// Parse DILocation.
7192 MDNode *DebugLoc;
7193 if (parseMDNode(DebugLoc))
7194 return true;
7195
7196 if (parseToken(lltok::rparen, "Expected ')' here"))
7197 return true;
7199 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7200 AddressExpression, DebugLoc);
7201 return false;
7202}
7203//===----------------------------------------------------------------------===//
7204// Instruction Parsing.
7205//===----------------------------------------------------------------------===//
7206
7207/// parseInstruction - parse one of the many different instructions.
7208///
7209int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7210 PerFunctionState &PFS) {
7211 lltok::Kind Token = Lex.getKind();
7212 if (Token == lltok::Eof)
7213 return tokError("found end of file when expecting more instructions");
7214 LocTy Loc = Lex.getLoc();
7215 unsigned KeywordVal = Lex.getUIntVal();
7216 Lex.Lex(); // Eat the keyword.
7217
7218 switch (Token) {
7219 default:
7220 return error(Loc, "expected instruction opcode");
7221 // Terminator Instructions.
7222 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7223 case lltok::kw_ret:
7224 return parseRet(Inst, BB, PFS);
7225 case lltok::kw_br:
7226 return parseBr(Inst, PFS);
7227 case lltok::kw_switch:
7228 return parseSwitch(Inst, PFS);
7230 return parseIndirectBr(Inst, PFS);
7231 case lltok::kw_invoke:
7232 return parseInvoke(Inst, PFS);
7233 case lltok::kw_resume:
7234 return parseResume(Inst, PFS);
7236 return parseCleanupRet(Inst, PFS);
7237 case lltok::kw_catchret:
7238 return parseCatchRet(Inst, PFS);
7240 return parseCatchSwitch(Inst, PFS);
7241 case lltok::kw_catchpad:
7242 return parseCatchPad(Inst, PFS);
7244 return parseCleanupPad(Inst, PFS);
7245 case lltok::kw_callbr:
7246 return parseCallBr(Inst, PFS);
7247 // Unary Operators.
7248 case lltok::kw_fneg: {
7249 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7250 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7251 if (Res != 0)
7252 return Res;
7253 if (FMF.any())
7254 Inst->setFastMathFlags(FMF);
7255 return false;
7256 }
7257 // Binary Operators.
7258 case lltok::kw_add:
7259 case lltok::kw_sub:
7260 case lltok::kw_mul:
7261 case lltok::kw_shl: {
7262 bool NUW = EatIfPresent(lltok::kw_nuw);
7263 bool NSW = EatIfPresent(lltok::kw_nsw);
7264 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7265
7266 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7267 return true;
7268
7269 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7270 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7271 return false;
7272 }
7273 case lltok::kw_fadd:
7274 case lltok::kw_fsub:
7275 case lltok::kw_fmul:
7276 case lltok::kw_fdiv:
7277 case lltok::kw_frem: {
7278 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7279 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7280 if (Res != 0)
7281 return Res;
7282 if (FMF.any())
7283 Inst->setFastMathFlags(FMF);
7284 return 0;
7285 }
7286
7287 case lltok::kw_sdiv:
7288 case lltok::kw_udiv:
7289 case lltok::kw_lshr:
7290 case lltok::kw_ashr: {
7291 bool Exact = EatIfPresent(lltok::kw_exact);
7292
7293 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7294 return true;
7295 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7296 return false;
7297 }
7298
7299 case lltok::kw_urem:
7300 case lltok::kw_srem:
7301 return parseArithmetic(Inst, PFS, KeywordVal,
7302 /*IsFP*/ false);
7303 case lltok::kw_or: {
7304 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7305 if (parseLogical(Inst, PFS, KeywordVal))
7306 return true;
7307 if (Disjoint)
7308 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7309 return false;
7310 }
7311 case lltok::kw_and:
7312 case lltok::kw_xor:
7313 return parseLogical(Inst, PFS, KeywordVal);
7314 case lltok::kw_icmp: {
7315 bool SameSign = EatIfPresent(lltok::kw_samesign);
7316 if (parseCompare(Inst, PFS, KeywordVal))
7317 return true;
7318 if (SameSign)
7319 cast<ICmpInst>(Inst)->setSameSign();
7320 return false;
7321 }
7322 case lltok::kw_fcmp: {
7323 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7324 int Res = parseCompare(Inst, PFS, KeywordVal);
7325 if (Res != 0)
7326 return Res;
7327 if (FMF.any())
7328 Inst->setFastMathFlags(FMF);
7329 return 0;
7330 }
7331
7332 // Casts.
7333 case lltok::kw_uitofp:
7334 case lltok::kw_zext: {
7335 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7336 bool Res = parseCast(Inst, PFS, KeywordVal);
7337 if (Res != 0)
7338 return Res;
7339 if (NonNeg)
7340 Inst->setNonNeg();
7341 return 0;
7342 }
7343 case lltok::kw_trunc: {
7344 bool NUW = EatIfPresent(lltok::kw_nuw);
7345 bool NSW = EatIfPresent(lltok::kw_nsw);
7346 if (!NUW)
7347 NUW = EatIfPresent(lltok::kw_nuw);
7348 if (parseCast(Inst, PFS, KeywordVal))
7349 return true;
7350 if (NUW)
7351 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7352 if (NSW)
7353 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7354 return false;
7355 }
7356 case lltok::kw_sext:
7357 case lltok::kw_bitcast:
7359 case lltok::kw_sitofp:
7360 case lltok::kw_fptoui:
7361 case lltok::kw_fptosi:
7362 case lltok::kw_inttoptr:
7364 case lltok::kw_ptrtoint:
7365 return parseCast(Inst, PFS, KeywordVal);
7366 case lltok::kw_fptrunc:
7367 case lltok::kw_fpext: {
7368 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7369 if (parseCast(Inst, PFS, KeywordVal))
7370 return true;
7371 if (FMF.any())
7372 Inst->setFastMathFlags(FMF);
7373 return false;
7374 }
7375
7376 // Other.
7377 case lltok::kw_select: {
7378 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7379 int Res = parseSelect(Inst, PFS);
7380 if (Res != 0)
7381 return Res;
7382 if (FMF.any()) {
7383 if (!isa<FPMathOperator>(Inst))
7384 return error(Loc, "fast-math-flags specified for select without "
7385 "floating-point scalar or vector return type");
7386 Inst->setFastMathFlags(FMF);
7387 }
7388 return 0;
7389 }
7390 case lltok::kw_va_arg:
7391 return parseVAArg(Inst, PFS);
7393 return parseExtractElement(Inst, PFS);
7395 return parseInsertElement(Inst, PFS);
7397 return parseShuffleVector(Inst, PFS);
7398 case lltok::kw_phi: {
7399 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7400 int Res = parsePHI(Inst, PFS);
7401 if (Res != 0)
7402 return Res;
7403 if (FMF.any()) {
7404 if (!isa<FPMathOperator>(Inst))
7405 return error(Loc, "fast-math-flags specified for phi without "
7406 "floating-point scalar or vector return type");
7407 Inst->setFastMathFlags(FMF);
7408 }
7409 return 0;
7410 }
7412 return parseLandingPad(Inst, PFS);
7413 case lltok::kw_freeze:
7414 return parseFreeze(Inst, PFS);
7415 // Call.
7416 case lltok::kw_call:
7417 return parseCall(Inst, PFS, CallInst::TCK_None);
7418 case lltok::kw_tail:
7419 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7420 case lltok::kw_musttail:
7421 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7422 case lltok::kw_notail:
7423 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7424 // Memory.
7425 case lltok::kw_alloca:
7426 return parseAlloc(Inst, PFS);
7427 case lltok::kw_load:
7428 return parseLoad(Inst, PFS);
7429 case lltok::kw_store:
7430 return parseStore(Inst, PFS);
7431 case lltok::kw_cmpxchg:
7432 return parseCmpXchg(Inst, PFS);
7434 return parseAtomicRMW(Inst, PFS);
7435 case lltok::kw_fence:
7436 return parseFence(Inst, PFS);
7438 return parseGetElementPtr(Inst, PFS);
7440 return parseExtractValue(Inst, PFS);
7442 return parseInsertValue(Inst, PFS);
7443 }
7444}
7445
7446/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7447bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7448 if (Opc == Instruction::FCmp) {
7449 switch (Lex.getKind()) {
7450 default:
7451 return tokError("expected fcmp predicate (e.g. 'oeq')");
7452 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7453 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7454 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7455 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7456 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7457 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7458 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7459 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7460 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7461 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7462 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7463 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7464 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7465 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7466 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7467 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7468 }
7469 } else {
7470 switch (Lex.getKind()) {
7471 default:
7472 return tokError("expected icmp predicate (e.g. 'eq')");
7473 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7474 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7475 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7476 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7477 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7478 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7479 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7480 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7481 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7482 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7483 }
7484 }
7485 Lex.Lex();
7486 return false;
7487}
7488
7489//===----------------------------------------------------------------------===//
7490// Terminator Instructions.
7491//===----------------------------------------------------------------------===//
7492
7493/// parseRet - parse a return instruction.
7494/// ::= 'ret' void (',' !dbg, !1)*
7495/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7496bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7497 PerFunctionState &PFS) {
7498 SMLoc TypeLoc = Lex.getLoc();
7499 Type *Ty = nullptr;
7500 if (parseType(Ty, true /*void allowed*/))
7501 return true;
7502
7503 Type *ResType = PFS.getFunction().getReturnType();
7504
7505 if (Ty->isVoidTy()) {
7506 if (!ResType->isVoidTy())
7507 return error(TypeLoc, "value doesn't match function result type '" +
7508 getTypeString(ResType) + "'");
7509
7510 Inst = ReturnInst::Create(Context);
7511 return false;
7512 }
7513
7514 Value *RV;
7515 if (parseValue(Ty, RV, PFS))
7516 return true;
7517
7518 if (ResType != RV->getType())
7519 return error(TypeLoc, "value doesn't match function result type '" +
7520 getTypeString(ResType) + "'");
7521
7522 Inst = ReturnInst::Create(Context, RV);
7523 return false;
7524}
7525
7526/// parseBr
7527/// ::= 'br' TypeAndValue
7528/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7529bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7530 LocTy Loc, Loc2;
7531 Value *Op0;
7532 BasicBlock *Op1, *Op2;
7533 if (parseTypeAndValue(Op0, Loc, PFS))
7534 return true;
7535
7536 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7537 Inst = BranchInst::Create(BB);
7538 return false;
7539 }
7540
7541 if (Op0->getType() != Type::getInt1Ty(Context))
7542 return error(Loc, "branch condition must have 'i1' type");
7543
7544 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7545 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7546 parseToken(lltok::comma, "expected ',' after true destination") ||
7547 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7548 return true;
7549
7550 Inst = BranchInst::Create(Op1, Op2, Op0);
7551 return false;
7552}
7553
7554/// parseSwitch
7555/// Instruction
7556/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7557/// JumpTable
7558/// ::= (TypeAndValue ',' TypeAndValue)*
7559bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7560 LocTy CondLoc, BBLoc;
7561 Value *Cond;
7562 BasicBlock *DefaultBB;
7563 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7564 parseToken(lltok::comma, "expected ',' after switch condition") ||
7565 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7566 parseToken(lltok::lsquare, "expected '[' with switch table"))
7567 return true;
7568
7569 if (!Cond->getType()->isIntegerTy())
7570 return error(CondLoc, "switch condition must have integer type");
7571
7572 // parse the jump table pairs.
7573 SmallPtrSet<Value*, 32> SeenCases;
7575 while (Lex.getKind() != lltok::rsquare) {
7576 Value *Constant;
7577 BasicBlock *DestBB;
7578
7579 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7580 parseToken(lltok::comma, "expected ',' after case value") ||
7581 parseTypeAndBasicBlock(DestBB, PFS))
7582 return true;
7583
7584 if (!SeenCases.insert(Constant).second)
7585 return error(CondLoc, "duplicate case value in switch");
7586 if (!isa<ConstantInt>(Constant))
7587 return error(CondLoc, "case value is not a constant integer");
7588
7589 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7590 }
7591
7592 Lex.Lex(); // Eat the ']'.
7593
7594 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7595 for (const auto &[OnVal, Dest] : Table)
7596 SI->addCase(OnVal, Dest);
7597 Inst = SI;
7598 return false;
7599}
7600
7601/// parseIndirectBr
7602/// Instruction
7603/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7604bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7605 LocTy AddrLoc;
7606 Value *Address;
7607 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7608 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7609 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7610 return true;
7611
7612 if (!Address->getType()->isPointerTy())
7613 return error(AddrLoc, "indirectbr address must have pointer type");
7614
7615 // parse the destination list.
7616 SmallVector<BasicBlock*, 16> DestList;
7617
7618 if (Lex.getKind() != lltok::rsquare) {
7619 BasicBlock *DestBB;
7620 if (parseTypeAndBasicBlock(DestBB, PFS))
7621 return true;
7622 DestList.push_back(DestBB);
7623
7624 while (EatIfPresent(lltok::comma)) {
7625 if (parseTypeAndBasicBlock(DestBB, PFS))
7626 return true;
7627 DestList.push_back(DestBB);
7628 }
7629 }
7630
7631 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7632 return true;
7633
7634 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7635 for (BasicBlock *Dest : DestList)
7636 IBI->addDestination(Dest);
7637 Inst = IBI;
7638 return false;
7639}
7640
7641// If RetType is a non-function pointer type, then this is the short syntax
7642// for the call, which means that RetType is just the return type. Infer the
7643// rest of the function argument types from the arguments that are present.
7644bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7645 FunctionType *&FuncTy) {
7646 FuncTy = dyn_cast<FunctionType>(RetType);
7647 if (!FuncTy) {
7648 // Pull out the types of all of the arguments...
7649 SmallVector<Type *, 8> ParamTypes;
7650 ParamTypes.reserve(ArgList.size());
7651 for (const ParamInfo &Arg : ArgList)
7652 ParamTypes.push_back(Arg.V->getType());
7653
7654 if (!FunctionType::isValidReturnType(RetType))
7655 return true;
7656
7657 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7658 }
7659 return false;
7660}
7661
7662/// parseInvoke
7663/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7664/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7665bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7666 LocTy CallLoc = Lex.getLoc();
7667 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7668 std::vector<unsigned> FwdRefAttrGrps;
7669 LocTy NoBuiltinLoc;
7670 unsigned CC;
7671 unsigned InvokeAddrSpace;
7672 Type *RetType = nullptr;
7673 LocTy RetTypeLoc;
7674 ValID CalleeID;
7677
7678 BasicBlock *NormalBB, *UnwindBB;
7679 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7680 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7681 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7682 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7683 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7684 NoBuiltinLoc) ||
7685 parseOptionalOperandBundles(BundleList, PFS) ||
7686 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7687 parseTypeAndBasicBlock(NormalBB, PFS) ||
7688 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7689 parseTypeAndBasicBlock(UnwindBB, PFS))
7690 return true;
7691
7692 // If RetType is a non-function pointer type, then this is the short syntax
7693 // for the call, which means that RetType is just the return type. Infer the
7694 // rest of the function argument types from the arguments that are present.
7695 FunctionType *Ty;
7696 if (resolveFunctionType(RetType, ArgList, Ty))
7697 return error(RetTypeLoc, "Invalid result type for LLVM function");
7698
7699 CalleeID.FTy = Ty;
7700
7701 // Look up the callee.
7702 Value *Callee;
7703 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
7704 Callee, &PFS))
7705 return true;
7706
7707 // Set up the Attribute for the function.
7708 SmallVector<Value *, 8> Args;
7710
7711 // Loop through FunctionType's arguments and ensure they are specified
7712 // correctly. Also, gather any parameter attributes.
7713 FunctionType::param_iterator I = Ty->param_begin();
7714 FunctionType::param_iterator E = Ty->param_end();
7715 for (const ParamInfo &Arg : ArgList) {
7716 Type *ExpectedTy = nullptr;
7717 if (I != E) {
7718 ExpectedTy = *I++;
7719 } else if (!Ty->isVarArg()) {
7720 return error(Arg.Loc, "too many arguments specified");
7721 }
7722
7723 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7724 return error(Arg.Loc, "argument is not of expected type '" +
7725 getTypeString(ExpectedTy) + "'");
7726 Args.push_back(Arg.V);
7727 ArgAttrs.push_back(Arg.Attrs);
7728 }
7729
7730 if (I != E)
7731 return error(CallLoc, "not enough parameters specified for call");
7732
7733 // Finish off the Attribute and check them
7734 AttributeList PAL =
7735 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7736 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7737
7738 InvokeInst *II =
7739 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7740 II->setCallingConv(CC);
7741 II->setAttributes(PAL);
7742 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7743 Inst = II;
7744 return false;
7745}
7746
7747/// parseResume
7748/// ::= 'resume' TypeAndValue
7749bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7750 Value *Exn; LocTy ExnLoc;
7751 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7752 return true;
7753
7754 ResumeInst *RI = ResumeInst::Create(Exn);
7755 Inst = RI;
7756 return false;
7757}
7758
7759bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7760 PerFunctionState &PFS) {
7761 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7762 return true;
7763
7764 while (Lex.getKind() != lltok::rsquare) {
7765 // If this isn't the first argument, we need a comma.
7766 if (!Args.empty() &&
7767 parseToken(lltok::comma, "expected ',' in argument list"))
7768 return true;
7769
7770 // parse the argument.
7771 LocTy ArgLoc;
7772 Type *ArgTy = nullptr;
7773 if (parseType(ArgTy, ArgLoc))
7774 return true;
7775
7776 Value *V;
7777 if (ArgTy->isMetadataTy()) {
7778 if (parseMetadataAsValue(V, PFS))
7779 return true;
7780 } else {
7781 if (parseValue(ArgTy, V, PFS))
7782 return true;
7783 }
7784 Args.push_back(V);
7785 }
7786
7787 Lex.Lex(); // Lex the ']'.
7788 return false;
7789}
7790
7791/// parseCleanupRet
7792/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7793bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7794 Value *CleanupPad = nullptr;
7795
7796 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7797 return true;
7798
7799 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7800 return true;
7801
7802 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7803 return true;
7804
7805 BasicBlock *UnwindBB = nullptr;
7806 if (Lex.getKind() == lltok::kw_to) {
7807 Lex.Lex();
7808 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7809 return true;
7810 } else {
7811 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7812 return true;
7813 }
7814 }
7815
7816 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7817 return false;
7818}
7819
7820/// parseCatchRet
7821/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7822bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7823 Value *CatchPad = nullptr;
7824
7825 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7826 return true;
7827
7828 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7829 return true;
7830
7831 BasicBlock *BB;
7832 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7833 parseTypeAndBasicBlock(BB, PFS))
7834 return true;
7835
7836 Inst = CatchReturnInst::Create(CatchPad, BB);
7837 return false;
7838}
7839
7840/// parseCatchSwitch
7841/// ::= 'catchswitch' within Parent
7842bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7843 Value *ParentPad;
7844
7845 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7846 return true;
7847
7848 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7849 Lex.getKind() != lltok::LocalVarID)
7850 return tokError("expected scope value for catchswitch");
7851
7852 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7853 return true;
7854
7855 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7856 return true;
7857
7859 do {
7860 BasicBlock *DestBB;
7861 if (parseTypeAndBasicBlock(DestBB, PFS))
7862 return true;
7863 Table.push_back(DestBB);
7864 } while (EatIfPresent(lltok::comma));
7865
7866 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7867 return true;
7868
7869 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7870 return true;
7871
7872 BasicBlock *UnwindBB = nullptr;
7873 if (EatIfPresent(lltok::kw_to)) {
7874 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7875 return true;
7876 } else {
7877 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7878 return true;
7879 }
7880
7881 auto *CatchSwitch =
7882 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7883 for (BasicBlock *DestBB : Table)
7884 CatchSwitch->addHandler(DestBB);
7885 Inst = CatchSwitch;
7886 return false;
7887}
7888
7889/// parseCatchPad
7890/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7891bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7892 Value *CatchSwitch = nullptr;
7893
7894 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7895 return true;
7896
7897 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7898 return tokError("expected scope value for catchpad");
7899
7900 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7901 return true;
7902
7903 SmallVector<Value *, 8> Args;
7904 if (parseExceptionArgs(Args, PFS))
7905 return true;
7906
7907 Inst = CatchPadInst::Create(CatchSwitch, Args);
7908 return false;
7909}
7910
7911/// parseCleanupPad
7912/// ::= 'cleanuppad' within Parent ParamList
7913bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7914 Value *ParentPad = nullptr;
7915
7916 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7917 return true;
7918
7919 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7920 Lex.getKind() != lltok::LocalVarID)
7921 return tokError("expected scope value for cleanuppad");
7922
7923 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7924 return true;
7925
7926 SmallVector<Value *, 8> Args;
7927 if (parseExceptionArgs(Args, PFS))
7928 return true;
7929
7930 Inst = CleanupPadInst::Create(ParentPad, Args);
7931 return false;
7932}
7933
7934//===----------------------------------------------------------------------===//
7935// Unary Operators.
7936//===----------------------------------------------------------------------===//
7937
7938/// parseUnaryOp
7939/// ::= UnaryOp TypeAndValue ',' Value
7940///
7941/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7942/// operand is allowed.
7943bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7944 unsigned Opc, bool IsFP) {
7945 LocTy Loc; Value *LHS;
7946 if (parseTypeAndValue(LHS, Loc, PFS))
7947 return true;
7948
7949 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7951
7952 if (!Valid)
7953 return error(Loc, "invalid operand type for instruction");
7954
7956 return false;
7957}
7958
7959/// parseCallBr
7960/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7961/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7962/// '[' LabelList ']'
7963bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7964 LocTy CallLoc = Lex.getLoc();
7965 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7966 std::vector<unsigned> FwdRefAttrGrps;
7967 LocTy NoBuiltinLoc;
7968 unsigned CC;
7969 Type *RetType = nullptr;
7970 LocTy RetTypeLoc;
7971 ValID CalleeID;
7974
7975 BasicBlock *DefaultDest;
7976 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7977 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7978 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7979 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7980 NoBuiltinLoc) ||
7981 parseOptionalOperandBundles(BundleList, PFS) ||
7982 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7983 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7984 parseToken(lltok::lsquare, "expected '[' in callbr"))
7985 return true;
7986
7987 // parse the destination list.
7988 SmallVector<BasicBlock *, 16> IndirectDests;
7989
7990 if (Lex.getKind() != lltok::rsquare) {
7991 BasicBlock *DestBB;
7992 if (parseTypeAndBasicBlock(DestBB, PFS))
7993 return true;
7994 IndirectDests.push_back(DestBB);
7995
7996 while (EatIfPresent(lltok::comma)) {
7997 if (parseTypeAndBasicBlock(DestBB, PFS))
7998 return true;
7999 IndirectDests.push_back(DestBB);
8000 }
8001 }
8002
8003 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8004 return true;
8005
8006 // If RetType is a non-function pointer type, then this is the short syntax
8007 // for the call, which means that RetType is just the return type. Infer the
8008 // rest of the function argument types from the arguments that are present.
8009 FunctionType *Ty;
8010 if (resolveFunctionType(RetType, ArgList, Ty))
8011 return error(RetTypeLoc, "Invalid result type for LLVM function");
8012
8013 CalleeID.FTy = Ty;
8014
8015 // Look up the callee.
8016 Value *Callee;
8017 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8018 &PFS))
8019 return true;
8020
8021 // Set up the Attribute for the function.
8022 SmallVector<Value *, 8> Args;
8024
8025 // Loop through FunctionType's arguments and ensure they are specified
8026 // correctly. Also, gather any parameter attributes.
8027 FunctionType::param_iterator I = Ty->param_begin();
8028 FunctionType::param_iterator E = Ty->param_end();
8029 for (const ParamInfo &Arg : ArgList) {
8030 Type *ExpectedTy = nullptr;
8031 if (I != E) {
8032 ExpectedTy = *I++;
8033 } else if (!Ty->isVarArg()) {
8034 return error(Arg.Loc, "too many arguments specified");
8035 }
8036
8037 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8038 return error(Arg.Loc, "argument is not of expected type '" +
8039 getTypeString(ExpectedTy) + "'");
8040 Args.push_back(Arg.V);
8041 ArgAttrs.push_back(Arg.Attrs);
8042 }
8043
8044 if (I != E)
8045 return error(CallLoc, "not enough parameters specified for call");
8046
8047 // Finish off the Attribute and check them
8048 AttributeList PAL =
8049 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8050 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8051
8052 CallBrInst *CBI =
8053 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8054 BundleList);
8055 CBI->setCallingConv(CC);
8056 CBI->setAttributes(PAL);
8057 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8058 Inst = CBI;
8059 return false;
8060}
8061
8062//===----------------------------------------------------------------------===//
8063// Binary Operators.
8064//===----------------------------------------------------------------------===//
8065
8066/// parseArithmetic
8067/// ::= ArithmeticOps TypeAndValue ',' Value
8068///
8069/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8070/// operand is allowed.
8071bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8072 unsigned Opc, bool IsFP) {
8073 LocTy Loc; Value *LHS, *RHS;
8074 if (parseTypeAndValue(LHS, Loc, PFS) ||
8075 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8076 parseValue(LHS->getType(), RHS, PFS))
8077 return true;
8078
8079 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8081
8082 if (!Valid)
8083 return error(Loc, "invalid operand type for instruction");
8084
8086 return false;
8087}
8088
8089/// parseLogical
8090/// ::= ArithmeticOps TypeAndValue ',' Value {
8091bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8092 unsigned Opc) {
8093 LocTy Loc; Value *LHS, *RHS;
8094 if (parseTypeAndValue(LHS, Loc, PFS) ||
8095 parseToken(lltok::comma, "expected ',' in logical operation") ||
8096 parseValue(LHS->getType(), RHS, PFS))
8097 return true;
8098
8099 if (!LHS->getType()->isIntOrIntVectorTy())
8100 return error(Loc,
8101 "instruction requires integer or integer vector operands");
8102
8104 return false;
8105}
8106
8107/// parseCompare
8108/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8109/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8110bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8111 unsigned Opc) {
8112 // parse the integer/fp comparison predicate.
8113 LocTy Loc;
8114 unsigned Pred;
8115 Value *LHS, *RHS;
8116 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8117 parseToken(lltok::comma, "expected ',' after compare value") ||
8118 parseValue(LHS->getType(), RHS, PFS))
8119 return true;
8120
8121 if (Opc == Instruction::FCmp) {
8122 if (!LHS->getType()->isFPOrFPVectorTy())
8123 return error(Loc, "fcmp requires floating point operands");
8124 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8125 } else {
8126 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8127 if (!LHS->getType()->isIntOrIntVectorTy() &&
8129 return error(Loc, "icmp requires integer operands");
8130 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8131 }
8132 return false;
8133}
8134
8135//===----------------------------------------------------------------------===//
8136// Other Instructions.
8137//===----------------------------------------------------------------------===//
8138
8139/// parseCast
8140/// ::= CastOpc TypeAndValue 'to' Type
8141bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8142 unsigned Opc) {
8143 LocTy Loc;
8144 Value *Op;
8145 Type *DestTy = nullptr;
8146 if (parseTypeAndValue(Op, Loc, PFS) ||
8147 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8148 parseType(DestTy))
8149 return true;
8150
8152 return error(Loc, "invalid cast opcode for cast from '" +
8153 getTypeString(Op->getType()) + "' to '" +
8154 getTypeString(DestTy) + "'");
8155 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8156 return false;
8157}
8158
8159/// parseSelect
8160/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8161bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8162 LocTy Loc;
8163 Value *Op0, *Op1, *Op2;
8164 if (parseTypeAndValue(Op0, Loc, PFS) ||
8165 parseToken(lltok::comma, "expected ',' after select condition") ||
8166 parseTypeAndValue(Op1, PFS) ||
8167 parseToken(lltok::comma, "expected ',' after select value") ||
8168 parseTypeAndValue(Op2, PFS))
8169 return true;
8170
8171 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8172 return error(Loc, Reason);
8173
8174 Inst = SelectInst::Create(Op0, Op1, Op2);
8175 return false;
8176}
8177
8178/// parseVAArg
8179/// ::= 'va_arg' TypeAndValue ',' Type
8180bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8181 Value *Op;
8182 Type *EltTy = nullptr;
8183 LocTy TypeLoc;
8184 if (parseTypeAndValue(Op, PFS) ||
8185 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8186 parseType(EltTy, TypeLoc))
8187 return true;
8188
8189 if (!EltTy->isFirstClassType())
8190 return error(TypeLoc, "va_arg requires operand with first class type");
8191
8192 Inst = new VAArgInst(Op, EltTy);
8193 return false;
8194}
8195
8196/// parseExtractElement
8197/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8198bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8199 LocTy Loc;
8200 Value *Op0, *Op1;
8201 if (parseTypeAndValue(Op0, Loc, PFS) ||
8202 parseToken(lltok::comma, "expected ',' after extract value") ||
8203 parseTypeAndValue(Op1, PFS))
8204 return true;
8205
8207 return error(Loc, "invalid extractelement operands");
8208
8209 Inst = ExtractElementInst::Create(Op0, Op1);
8210 return false;
8211}
8212
8213/// parseInsertElement
8214/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8215bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8216 LocTy Loc;
8217 Value *Op0, *Op1, *Op2;
8218 if (parseTypeAndValue(Op0, Loc, PFS) ||
8219 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8220 parseTypeAndValue(Op1, PFS) ||
8221 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8222 parseTypeAndValue(Op2, PFS))
8223 return true;
8224
8225 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8226 return error(Loc, "invalid insertelement operands");
8227
8228 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8229 return false;
8230}
8231
8232/// parseShuffleVector
8233/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8234bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8235 LocTy Loc;
8236 Value *Op0, *Op1, *Op2;
8237 if (parseTypeAndValue(Op0, Loc, PFS) ||
8238 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8239 parseTypeAndValue(Op1, PFS) ||
8240 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8241 parseTypeAndValue(Op2, PFS))
8242 return true;
8243
8244 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8245 return error(Loc, "invalid shufflevector operands");
8246
8247 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8248 return false;
8249}
8250
8251/// parsePHI
8252/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8253int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8254 Type *Ty = nullptr; LocTy TypeLoc;
8255 Value *Op0, *Op1;
8256
8257 if (parseType(Ty, TypeLoc))
8258 return true;
8259
8260 if (!Ty->isFirstClassType())
8261 return error(TypeLoc, "phi node must have first class type");
8262
8263 bool First = true;
8264 bool AteExtraComma = false;
8266
8267 while (true) {
8268 if (First) {
8269 if (Lex.getKind() != lltok::lsquare)
8270 break;
8271 First = false;
8272 } else if (!EatIfPresent(lltok::comma))
8273 break;
8274
8275 if (Lex.getKind() == lltok::MetadataVar) {
8276 AteExtraComma = true;
8277 break;
8278 }
8279
8280 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8281 parseValue(Ty, Op0, PFS) ||
8282 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8283 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8284 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8285 return true;
8286
8287 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8288 }
8289
8290 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8291 for (const auto &[Val, BB] : PHIVals)
8292 PN->addIncoming(Val, BB);
8293 Inst = PN;
8294 return AteExtraComma ? InstExtraComma : InstNormal;
8295}
8296
8297/// parseLandingPad
8298/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8299/// Clause
8300/// ::= 'catch' TypeAndValue
8301/// ::= 'filter'
8302/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8303bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8304 Type *Ty = nullptr; LocTy TyLoc;
8305
8306 if (parseType(Ty, TyLoc))
8307 return true;
8308
8309 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8310 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8311
8312 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8314 if (EatIfPresent(lltok::kw_catch))
8316 else if (EatIfPresent(lltok::kw_filter))
8318 else
8319 return tokError("expected 'catch' or 'filter' clause type");
8320
8321 Value *V;
8322 LocTy VLoc;
8323 if (parseTypeAndValue(V, VLoc, PFS))
8324 return true;
8325
8326 // A 'catch' type expects a non-array constant. A filter clause expects an
8327 // array constant.
8328 if (CT == LandingPadInst::Catch) {
8329 if (isa<ArrayType>(V->getType()))
8330 return error(VLoc, "'catch' clause has an invalid type");
8331 } else {
8332 if (!isa<ArrayType>(V->getType()))
8333 return error(VLoc, "'filter' clause has an invalid type");
8334 }
8335
8337 if (!CV)
8338 return error(VLoc, "clause argument must be a constant");
8339 LP->addClause(CV);
8340 }
8341
8342 Inst = LP.release();
8343 return false;
8344}
8345
8346/// parseFreeze
8347/// ::= 'freeze' Type Value
8348bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8349 LocTy Loc;
8350 Value *Op;
8351 if (parseTypeAndValue(Op, Loc, PFS))
8352 return true;
8353
8354 Inst = new FreezeInst(Op);
8355 return false;
8356}
8357
8358/// parseCall
8359/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8360/// OptionalAttrs Type Value ParameterList OptionalAttrs
8361/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8362/// OptionalAttrs Type Value ParameterList OptionalAttrs
8363/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8364/// OptionalAttrs Type Value ParameterList OptionalAttrs
8365/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8366/// OptionalAttrs Type Value ParameterList OptionalAttrs
8367bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8369 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8370 std::vector<unsigned> FwdRefAttrGrps;
8371 LocTy BuiltinLoc;
8372 unsigned CallAddrSpace;
8373 unsigned CC;
8374 Type *RetType = nullptr;
8375 LocTy RetTypeLoc;
8376 ValID CalleeID;
8379 LocTy CallLoc = Lex.getLoc();
8380
8381 if (TCK != CallInst::TCK_None &&
8382 parseToken(lltok::kw_call,
8383 "expected 'tail call', 'musttail call', or 'notail call'"))
8384 return true;
8385
8386 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8387
8388 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8389 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8390 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8391 parseValID(CalleeID, &PFS) ||
8392 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8393 PFS.getFunction().isVarArg()) ||
8394 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8395 parseOptionalOperandBundles(BundleList, PFS))
8396 return true;
8397
8398 // If RetType is a non-function pointer type, then this is the short syntax
8399 // for the call, which means that RetType is just the return type. Infer the
8400 // rest of the function argument types from the arguments that are present.
8401 FunctionType *Ty;
8402 if (resolveFunctionType(RetType, ArgList, Ty))
8403 return error(RetTypeLoc, "Invalid result type for LLVM function");
8404
8405 CalleeID.FTy = Ty;
8406
8407 // Look up the callee.
8408 Value *Callee;
8409 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8410 Callee, &PFS))
8411 return true;
8412
8413 // Set up the Attribute for the function.
8415
8416 SmallVector<Value*, 8> Args;
8417
8418 // Loop through FunctionType's arguments and ensure they are specified
8419 // correctly. Also, gather any parameter attributes.
8420 FunctionType::param_iterator I = Ty->param_begin();
8421 FunctionType::param_iterator E = Ty->param_end();
8422 for (const ParamInfo &Arg : ArgList) {
8423 Type *ExpectedTy = nullptr;
8424 if (I != E) {
8425 ExpectedTy = *I++;
8426 } else if (!Ty->isVarArg()) {
8427 return error(Arg.Loc, "too many arguments specified");
8428 }
8429
8430 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8431 return error(Arg.Loc, "argument is not of expected type '" +
8432 getTypeString(ExpectedTy) + "'");
8433 Args.push_back(Arg.V);
8434 Attrs.push_back(Arg.Attrs);
8435 }
8436
8437 if (I != E)
8438 return error(CallLoc, "not enough parameters specified for call");
8439
8440 // Finish off the Attribute and check them
8441 AttributeList PAL =
8442 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8443 AttributeSet::get(Context, RetAttrs), Attrs);
8444
8445 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8446 CI->setTailCallKind(TCK);
8447 CI->setCallingConv(CC);
8448 if (FMF.any()) {
8449 if (!isa<FPMathOperator>(CI)) {
8450 CI->deleteValue();
8451 return error(CallLoc, "fast-math-flags specified for call without "
8452 "floating-point scalar or vector return type");
8453 }
8454 CI->setFastMathFlags(FMF);
8455 }
8456
8457 if (CalleeID.Kind == ValID::t_GlobalName &&
8458 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8459 if (SeenNewDbgInfoFormat) {
8460 CI->deleteValue();
8461 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8462 "using non-intrinsic debug info");
8463 }
8464 SeenOldDbgInfoFormat = true;
8465 }
8466 CI->setAttributes(PAL);
8467 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8468 Inst = CI;
8469 return false;
8470}
8471
8472//===----------------------------------------------------------------------===//
8473// Memory Instructions.
8474//===----------------------------------------------------------------------===//
8475
8476/// parseAlloc
8477/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8478/// (',' 'align' i32)? (',', 'addrspace(n))?
8479int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8480 Value *Size = nullptr;
8481 LocTy SizeLoc, TyLoc, ASLoc;
8482 MaybeAlign Alignment;
8483 unsigned AddrSpace = 0;
8484 Type *Ty = nullptr;
8485
8486 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8487 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8488
8489 if (parseType(Ty, TyLoc))
8490 return true;
8491
8493 return error(TyLoc, "invalid type for alloca");
8494
8495 bool AteExtraComma = false;
8496 if (EatIfPresent(lltok::comma)) {
8497 if (Lex.getKind() == lltok::kw_align) {
8498 if (parseOptionalAlignment(Alignment))
8499 return true;
8500 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8501 return true;
8502 } else if (Lex.getKind() == lltok::kw_addrspace) {
8503 ASLoc = Lex.getLoc();
8504 if (parseOptionalAddrSpace(AddrSpace))
8505 return true;
8506 } else if (Lex.getKind() == lltok::MetadataVar) {
8507 AteExtraComma = true;
8508 } else {
8509 if (parseTypeAndValue(Size, SizeLoc, PFS))
8510 return true;
8511 if (EatIfPresent(lltok::comma)) {
8512 if (Lex.getKind() == lltok::kw_align) {
8513 if (parseOptionalAlignment(Alignment))
8514 return true;
8515 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8516 return true;
8517 } else if (Lex.getKind() == lltok::kw_addrspace) {
8518 ASLoc = Lex.getLoc();
8519 if (parseOptionalAddrSpace(AddrSpace))
8520 return true;
8521 } else if (Lex.getKind() == lltok::MetadataVar) {
8522 AteExtraComma = true;
8523 }
8524 }
8525 }
8526 }
8527
8528 if (Size && !Size->getType()->isIntegerTy())
8529 return error(SizeLoc, "element count must have integer type");
8530
8531 SmallPtrSet<Type *, 4> Visited;
8532 if (!Alignment && !Ty->isSized(&Visited))
8533 return error(TyLoc, "Cannot allocate unsized type");
8534 if (!Alignment)
8535 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8536 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8537 AI->setUsedWithInAlloca(IsInAlloca);
8538 AI->setSwiftError(IsSwiftError);
8539 Inst = AI;
8540 return AteExtraComma ? InstExtraComma : InstNormal;
8541}
8542
8543/// parseLoad
8544/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8545/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8546/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8547int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8548 Value *Val; LocTy Loc;
8549 MaybeAlign Alignment;
8550 bool AteExtraComma = false;
8551 bool isAtomic = false;
8554
8555 if (Lex.getKind() == lltok::kw_atomic) {
8556 isAtomic = true;
8557 Lex.Lex();
8558 }
8559
8560 bool isVolatile = false;
8561 if (Lex.getKind() == lltok::kw_volatile) {
8562 isVolatile = true;
8563 Lex.Lex();
8564 }
8565
8566 Type *Ty;
8567 LocTy ExplicitTypeLoc = Lex.getLoc();
8568 if (parseType(Ty) ||
8569 parseToken(lltok::comma, "expected comma after load's type") ||
8570 parseTypeAndValue(Val, Loc, PFS) ||
8571 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8572 parseOptionalCommaAlign(Alignment, AteExtraComma))
8573 return true;
8574
8575 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8576 return error(Loc, "load operand must be a pointer to a first class type");
8577 if (isAtomic && !Alignment)
8578 return error(Loc, "atomic load must have explicit non-zero alignment");
8579 if (Ordering == AtomicOrdering::Release ||
8581 return error(Loc, "atomic load cannot use Release ordering");
8582
8583 SmallPtrSet<Type *, 4> Visited;
8584 if (!Alignment && !Ty->isSized(&Visited))
8585 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8586 if (!Alignment)
8587 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8588 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8589 return AteExtraComma ? InstExtraComma : InstNormal;
8590}
8591
8592/// parseStore
8593
8594/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8595/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8596/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8597int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8598 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8599 MaybeAlign Alignment;
8600 bool AteExtraComma = false;
8601 bool isAtomic = false;
8604
8605 if (Lex.getKind() == lltok::kw_atomic) {
8606 isAtomic = true;
8607 Lex.Lex();
8608 }
8609
8610 bool isVolatile = false;
8611 if (Lex.getKind() == lltok::kw_volatile) {
8612 isVolatile = true;
8613 Lex.Lex();
8614 }
8615
8616 if (parseTypeAndValue(Val, Loc, PFS) ||
8617 parseToken(lltok::comma, "expected ',' after store operand") ||
8618 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8619 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8620 parseOptionalCommaAlign(Alignment, AteExtraComma))
8621 return true;
8622
8623 if (!Ptr->getType()->isPointerTy())
8624 return error(PtrLoc, "store operand must be a pointer");
8625 if (!Val->getType()->isFirstClassType())
8626 return error(Loc, "store operand must be a first class value");
8627 if (isAtomic && !Alignment)
8628 return error(Loc, "atomic store must have explicit non-zero alignment");
8629 if (Ordering == AtomicOrdering::Acquire ||
8631 return error(Loc, "atomic store cannot use Acquire ordering");
8632 SmallPtrSet<Type *, 4> Visited;
8633 if (!Alignment && !Val->getType()->isSized(&Visited))
8634 return error(Loc, "storing unsized types is not allowed");
8635 if (!Alignment)
8636 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8637
8638 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8639 return AteExtraComma ? InstExtraComma : InstNormal;
8640}
8641
8642/// parseCmpXchg
8643/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8644/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8645/// 'Align'?
8646int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8647 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8648 bool AteExtraComma = false;
8649 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8650 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8652 bool isVolatile = false;
8653 bool isWeak = false;
8654 MaybeAlign Alignment;
8655
8656 if (EatIfPresent(lltok::kw_weak))
8657 isWeak = true;
8658
8659 if (EatIfPresent(lltok::kw_volatile))
8660 isVolatile = true;
8661
8662 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8663 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8664 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8665 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8666 parseTypeAndValue(New, NewLoc, PFS) ||
8667 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8668 parseOrdering(FailureOrdering) ||
8669 parseOptionalCommaAlign(Alignment, AteExtraComma))
8670 return true;
8671
8672 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8673 return tokError("invalid cmpxchg success ordering");
8674 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8675 return tokError("invalid cmpxchg failure ordering");
8676 if (!Ptr->getType()->isPointerTy())
8677 return error(PtrLoc, "cmpxchg operand must be a pointer");
8678 if (Cmp->getType() != New->getType())
8679 return error(NewLoc, "compare value and new value type do not match");
8680 if (!New->getType()->isFirstClassType())
8681 return error(NewLoc, "cmpxchg operand must be a first class value");
8682
8683 const Align DefaultAlignment(
8684 PFS.getFunction().getDataLayout().getTypeStoreSize(
8685 Cmp->getType()));
8686
8687 AtomicCmpXchgInst *CXI =
8688 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8689 SuccessOrdering, FailureOrdering, SSID);
8690 CXI->setVolatile(isVolatile);
8691 CXI->setWeak(isWeak);
8692
8693 Inst = CXI;
8694 return AteExtraComma ? InstExtraComma : InstNormal;
8695}
8696
8697/// parseAtomicRMW
8698/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8699/// 'singlethread'? AtomicOrdering
8700int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8701 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8702 bool AteExtraComma = false;
8705 bool isVolatile = false;
8706 bool IsFP = false;
8708 MaybeAlign Alignment;
8709
8710 if (EatIfPresent(lltok::kw_volatile))
8711 isVolatile = true;
8712
8713 switch (Lex.getKind()) {
8714 default:
8715 return tokError("expected binary operation in atomicrmw");
8729 break;
8732 break;
8735 break;
8736 case lltok::kw_usub_sat:
8738 break;
8739 case lltok::kw_fadd:
8741 IsFP = true;
8742 break;
8743 case lltok::kw_fsub:
8745 IsFP = true;
8746 break;
8747 case lltok::kw_fmax:
8749 IsFP = true;
8750 break;
8751 case lltok::kw_fmin:
8753 IsFP = true;
8754 break;
8755 case lltok::kw_fmaximum:
8757 IsFP = true;
8758 break;
8759 case lltok::kw_fminimum:
8761 IsFP = true;
8762 break;
8763 }
8764 Lex.Lex(); // Eat the operation.
8765
8766 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8767 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8768 parseTypeAndValue(Val, ValLoc, PFS) ||
8769 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8770 parseOptionalCommaAlign(Alignment, AteExtraComma))
8771 return true;
8772
8773 if (Ordering == AtomicOrdering::Unordered)
8774 return tokError("atomicrmw cannot be unordered");
8775 if (!Ptr->getType()->isPointerTy())
8776 return error(PtrLoc, "atomicrmw operand must be a pointer");
8777 if (Val->getType()->isScalableTy())
8778 return error(ValLoc, "atomicrmw operand may not be scalable");
8779
8781 if (!Val->getType()->isIntegerTy() &&
8782 !Val->getType()->isFloatingPointTy() &&
8783 !Val->getType()->isPointerTy()) {
8784 return error(
8785 ValLoc,
8787 " operand must be an integer, floating point, or pointer type");
8788 }
8789 } else if (IsFP) {
8790 if (!Val->getType()->isFPOrFPVectorTy()) {
8791 return error(ValLoc, "atomicrmw " +
8793 " operand must be a floating point type");
8794 }
8795 } else {
8796 if (!Val->getType()->isIntegerTy()) {
8797 return error(ValLoc, "atomicrmw " +
8799 " operand must be an integer");
8800 }
8801 }
8802
8803 unsigned Size =
8804 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8805 Val->getType());
8806 if (Size < 8 || (Size & (Size - 1)))
8807 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8808 " integer");
8809 const Align DefaultAlignment(
8810 PFS.getFunction().getDataLayout().getTypeStoreSize(
8811 Val->getType()));
8812 AtomicRMWInst *RMWI =
8813 new AtomicRMWInst(Operation, Ptr, Val,
8814 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8815 RMWI->setVolatile(isVolatile);
8816 Inst = RMWI;
8817 return AteExtraComma ? InstExtraComma : InstNormal;
8818}
8819
8820/// parseFence
8821/// ::= 'fence' 'singlethread'? AtomicOrdering
8822int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8825 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8826 return true;
8827
8828 if (Ordering == AtomicOrdering::Unordered)
8829 return tokError("fence cannot be unordered");
8830 if (Ordering == AtomicOrdering::Monotonic)
8831 return tokError("fence cannot be monotonic");
8832
8833 Inst = new FenceInst(Context, Ordering, SSID);
8834 return InstNormal;
8835}
8836
8837/// parseGetElementPtr
8838/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8839int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8840 Value *Ptr = nullptr;
8841 Value *Val = nullptr;
8842 LocTy Loc, EltLoc;
8843 GEPNoWrapFlags NW;
8844
8845 while (true) {
8846 if (EatIfPresent(lltok::kw_inbounds))
8848 else if (EatIfPresent(lltok::kw_nusw))
8850 else if (EatIfPresent(lltok::kw_nuw))
8852 else
8853 break;
8854 }
8855
8856 Type *Ty = nullptr;
8857 if (parseType(Ty) ||
8858 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8859 parseTypeAndValue(Ptr, Loc, PFS))
8860 return true;
8861
8862 Type *BaseType = Ptr->getType();
8863 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8864 if (!BasePointerType)
8865 return error(Loc, "base of getelementptr must be a pointer");
8866
8867 SmallVector<Value*, 16> Indices;
8868 bool AteExtraComma = false;
8869 // GEP returns a vector of pointers if at least one of parameters is a vector.
8870 // All vector parameters should have the same vector width.
8871 ElementCount GEPWidth = BaseType->isVectorTy()
8872 ? cast<VectorType>(BaseType)->getElementCount()
8874
8875 while (EatIfPresent(lltok::comma)) {
8876 if (Lex.getKind() == lltok::MetadataVar) {
8877 AteExtraComma = true;
8878 break;
8879 }
8880 if (parseTypeAndValue(Val, EltLoc, PFS))
8881 return true;
8882 if (!Val->getType()->isIntOrIntVectorTy())
8883 return error(EltLoc, "getelementptr index must be an integer");
8884
8885 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8886 ElementCount ValNumEl = ValVTy->getElementCount();
8887 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8888 return error(
8889 EltLoc,
8890 "getelementptr vector index has a wrong number of elements");
8891 GEPWidth = ValNumEl;
8892 }
8893 Indices.push_back(Val);
8894 }
8895
8896 SmallPtrSet<Type*, 4> Visited;
8897 if (!Indices.empty() && !Ty->isSized(&Visited))
8898 return error(Loc, "base element of getelementptr must be sized");
8899
8900 auto *STy = dyn_cast<StructType>(Ty);
8901 if (STy && STy->isScalableTy())
8902 return error(Loc, "getelementptr cannot target structure that contains "
8903 "scalable vector type");
8904
8905 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8906 return error(Loc, "invalid getelementptr indices");
8907 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
8908 Inst = GEP;
8909 GEP->setNoWrapFlags(NW);
8910 return AteExtraComma ? InstExtraComma : InstNormal;
8911}
8912
8913/// parseExtractValue
8914/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8915int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8916 Value *Val; LocTy Loc;
8917 SmallVector<unsigned, 4> Indices;
8918 bool AteExtraComma;
8919 if (parseTypeAndValue(Val, Loc, PFS) ||
8920 parseIndexList(Indices, AteExtraComma))
8921 return true;
8922
8923 if (!Val->getType()->isAggregateType())
8924 return error(Loc, "extractvalue operand must be aggregate type");
8925
8926 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8927 return error(Loc, "invalid indices for extractvalue");
8928 Inst = ExtractValueInst::Create(Val, Indices);
8929 return AteExtraComma ? InstExtraComma : InstNormal;
8930}
8931
8932/// parseInsertValue
8933/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8934int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8935 Value *Val0, *Val1; LocTy Loc0, Loc1;
8936 SmallVector<unsigned, 4> Indices;
8937 bool AteExtraComma;
8938 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8939 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8940 parseTypeAndValue(Val1, Loc1, PFS) ||
8941 parseIndexList(Indices, AteExtraComma))
8942 return true;
8943
8944 if (!Val0->getType()->isAggregateType())
8945 return error(Loc0, "insertvalue operand must be aggregate type");
8946
8947 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8948 if (!IndexedType)
8949 return error(Loc0, "invalid indices for insertvalue");
8950 if (IndexedType != Val1->getType())
8951 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8952 getTypeString(Val1->getType()) + "' instead of '" +
8953 getTypeString(IndexedType) + "'");
8954 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8955 return AteExtraComma ? InstExtraComma : InstNormal;
8956}
8957
8958//===----------------------------------------------------------------------===//
8959// Embedded metadata.
8960//===----------------------------------------------------------------------===//
8961
8962/// parseMDNodeVector
8963/// ::= { Element (',' Element)* }
8964/// Element
8965/// ::= 'null' | Metadata
8966bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8967 if (parseToken(lltok::lbrace, "expected '{' here"))
8968 return true;
8969
8970 // Check for an empty list.
8971 if (EatIfPresent(lltok::rbrace))
8972 return false;
8973
8974 do {
8975 if (EatIfPresent(lltok::kw_null)) {
8976 Elts.push_back(nullptr);
8977 continue;
8978 }
8979
8980 Metadata *MD;
8981 if (parseMetadata(MD, nullptr))
8982 return true;
8983 Elts.push_back(MD);
8984 } while (EatIfPresent(lltok::comma));
8985
8986 return parseToken(lltok::rbrace, "expected end of metadata node");
8987}
8988
8989//===----------------------------------------------------------------------===//
8990// Use-list order directives.
8991//===----------------------------------------------------------------------===//
8992bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8993 SMLoc Loc) {
8994 if (!V->hasUseList())
8995 return false;
8996 if (V->use_empty())
8997 return error(Loc, "value has no uses");
8998
8999 unsigned NumUses = 0;
9000 SmallDenseMap<const Use *, unsigned, 16> Order;
9001 for (const Use &U : V->uses()) {
9002 if (++NumUses > Indexes.size())
9003 break;
9004 Order[&U] = Indexes[NumUses - 1];
9005 }
9006 if (NumUses < 2)
9007 return error(Loc, "value only has one use");
9008 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9009 return error(Loc,
9010 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9011
9012 V->sortUseList([&](const Use &L, const Use &R) {
9013 return Order.lookup(&L) < Order.lookup(&R);
9014 });
9015 return false;
9016}
9017
9018/// parseUseListOrderIndexes
9019/// ::= '{' uint32 (',' uint32)+ '}'
9020bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9021 SMLoc Loc = Lex.getLoc();
9022 if (parseToken(lltok::lbrace, "expected '{' here"))
9023 return true;
9024 if (Lex.getKind() == lltok::rbrace)
9025 return tokError("expected non-empty list of uselistorder indexes");
9026
9027 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9028 // indexes should be distinct numbers in the range [0, size-1], and should
9029 // not be in order.
9030 unsigned Offset = 0;
9031 unsigned Max = 0;
9032 bool IsOrdered = true;
9033 assert(Indexes.empty() && "Expected empty order vector");
9034 do {
9035 unsigned Index;
9036 if (parseUInt32(Index))
9037 return true;
9038
9039 // Update consistency checks.
9040 Offset += Index - Indexes.size();
9041 Max = std::max(Max, Index);
9042 IsOrdered &= Index == Indexes.size();
9043
9044 Indexes.push_back(Index);
9045 } while (EatIfPresent(lltok::comma));
9046
9047 if (parseToken(lltok::rbrace, "expected '}' here"))
9048 return true;
9049
9050 if (Indexes.size() < 2)
9051 return error(Loc, "expected >= 2 uselistorder indexes");
9052 if (Offset != 0 || Max >= Indexes.size())
9053 return error(Loc,
9054 "expected distinct uselistorder indexes in range [0, size)");
9055 if (IsOrdered)
9056 return error(Loc, "expected uselistorder indexes to change the order");
9057
9058 return false;
9059}
9060
9061/// parseUseListOrder
9062/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9063bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9064 SMLoc Loc = Lex.getLoc();
9065 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9066 return true;
9067
9068 Value *V;
9069 SmallVector<unsigned, 16> Indexes;
9070 if (parseTypeAndValue(V, PFS) ||
9071 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9072 parseUseListOrderIndexes(Indexes))
9073 return true;
9074
9075 return sortUseListOrder(V, Indexes, Loc);
9076}
9077
9078/// parseUseListOrderBB
9079/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9080bool LLParser::parseUseListOrderBB() {
9081 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9082 SMLoc Loc = Lex.getLoc();
9083 Lex.Lex();
9084
9085 ValID Fn, Label;
9086 SmallVector<unsigned, 16> Indexes;
9087 if (parseValID(Fn, /*PFS=*/nullptr) ||
9088 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9089 parseValID(Label, /*PFS=*/nullptr) ||
9090 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9091 parseUseListOrderIndexes(Indexes))
9092 return true;
9093
9094 // Check the function.
9095 GlobalValue *GV;
9096 if (Fn.Kind == ValID::t_GlobalName)
9097 GV = M->getNamedValue(Fn.StrVal);
9098 else if (Fn.Kind == ValID::t_GlobalID)
9099 GV = NumberedVals.get(Fn.UIntVal);
9100 else
9101 return error(Fn.Loc, "expected function name in uselistorder_bb");
9102 if (!GV)
9103 return error(Fn.Loc,
9104 "invalid function forward reference in uselistorder_bb");
9105 auto *F = dyn_cast<Function>(GV);
9106 if (!F)
9107 return error(Fn.Loc, "expected function name in uselistorder_bb");
9108 if (F->isDeclaration())
9109 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9110
9111 // Check the basic block.
9112 if (Label.Kind == ValID::t_LocalID)
9113 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9114 if (Label.Kind != ValID::t_LocalName)
9115 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9116 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9117 if (!V)
9118 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9119 if (!isa<BasicBlock>(V))
9120 return error(Label.Loc, "expected basic block in uselistorder_bb");
9121
9122 return sortUseListOrder(V, Indexes, Loc);
9123}
9124
9125/// ModuleEntry
9126/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9127/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9128bool LLParser::parseModuleEntry(unsigned ID) {
9129 assert(Lex.getKind() == lltok::kw_module);
9130 Lex.Lex();
9131
9132 std::string Path;
9133 if (parseToken(lltok::colon, "expected ':' here") ||
9134 parseToken(lltok::lparen, "expected '(' here") ||
9135 parseToken(lltok::kw_path, "expected 'path' here") ||
9136 parseToken(lltok::colon, "expected ':' here") ||
9137 parseStringConstant(Path) ||
9138 parseToken(lltok::comma, "expected ',' here") ||
9139 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9140 parseToken(lltok::colon, "expected ':' here") ||
9141 parseToken(lltok::lparen, "expected '(' here"))
9142 return true;
9143
9144 ModuleHash Hash;
9145 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9146 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9147 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9148 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9149 parseUInt32(Hash[4]))
9150 return true;
9151
9152 if (parseToken(lltok::rparen, "expected ')' here") ||
9153 parseToken(lltok::rparen, "expected ')' here"))
9154 return true;
9155
9156 auto ModuleEntry = Index->addModule(Path, Hash);
9157 ModuleIdMap[ID] = ModuleEntry->first();
9158
9159 return false;
9160}
9161
9162/// TypeIdEntry
9163/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9164bool LLParser::parseTypeIdEntry(unsigned ID) {
9165 assert(Lex.getKind() == lltok::kw_typeid);
9166 Lex.Lex();
9167
9168 std::string Name;
9169 if (parseToken(lltok::colon, "expected ':' here") ||
9170 parseToken(lltok::lparen, "expected '(' here") ||
9171 parseToken(lltok::kw_name, "expected 'name' here") ||
9172 parseToken(lltok::colon, "expected ':' here") ||
9173 parseStringConstant(Name))
9174 return true;
9175
9176 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9177 if (parseToken(lltok::comma, "expected ',' here") ||
9178 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9179 return true;
9180
9181 // Check if this ID was forward referenced, and if so, update the
9182 // corresponding GUIDs.
9183 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9184 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9185 for (auto TIDRef : FwdRefTIDs->second) {
9186 assert(!*TIDRef.first &&
9187 "Forward referenced type id GUID expected to be 0");
9188 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9189 }
9190 ForwardRefTypeIds.erase(FwdRefTIDs);
9191 }
9192
9193 return false;
9194}
9195
9196/// TypeIdSummary
9197/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9198bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9199 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9200 parseToken(lltok::colon, "expected ':' here") ||
9201 parseToken(lltok::lparen, "expected '(' here") ||
9202 parseTypeTestResolution(TIS.TTRes))
9203 return true;
9204
9205 if (EatIfPresent(lltok::comma)) {
9206 // Expect optional wpdResolutions field
9207 if (parseOptionalWpdResolutions(TIS.WPDRes))
9208 return true;
9209 }
9210
9211 if (parseToken(lltok::rparen, "expected ')' here"))
9212 return true;
9213
9214 return false;
9215}
9216
9218 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9219
9220/// TypeIdCompatibleVtableEntry
9221/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9222/// TypeIdCompatibleVtableInfo
9223/// ')'
9224bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9226 Lex.Lex();
9227
9228 std::string Name;
9229 if (parseToken(lltok::colon, "expected ':' here") ||
9230 parseToken(lltok::lparen, "expected '(' here") ||
9231 parseToken(lltok::kw_name, "expected 'name' here") ||
9232 parseToken(lltok::colon, "expected ':' here") ||
9233 parseStringConstant(Name))
9234 return true;
9235
9237 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9238 if (parseToken(lltok::comma, "expected ',' here") ||
9239 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9240 parseToken(lltok::colon, "expected ':' here") ||
9241 parseToken(lltok::lparen, "expected '(' here"))
9242 return true;
9243
9244 IdToIndexMapType IdToIndexMap;
9245 // parse each call edge
9246 do {
9248 if (parseToken(lltok::lparen, "expected '(' here") ||
9249 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9250 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9251 parseToken(lltok::comma, "expected ',' here"))
9252 return true;
9253
9254 LocTy Loc = Lex.getLoc();
9255 unsigned GVId;
9256 ValueInfo VI;
9257 if (parseGVReference(VI, GVId))
9258 return true;
9259
9260 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9261 // forward reference. We will save the location of the ValueInfo needing an
9262 // update, but can only do so once the std::vector is finalized.
9263 if (VI == EmptyVI)
9264 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9265 TI.push_back({Offset, VI});
9266
9267 if (parseToken(lltok::rparen, "expected ')' in call"))
9268 return true;
9269 } while (EatIfPresent(lltok::comma));
9270
9271 // Now that the TI vector is finalized, it is safe to save the locations
9272 // of any forward GV references that need updating later.
9273 for (auto I : IdToIndexMap) {
9274 auto &Infos = ForwardRefValueInfos[I.first];
9275 for (auto P : I.second) {
9276 assert(TI[P.first].VTableVI == EmptyVI &&
9277 "Forward referenced ValueInfo expected to be empty");
9278 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9279 }
9280 }
9281
9282 if (parseToken(lltok::rparen, "expected ')' here") ||
9283 parseToken(lltok::rparen, "expected ')' here"))
9284 return true;
9285
9286 // Check if this ID was forward referenced, and if so, update the
9287 // corresponding GUIDs.
9288 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9289 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9290 for (auto TIDRef : FwdRefTIDs->second) {
9291 assert(!*TIDRef.first &&
9292 "Forward referenced type id GUID expected to be 0");
9293 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9294 }
9295 ForwardRefTypeIds.erase(FwdRefTIDs);
9296 }
9297
9298 return false;
9299}
9300
9301/// TypeTestResolution
9302/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9303/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9304/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9305/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9306/// [',' 'inlinesBits' ':' UInt64]? ')'
9307bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9308 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9309 parseToken(lltok::colon, "expected ':' here") ||
9310 parseToken(lltok::lparen, "expected '(' here") ||
9311 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9312 parseToken(lltok::colon, "expected ':' here"))
9313 return true;
9314
9315 switch (Lex.getKind()) {
9316 case lltok::kw_unknown:
9318 break;
9319 case lltok::kw_unsat:
9321 break;
9324 break;
9325 case lltok::kw_inline:
9327 break;
9328 case lltok::kw_single:
9330 break;
9331 case lltok::kw_allOnes:
9333 break;
9334 default:
9335 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9336 }
9337 Lex.Lex();
9338
9339 if (parseToken(lltok::comma, "expected ',' here") ||
9340 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9341 parseToken(lltok::colon, "expected ':' here") ||
9342 parseUInt32(TTRes.SizeM1BitWidth))
9343 return true;
9344
9345 // parse optional fields
9346 while (EatIfPresent(lltok::comma)) {
9347 switch (Lex.getKind()) {
9349 Lex.Lex();
9350 if (parseToken(lltok::colon, "expected ':'") ||
9351 parseUInt64(TTRes.AlignLog2))
9352 return true;
9353 break;
9354 case lltok::kw_sizeM1:
9355 Lex.Lex();
9356 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9357 return true;
9358 break;
9359 case lltok::kw_bitMask: {
9360 unsigned Val;
9361 Lex.Lex();
9362 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9363 return true;
9364 assert(Val <= 0xff);
9365 TTRes.BitMask = (uint8_t)Val;
9366 break;
9367 }
9369 Lex.Lex();
9370 if (parseToken(lltok::colon, "expected ':'") ||
9371 parseUInt64(TTRes.InlineBits))
9372 return true;
9373 break;
9374 default:
9375 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9376 }
9377 }
9378
9379 if (parseToken(lltok::rparen, "expected ')' here"))
9380 return true;
9381
9382 return false;
9383}
9384
9385/// OptionalWpdResolutions
9386/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9387/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9388bool LLParser::parseOptionalWpdResolutions(
9389 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9390 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9391 parseToken(lltok::colon, "expected ':' here") ||
9392 parseToken(lltok::lparen, "expected '(' here"))
9393 return true;
9394
9395 do {
9396 uint64_t Offset;
9397 WholeProgramDevirtResolution WPDRes;
9398 if (parseToken(lltok::lparen, "expected '(' here") ||
9399 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9400 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9401 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9402 parseToken(lltok::rparen, "expected ')' here"))
9403 return true;
9404 WPDResMap[Offset] = WPDRes;
9405 } while (EatIfPresent(lltok::comma));
9406
9407 if (parseToken(lltok::rparen, "expected ')' here"))
9408 return true;
9409
9410 return false;
9411}
9412
9413/// WpdRes
9414/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9415/// [',' OptionalResByArg]? ')'
9416/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9417/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9418/// [',' OptionalResByArg]? ')'
9419/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9420/// [',' OptionalResByArg]? ')'
9421bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9422 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9423 parseToken(lltok::colon, "expected ':' here") ||
9424 parseToken(lltok::lparen, "expected '(' here") ||
9425 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9426 parseToken(lltok::colon, "expected ':' here"))
9427 return true;
9428
9429 switch (Lex.getKind()) {
9430 case lltok::kw_indir:
9432 break;
9435 break;
9438 break;
9439 default:
9440 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9441 }
9442 Lex.Lex();
9443
9444 // parse optional fields
9445 while (EatIfPresent(lltok::comma)) {
9446 switch (Lex.getKind()) {
9448 Lex.Lex();
9449 if (parseToken(lltok::colon, "expected ':' here") ||
9450 parseStringConstant(WPDRes.SingleImplName))
9451 return true;
9452 break;
9453 case lltok::kw_resByArg:
9454 if (parseOptionalResByArg(WPDRes.ResByArg))
9455 return true;
9456 break;
9457 default:
9458 return error(Lex.getLoc(),
9459 "expected optional WholeProgramDevirtResolution field");
9460 }
9461 }
9462
9463 if (parseToken(lltok::rparen, "expected ')' here"))
9464 return true;
9465
9466 return false;
9467}
9468
9469/// OptionalResByArg
9470/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9471/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9472/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9473/// 'virtualConstProp' )
9474/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9475/// [',' 'bit' ':' UInt32]? ')'
9476bool LLParser::parseOptionalResByArg(
9477 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9478 &ResByArg) {
9479 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9480 parseToken(lltok::colon, "expected ':' here") ||
9481 parseToken(lltok::lparen, "expected '(' here"))
9482 return true;
9483
9484 do {
9485 std::vector<uint64_t> Args;
9486 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9487 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9488 parseToken(lltok::colon, "expected ':' here") ||
9489 parseToken(lltok::lparen, "expected '(' here") ||
9490 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9491 parseToken(lltok::colon, "expected ':' here"))
9492 return true;
9493
9494 WholeProgramDevirtResolution::ByArg ByArg;
9495 switch (Lex.getKind()) {
9496 case lltok::kw_indir:
9498 break;
9501 break;
9504 break;
9507 break;
9508 default:
9509 return error(Lex.getLoc(),
9510 "unexpected WholeProgramDevirtResolution::ByArg kind");
9511 }
9512 Lex.Lex();
9513
9514 // parse optional fields
9515 while (EatIfPresent(lltok::comma)) {
9516 switch (Lex.getKind()) {
9517 case lltok::kw_info:
9518 Lex.Lex();
9519 if (parseToken(lltok::colon, "expected ':' here") ||
9520 parseUInt64(ByArg.Info))
9521 return true;
9522 break;
9523 case lltok::kw_byte:
9524 Lex.Lex();
9525 if (parseToken(lltok::colon, "expected ':' here") ||
9526 parseUInt32(ByArg.Byte))
9527 return true;
9528 break;
9529 case lltok::kw_bit:
9530 Lex.Lex();
9531 if (parseToken(lltok::colon, "expected ':' here") ||
9532 parseUInt32(ByArg.Bit))
9533 return true;
9534 break;
9535 default:
9536 return error(Lex.getLoc(),
9537 "expected optional whole program devirt field");
9538 }
9539 }
9540
9541 if (parseToken(lltok::rparen, "expected ')' here"))
9542 return true;
9543
9544 ResByArg[Args] = ByArg;
9545 } while (EatIfPresent(lltok::comma));
9546
9547 if (parseToken(lltok::rparen, "expected ')' here"))
9548 return true;
9549
9550 return false;
9551}
9552
9553/// OptionalResByArg
9554/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9555bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9556 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9557 parseToken(lltok::colon, "expected ':' here") ||
9558 parseToken(lltok::lparen, "expected '(' here"))
9559 return true;
9560
9561 do {
9562 uint64_t Val;
9563 if (parseUInt64(Val))
9564 return true;
9565 Args.push_back(Val);
9566 } while (EatIfPresent(lltok::comma));
9567
9568 if (parseToken(lltok::rparen, "expected ')' here"))
9569 return true;
9570
9571 return false;
9572}
9573
9574static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9575
9576static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9577 bool ReadOnly = Fwd->isReadOnly();
9578 bool WriteOnly = Fwd->isWriteOnly();
9579 assert(!(ReadOnly && WriteOnly));
9580 *Fwd = Resolved;
9581 if (ReadOnly)
9582 Fwd->setReadOnly();
9583 if (WriteOnly)
9584 Fwd->setWriteOnly();
9585}
9586
9587/// Stores the given Name/GUID and associated summary into the Index.
9588/// Also updates any forward references to the associated entry ID.
9589bool LLParser::addGlobalValueToIndex(
9590 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9591 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9592 // First create the ValueInfo utilizing the Name or GUID.
9593 ValueInfo VI;
9594 if (GUID != 0) {
9595 assert(Name.empty());
9596 VI = Index->getOrInsertValueInfo(GUID);
9597 } else {
9598 assert(!Name.empty());
9599 if (M) {
9600 auto *GV = M->getNamedValue(Name);
9601 if (!GV)
9602 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9603
9604 VI = Index->getOrInsertValueInfo(GV);
9605 } else {
9606 assert(
9607 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9608 "Need a source_filename to compute GUID for local");
9610 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9611 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9612 }
9613 }
9614
9615 // Resolve forward references from calls/refs
9616 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9617 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9618 for (auto VIRef : FwdRefVIs->second) {
9619 assert(VIRef.first->getRef() == FwdVIRef &&
9620 "Forward referenced ValueInfo expected to be empty");
9621 resolveFwdRef(VIRef.first, VI);
9622 }
9623 ForwardRefValueInfos.erase(FwdRefVIs);
9624 }
9625
9626 // Resolve forward references from aliases
9627 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9628 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9629 for (auto AliaseeRef : FwdRefAliasees->second) {
9630 assert(!AliaseeRef.first->hasAliasee() &&
9631 "Forward referencing alias already has aliasee");
9632 assert(Summary && "Aliasee must be a definition");
9633 AliaseeRef.first->setAliasee(VI, Summary.get());
9634 }
9635 ForwardRefAliasees.erase(FwdRefAliasees);
9636 }
9637
9638 // Add the summary if one was provided.
9639 if (Summary)
9640 Index->addGlobalValueSummary(VI, std::move(Summary));
9641
9642 // Save the associated ValueInfo for use in later references by ID.
9643 if (ID == NumberedValueInfos.size())
9644 NumberedValueInfos.push_back(VI);
9645 else {
9646 // Handle non-continuous numbers (to make test simplification easier).
9647 if (ID > NumberedValueInfos.size())
9648 NumberedValueInfos.resize(ID + 1);
9649 NumberedValueInfos[ID] = VI;
9650 }
9651
9652 return false;
9653}
9654
9655/// parseSummaryIndexFlags
9656/// ::= 'flags' ':' UInt64
9657bool LLParser::parseSummaryIndexFlags() {
9658 assert(Lex.getKind() == lltok::kw_flags);
9659 Lex.Lex();
9660
9661 if (parseToken(lltok::colon, "expected ':' here"))
9662 return true;
9663 uint64_t Flags;
9664 if (parseUInt64(Flags))
9665 return true;
9666 if (Index)
9667 Index->setFlags(Flags);
9668 return false;
9669}
9670
9671/// parseBlockCount
9672/// ::= 'blockcount' ':' UInt64
9673bool LLParser::parseBlockCount() {
9674 assert(Lex.getKind() == lltok::kw_blockcount);
9675 Lex.Lex();
9676
9677 if (parseToken(lltok::colon, "expected ':' here"))
9678 return true;
9679 uint64_t BlockCount;
9680 if (parseUInt64(BlockCount))
9681 return true;
9682 if (Index)
9683 Index->setBlockCount(BlockCount);
9684 return false;
9685}
9686
9687/// parseGVEntry
9688/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9689/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9690/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9691bool LLParser::parseGVEntry(unsigned ID) {
9692 assert(Lex.getKind() == lltok::kw_gv);
9693 Lex.Lex();
9694
9695 if (parseToken(lltok::colon, "expected ':' here") ||
9696 parseToken(lltok::lparen, "expected '(' here"))
9697 return true;
9698
9699 LocTy Loc = Lex.getLoc();
9700 std::string Name;
9702 switch (Lex.getKind()) {
9703 case lltok::kw_name:
9704 Lex.Lex();
9705 if (parseToken(lltok::colon, "expected ':' here") ||
9706 parseStringConstant(Name))
9707 return true;
9708 // Can't create GUID/ValueInfo until we have the linkage.
9709 break;
9710 case lltok::kw_guid:
9711 Lex.Lex();
9712 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9713 return true;
9714 break;
9715 default:
9716 return error(Lex.getLoc(), "expected name or guid tag");
9717 }
9718
9719 if (!EatIfPresent(lltok::comma)) {
9720 // No summaries. Wrap up.
9721 if (parseToken(lltok::rparen, "expected ')' here"))
9722 return true;
9723 // This was created for a call to an external or indirect target.
9724 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9725 // created for indirect calls with VP. A Name with no GUID came from
9726 // an external definition. We pass ExternalLinkage since that is only
9727 // used when the GUID must be computed from Name, and in that case
9728 // the symbol must have external linkage.
9729 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9730 nullptr, Loc);
9731 }
9732
9733 // Have a list of summaries
9734 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9735 parseToken(lltok::colon, "expected ':' here") ||
9736 parseToken(lltok::lparen, "expected '(' here"))
9737 return true;
9738 do {
9739 switch (Lex.getKind()) {
9740 case lltok::kw_function:
9741 if (parseFunctionSummary(Name, GUID, ID))
9742 return true;
9743 break;
9744 case lltok::kw_variable:
9745 if (parseVariableSummary(Name, GUID, ID))
9746 return true;
9747 break;
9748 case lltok::kw_alias:
9749 if (parseAliasSummary(Name, GUID, ID))
9750 return true;
9751 break;
9752 default:
9753 return error(Lex.getLoc(), "expected summary type");
9754 }
9755 } while (EatIfPresent(lltok::comma));
9756
9757 if (parseToken(lltok::rparen, "expected ')' here") ||
9758 parseToken(lltok::rparen, "expected ')' here"))
9759 return true;
9760
9761 return false;
9762}
9763
9764/// FunctionSummary
9765/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9766/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9767/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9768/// [',' OptionalRefs]? ')'
9769bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9770 unsigned ID) {
9771 LocTy Loc = Lex.getLoc();
9772 assert(Lex.getKind() == lltok::kw_function);
9773 Lex.Lex();
9774
9775 StringRef ModulePath;
9776 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9778 /*NotEligibleToImport=*/false,
9779 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9781 unsigned InstCount;
9783 FunctionSummary::TypeIdInfo TypeIdInfo;
9784 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9786 std::vector<CallsiteInfo> Callsites;
9787 std::vector<AllocInfo> Allocs;
9788 // Default is all-zeros (conservative values).
9789 FunctionSummary::FFlags FFlags = {};
9790 if (parseToken(lltok::colon, "expected ':' here") ||
9791 parseToken(lltok::lparen, "expected '(' here") ||
9792 parseModuleReference(ModulePath) ||
9793 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9794 parseToken(lltok::comma, "expected ',' here") ||
9795 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9796 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9797 return true;
9798
9799 // parse optional fields
9800 while (EatIfPresent(lltok::comma)) {
9801 switch (Lex.getKind()) {
9803 if (parseOptionalFFlags(FFlags))
9804 return true;
9805 break;
9806 case lltok::kw_calls:
9807 if (parseOptionalCalls(Calls))
9808 return true;
9809 break;
9811 if (parseOptionalTypeIdInfo(TypeIdInfo))
9812 return true;
9813 break;
9814 case lltok::kw_refs:
9815 if (parseOptionalRefs(Refs))
9816 return true;
9817 break;
9818 case lltok::kw_params:
9819 if (parseOptionalParamAccesses(ParamAccesses))
9820 return true;
9821 break;
9822 case lltok::kw_allocs:
9823 if (parseOptionalAllocs(Allocs))
9824 return true;
9825 break;
9827 if (parseOptionalCallsites(Callsites))
9828 return true;
9829 break;
9830 default:
9831 return error(Lex.getLoc(), "expected optional function summary field");
9832 }
9833 }
9834
9835 if (parseToken(lltok::rparen, "expected ')' here"))
9836 return true;
9837
9838 auto FS = std::make_unique<FunctionSummary>(
9839 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9840 std::move(TypeIdInfo.TypeTests),
9841 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9842 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9843 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9844 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9845 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9846
9847 FS->setModulePath(ModulePath);
9848
9849 return addGlobalValueToIndex(Name, GUID,
9851 std::move(FS), Loc);
9852}
9853
9854/// VariableSummary
9855/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9856/// [',' OptionalRefs]? ')'
9857bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9858 unsigned ID) {
9859 LocTy Loc = Lex.getLoc();
9860 assert(Lex.getKind() == lltok::kw_variable);
9861 Lex.Lex();
9862
9863 StringRef ModulePath;
9864 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9866 /*NotEligibleToImport=*/false,
9867 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9869 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9870 /* WriteOnly */ false,
9871 /* Constant */ false,
9874 VTableFuncList VTableFuncs;
9875 if (parseToken(lltok::colon, "expected ':' here") ||
9876 parseToken(lltok::lparen, "expected '(' here") ||
9877 parseModuleReference(ModulePath) ||
9878 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9879 parseToken(lltok::comma, "expected ',' here") ||
9880 parseGVarFlags(GVarFlags))
9881 return true;
9882
9883 // parse optional fields
9884 while (EatIfPresent(lltok::comma)) {
9885 switch (Lex.getKind()) {
9887 if (parseOptionalVTableFuncs(VTableFuncs))
9888 return true;
9889 break;
9890 case lltok::kw_refs:
9891 if (parseOptionalRefs(Refs))
9892 return true;
9893 break;
9894 default:
9895 return error(Lex.getLoc(), "expected optional variable summary field");
9896 }
9897 }
9898
9899 if (parseToken(lltok::rparen, "expected ')' here"))
9900 return true;
9901
9902 auto GS =
9903 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9904
9905 GS->setModulePath(ModulePath);
9906 GS->setVTableFuncs(std::move(VTableFuncs));
9907
9908 return addGlobalValueToIndex(Name, GUID,
9910 std::move(GS), Loc);
9911}
9912
9913/// AliasSummary
9914/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9915/// 'aliasee' ':' GVReference ')'
9916bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9917 unsigned ID) {
9918 assert(Lex.getKind() == lltok::kw_alias);
9919 LocTy Loc = Lex.getLoc();
9920 Lex.Lex();
9921
9922 StringRef ModulePath;
9923 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
9925 /*NotEligibleToImport=*/false,
9926 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9928 if (parseToken(lltok::colon, "expected ':' here") ||
9929 parseToken(lltok::lparen, "expected '(' here") ||
9930 parseModuleReference(ModulePath) ||
9931 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9932 parseToken(lltok::comma, "expected ',' here") ||
9933 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9934 parseToken(lltok::colon, "expected ':' here"))
9935 return true;
9936
9937 ValueInfo AliaseeVI;
9938 unsigned GVId;
9939 if (parseGVReference(AliaseeVI, GVId))
9940 return true;
9941
9942 if (parseToken(lltok::rparen, "expected ')' here"))
9943 return true;
9944
9945 auto AS = std::make_unique<AliasSummary>(GVFlags);
9946
9947 AS->setModulePath(ModulePath);
9948
9949 // Record forward reference if the aliasee is not parsed yet.
9950 if (AliaseeVI.getRef() == FwdVIRef) {
9951 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9952 } else {
9953 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9954 assert(Summary && "Aliasee must be a definition");
9955 AS->setAliasee(AliaseeVI, Summary);
9956 }
9957
9958 return addGlobalValueToIndex(Name, GUID,
9960 std::move(AS), Loc);
9961}
9962
9963/// Flag
9964/// ::= [0|1]
9965bool LLParser::parseFlag(unsigned &Val) {
9966 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9967 return tokError("expected integer");
9968 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9969 Lex.Lex();
9970 return false;
9971}
9972
9973/// OptionalFFlags
9974/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9975/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9976/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9977/// [',' 'noInline' ':' Flag]? ')'
9978/// [',' 'alwaysInline' ':' Flag]? ')'
9979/// [',' 'noUnwind' ':' Flag]? ')'
9980/// [',' 'mayThrow' ':' Flag]? ')'
9981/// [',' 'hasUnknownCall' ':' Flag]? ')'
9982/// [',' 'mustBeUnreachable' ':' Flag]? ')'
9983
9984bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9985 assert(Lex.getKind() == lltok::kw_funcFlags);
9986 Lex.Lex();
9987
9988 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9989 parseToken(lltok::lparen, "expected '(' in funcFlags"))
9990 return true;
9991
9992 do {
9993 unsigned Val = 0;
9994 switch (Lex.getKind()) {
9995 case lltok::kw_readNone:
9996 Lex.Lex();
9997 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9998 return true;
9999 FFlags.ReadNone = Val;
10000 break;
10001 case lltok::kw_readOnly:
10002 Lex.Lex();
10003 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10004 return true;
10005 FFlags.ReadOnly = Val;
10006 break;
10008 Lex.Lex();
10009 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10010 return true;
10011 FFlags.NoRecurse = Val;
10012 break;
10014 Lex.Lex();
10015 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10016 return true;
10017 FFlags.ReturnDoesNotAlias = Val;
10018 break;
10019 case lltok::kw_noInline:
10020 Lex.Lex();
10021 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10022 return true;
10023 FFlags.NoInline = Val;
10024 break;
10026 Lex.Lex();
10027 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10028 return true;
10029 FFlags.AlwaysInline = Val;
10030 break;
10031 case lltok::kw_noUnwind:
10032 Lex.Lex();
10033 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10034 return true;
10035 FFlags.NoUnwind = Val;
10036 break;
10037 case lltok::kw_mayThrow:
10038 Lex.Lex();
10039 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10040 return true;
10041 FFlags.MayThrow = Val;
10042 break;
10044 Lex.Lex();
10045 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10046 return true;
10047 FFlags.HasUnknownCall = Val;
10048 break;
10050 Lex.Lex();
10051 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10052 return true;
10053 FFlags.MustBeUnreachable = Val;
10054 break;
10055 default:
10056 return error(Lex.getLoc(), "expected function flag type");
10057 }
10058 } while (EatIfPresent(lltok::comma));
10059
10060 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10061 return true;
10062
10063 return false;
10064}
10065
10066/// OptionalCalls
10067/// := 'calls' ':' '(' Call [',' Call]* ')'
10068/// Call ::= '(' 'callee' ':' GVReference
10069/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10070/// [ ',' 'tail' ]? ')'
10071bool LLParser::parseOptionalCalls(
10072 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10073 assert(Lex.getKind() == lltok::kw_calls);
10074 Lex.Lex();
10075
10076 if (parseToken(lltok::colon, "expected ':' in calls") ||
10077 parseToken(lltok::lparen, "expected '(' in calls"))
10078 return true;
10079
10080 IdToIndexMapType IdToIndexMap;
10081 // parse each call edge
10082 do {
10083 ValueInfo VI;
10084 if (parseToken(lltok::lparen, "expected '(' in call") ||
10085 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10086 parseToken(lltok::colon, "expected ':'"))
10087 return true;
10088
10089 LocTy Loc = Lex.getLoc();
10090 unsigned GVId;
10091 if (parseGVReference(VI, GVId))
10092 return true;
10093
10095 unsigned RelBF = 0;
10096 unsigned HasTailCall = false;
10097
10098 // parse optional fields
10099 while (EatIfPresent(lltok::comma)) {
10100 switch (Lex.getKind()) {
10101 case lltok::kw_hotness:
10102 Lex.Lex();
10103 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10104 return true;
10105 break;
10106 case lltok::kw_relbf:
10107 Lex.Lex();
10108 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10109 return true;
10110 break;
10111 case lltok::kw_tail:
10112 Lex.Lex();
10113 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10114 return true;
10115 break;
10116 default:
10117 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10118 }
10119 }
10120 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
10121 return tokError("Expected only one of hotness or relbf");
10122 // Keep track of the Call array index needing a forward reference.
10123 // We will save the location of the ValueInfo needing an update, but
10124 // can only do so once the std::vector is finalized.
10125 if (VI.getRef() == FwdVIRef)
10126 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10127 Calls.push_back(
10128 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
10129
10130 if (parseToken(lltok::rparen, "expected ')' in call"))
10131 return true;
10132 } while (EatIfPresent(lltok::comma));
10133
10134 // Now that the Calls vector is finalized, it is safe to save the locations
10135 // of any forward GV references that need updating later.
10136 for (auto I : IdToIndexMap) {
10137 auto &Infos = ForwardRefValueInfos[I.first];
10138 for (auto P : I.second) {
10139 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10140 "Forward referenced ValueInfo expected to be empty");
10141 Infos.emplace_back(&Calls[P.first].first, P.second);
10142 }
10143 }
10144
10145 if (parseToken(lltok::rparen, "expected ')' in calls"))
10146 return true;
10147
10148 return false;
10149}
10150
10151/// Hotness
10152/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10153bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10154 switch (Lex.getKind()) {
10155 case lltok::kw_unknown:
10157 break;
10158 case lltok::kw_cold:
10160 break;
10161 case lltok::kw_none:
10163 break;
10164 case lltok::kw_hot:
10166 break;
10167 case lltok::kw_critical:
10169 break;
10170 default:
10171 return error(Lex.getLoc(), "invalid call edge hotness");
10172 }
10173 Lex.Lex();
10174 return false;
10175}
10176
10177/// OptionalVTableFuncs
10178/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10179/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10180bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10181 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10182 Lex.Lex();
10183
10184 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10185 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10186 return true;
10187
10188 IdToIndexMapType IdToIndexMap;
10189 // parse each virtual function pair
10190 do {
10191 ValueInfo VI;
10192 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10193 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10194 parseToken(lltok::colon, "expected ':'"))
10195 return true;
10196
10197 LocTy Loc = Lex.getLoc();
10198 unsigned GVId;
10199 if (parseGVReference(VI, GVId))
10200 return true;
10201
10202 uint64_t Offset;
10203 if (parseToken(lltok::comma, "expected comma") ||
10204 parseToken(lltok::kw_offset, "expected offset") ||
10205 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10206 return true;
10207
10208 // Keep track of the VTableFuncs array index needing a forward reference.
10209 // We will save the location of the ValueInfo needing an update, but
10210 // can only do so once the std::vector is finalized.
10211 if (VI == EmptyVI)
10212 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10213 VTableFuncs.push_back({VI, Offset});
10214
10215 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10216 return true;
10217 } while (EatIfPresent(lltok::comma));
10218
10219 // Now that the VTableFuncs vector is finalized, it is safe to save the
10220 // locations of any forward GV references that need updating later.
10221 for (auto I : IdToIndexMap) {
10222 auto &Infos = ForwardRefValueInfos[I.first];
10223 for (auto P : I.second) {
10224 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10225 "Forward referenced ValueInfo expected to be empty");
10226 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10227 }
10228 }
10229
10230 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10231 return true;
10232
10233 return false;
10234}
10235
10236/// ParamNo := 'param' ':' UInt64
10237bool LLParser::parseParamNo(uint64_t &ParamNo) {
10238 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10239 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10240 return true;
10241 return false;
10242}
10243
10244/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10245bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10246 APSInt Lower;
10247 APSInt Upper;
10248 auto ParseAPSInt = [&](APSInt &Val) {
10249 if (Lex.getKind() != lltok::APSInt)
10250 return tokError("expected integer");
10251 Val = Lex.getAPSIntVal();
10252 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10253 Val.setIsSigned(true);
10254 Lex.Lex();
10255 return false;
10256 };
10257 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10258 parseToken(lltok::colon, "expected ':' here") ||
10259 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10260 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10261 parseToken(lltok::rsquare, "expected ']' here"))
10262 return true;
10263
10264 ++Upper;
10265 Range =
10266 (Lower == Upper && !Lower.isMaxValue())
10267 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10268 : ConstantRange(Lower, Upper);
10269
10270 return false;
10271}
10272
10273/// ParamAccessCall
10274/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10275bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10276 IdLocListType &IdLocList) {
10277 if (parseToken(lltok::lparen, "expected '(' here") ||
10278 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10279 parseToken(lltok::colon, "expected ':' here"))
10280 return true;
10281
10282 unsigned GVId;
10283 ValueInfo VI;
10284 LocTy Loc = Lex.getLoc();
10285 if (parseGVReference(VI, GVId))
10286 return true;
10287
10288 Call.Callee = VI;
10289 IdLocList.emplace_back(GVId, Loc);
10290
10291 if (parseToken(lltok::comma, "expected ',' here") ||
10292 parseParamNo(Call.ParamNo) ||
10293 parseToken(lltok::comma, "expected ',' here") ||
10294 parseParamAccessOffset(Call.Offsets))
10295 return true;
10296
10297 if (parseToken(lltok::rparen, "expected ')' here"))
10298 return true;
10299
10300 return false;
10301}
10302
10303/// ParamAccess
10304/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10305/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10306bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10307 IdLocListType &IdLocList) {
10308 if (parseToken(lltok::lparen, "expected '(' here") ||
10309 parseParamNo(Param.ParamNo) ||
10310 parseToken(lltok::comma, "expected ',' here") ||
10311 parseParamAccessOffset(Param.Use))
10312 return true;
10313
10314 if (EatIfPresent(lltok::comma)) {
10315 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10316 parseToken(lltok::colon, "expected ':' here") ||
10317 parseToken(lltok::lparen, "expected '(' here"))
10318 return true;
10319 do {
10320 FunctionSummary::ParamAccess::Call Call;
10321 if (parseParamAccessCall(Call, IdLocList))
10322 return true;
10323 Param.Calls.push_back(Call);
10324 } while (EatIfPresent(lltok::comma));
10325
10326 if (parseToken(lltok::rparen, "expected ')' here"))
10327 return true;
10328 }
10329
10330 if (parseToken(lltok::rparen, "expected ')' here"))
10331 return true;
10332
10333 return false;
10334}
10335
10336/// OptionalParamAccesses
10337/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10338bool LLParser::parseOptionalParamAccesses(
10339 std::vector<FunctionSummary::ParamAccess> &Params) {
10340 assert(Lex.getKind() == lltok::kw_params);
10341 Lex.Lex();
10342
10343 if (parseToken(lltok::colon, "expected ':' here") ||
10344 parseToken(lltok::lparen, "expected '(' here"))
10345 return true;
10346
10347 IdLocListType VContexts;
10348 size_t CallsNum = 0;
10349 do {
10350 FunctionSummary::ParamAccess ParamAccess;
10351 if (parseParamAccess(ParamAccess, VContexts))
10352 return true;
10353 CallsNum += ParamAccess.Calls.size();
10354 assert(VContexts.size() == CallsNum);
10355 (void)CallsNum;
10356 Params.emplace_back(std::move(ParamAccess));
10357 } while (EatIfPresent(lltok::comma));
10358
10359 if (parseToken(lltok::rparen, "expected ')' here"))
10360 return true;
10361
10362 // Now that the Params is finalized, it is safe to save the locations
10363 // of any forward GV references that need updating later.
10364 IdLocListType::const_iterator ItContext = VContexts.begin();
10365 for (auto &PA : Params) {
10366 for (auto &C : PA.Calls) {
10367 if (C.Callee.getRef() == FwdVIRef)
10368 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10369 ItContext->second);
10370 ++ItContext;
10371 }
10372 }
10373 assert(ItContext == VContexts.end());
10374
10375 return false;
10376}
10377
10378/// OptionalRefs
10379/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10380bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10381 assert(Lex.getKind() == lltok::kw_refs);
10382 Lex.Lex();
10383
10384 if (parseToken(lltok::colon, "expected ':' in refs") ||
10385 parseToken(lltok::lparen, "expected '(' in refs"))
10386 return true;
10387
10388 struct ValueContext {
10389 ValueInfo VI;
10390 unsigned GVId;
10391 LocTy Loc;
10392 };
10393 std::vector<ValueContext> VContexts;
10394 // parse each ref edge
10395 do {
10396 ValueContext VC;
10397 VC.Loc = Lex.getLoc();
10398 if (parseGVReference(VC.VI, VC.GVId))
10399 return true;
10400 VContexts.push_back(VC);
10401 } while (EatIfPresent(lltok::comma));
10402
10403 // Sort value contexts so that ones with writeonly
10404 // and readonly ValueInfo are at the end of VContexts vector.
10405 // See FunctionSummary::specialRefCounts()
10406 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10407 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10408 });
10409
10410 IdToIndexMapType IdToIndexMap;
10411 for (auto &VC : VContexts) {
10412 // Keep track of the Refs array index needing a forward reference.
10413 // We will save the location of the ValueInfo needing an update, but
10414 // can only do so once the std::vector is finalized.
10415 if (VC.VI.getRef() == FwdVIRef)
10416 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10417 Refs.push_back(VC.VI);
10418 }
10419
10420 // Now that the Refs vector is finalized, it is safe to save the locations
10421 // of any forward GV references that need updating later.
10422 for (auto I : IdToIndexMap) {
10423 auto &Infos = ForwardRefValueInfos[I.first];
10424 for (auto P : I.second) {
10425 assert(Refs[P.first].getRef() == FwdVIRef &&
10426 "Forward referenced ValueInfo expected to be empty");
10427 Infos.emplace_back(&Refs[P.first], P.second);
10428 }
10429 }
10430
10431 if (parseToken(lltok::rparen, "expected ')' in refs"))
10432 return true;
10433
10434 return false;
10435}
10436
10437/// OptionalTypeIdInfo
10438/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10439/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10440/// [',' TypeCheckedLoadConstVCalls]? ')'
10441bool LLParser::parseOptionalTypeIdInfo(
10442 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10443 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10444 Lex.Lex();
10445
10446 if (parseToken(lltok::colon, "expected ':' here") ||
10447 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10448 return true;
10449
10450 do {
10451 switch (Lex.getKind()) {
10453 if (parseTypeTests(TypeIdInfo.TypeTests))
10454 return true;
10455 break;
10457 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10458 TypeIdInfo.TypeTestAssumeVCalls))
10459 return true;
10460 break;
10462 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10463 TypeIdInfo.TypeCheckedLoadVCalls))
10464 return true;
10465 break;
10467 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10468 TypeIdInfo.TypeTestAssumeConstVCalls))
10469 return true;
10470 break;
10472 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10473 TypeIdInfo.TypeCheckedLoadConstVCalls))
10474 return true;
10475 break;
10476 default:
10477 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10478 }
10479 } while (EatIfPresent(lltok::comma));
10480
10481 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10482 return true;
10483
10484 return false;
10485}
10486
10487/// TypeTests
10488/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10489/// [',' (SummaryID | UInt64)]* ')'
10490bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10491 assert(Lex.getKind() == lltok::kw_typeTests);
10492 Lex.Lex();
10493
10494 if (parseToken(lltok::colon, "expected ':' here") ||
10495 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10496 return true;
10497
10498 IdToIndexMapType IdToIndexMap;
10499 do {
10501 if (Lex.getKind() == lltok::SummaryID) {
10502 unsigned ID = Lex.getUIntVal();
10503 LocTy Loc = Lex.getLoc();
10504 // Keep track of the TypeTests array index needing a forward reference.
10505 // We will save the location of the GUID needing an update, but
10506 // can only do so once the std::vector is finalized.
10507 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10508 Lex.Lex();
10509 } else if (parseUInt64(GUID))
10510 return true;
10511 TypeTests.push_back(GUID);
10512 } while (EatIfPresent(lltok::comma));
10513
10514 // Now that the TypeTests vector is finalized, it is safe to save the
10515 // locations of any forward GV references that need updating later.
10516 for (auto I : IdToIndexMap) {
10517 auto &Ids = ForwardRefTypeIds[I.first];
10518 for (auto P : I.second) {
10519 assert(TypeTests[P.first] == 0 &&
10520 "Forward referenced type id GUID expected to be 0");
10521 Ids.emplace_back(&TypeTests[P.first], P.second);
10522 }
10523 }
10524
10525 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10526 return true;
10527
10528 return false;
10529}
10530
10531/// VFuncIdList
10532/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10533bool LLParser::parseVFuncIdList(
10534 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10535 assert(Lex.getKind() == Kind);
10536 Lex.Lex();
10537
10538 if (parseToken(lltok::colon, "expected ':' here") ||
10539 parseToken(lltok::lparen, "expected '(' here"))
10540 return true;
10541
10542 IdToIndexMapType IdToIndexMap;
10543 do {
10544 FunctionSummary::VFuncId VFuncId;
10545 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10546 return true;
10547 VFuncIdList.push_back(VFuncId);
10548 } while (EatIfPresent(lltok::comma));
10549
10550 if (parseToken(lltok::rparen, "expected ')' here"))
10551 return true;
10552
10553 // Now that the VFuncIdList vector is finalized, it is safe to save the
10554 // locations of any forward GV references that need updating later.
10555 for (auto I : IdToIndexMap) {
10556 auto &Ids = ForwardRefTypeIds[I.first];
10557 for (auto P : I.second) {
10558 assert(VFuncIdList[P.first].GUID == 0 &&
10559 "Forward referenced type id GUID expected to be 0");
10560 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10561 }
10562 }
10563
10564 return false;
10565}
10566
10567/// ConstVCallList
10568/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10569bool LLParser::parseConstVCallList(
10570 lltok::Kind Kind,
10571 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10572 assert(Lex.getKind() == Kind);
10573 Lex.Lex();
10574
10575 if (parseToken(lltok::colon, "expected ':' here") ||
10576 parseToken(lltok::lparen, "expected '(' here"))
10577 return true;
10578
10579 IdToIndexMapType IdToIndexMap;
10580 do {
10581 FunctionSummary::ConstVCall ConstVCall;
10582 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10583 return true;
10584 ConstVCallList.push_back(ConstVCall);
10585 } while (EatIfPresent(lltok::comma));
10586
10587 if (parseToken(lltok::rparen, "expected ')' here"))
10588 return true;
10589
10590 // Now that the ConstVCallList vector is finalized, it is safe to save the
10591 // locations of any forward GV references that need updating later.
10592 for (auto I : IdToIndexMap) {
10593 auto &Ids = ForwardRefTypeIds[I.first];
10594 for (auto P : I.second) {
10595 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10596 "Forward referenced type id GUID expected to be 0");
10597 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10598 }
10599 }
10600
10601 return false;
10602}
10603
10604/// ConstVCall
10605/// ::= '(' VFuncId ',' Args ')'
10606bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10607 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10608 if (parseToken(lltok::lparen, "expected '(' here") ||
10609 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10610 return true;
10611
10612 if (EatIfPresent(lltok::comma))
10613 if (parseArgs(ConstVCall.Args))
10614 return true;
10615
10616 if (parseToken(lltok::rparen, "expected ')' here"))
10617 return true;
10618
10619 return false;
10620}
10621
10622/// VFuncId
10623/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10624/// 'offset' ':' UInt64 ')'
10625bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10626 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10627 assert(Lex.getKind() == lltok::kw_vFuncId);
10628 Lex.Lex();
10629
10630 if (parseToken(lltok::colon, "expected ':' here") ||
10631 parseToken(lltok::lparen, "expected '(' here"))
10632 return true;
10633
10634 if (Lex.getKind() == lltok::SummaryID) {
10635 VFuncId.GUID = 0;
10636 unsigned ID = Lex.getUIntVal();
10637 LocTy Loc = Lex.getLoc();
10638 // Keep track of the array index needing a forward reference.
10639 // We will save the location of the GUID needing an update, but
10640 // can only do so once the caller's std::vector is finalized.
10641 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10642 Lex.Lex();
10643 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10644 parseToken(lltok::colon, "expected ':' here") ||
10645 parseUInt64(VFuncId.GUID))
10646 return true;
10647
10648 if (parseToken(lltok::comma, "expected ',' here") ||
10649 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10650 parseToken(lltok::colon, "expected ':' here") ||
10651 parseUInt64(VFuncId.Offset) ||
10652 parseToken(lltok::rparen, "expected ')' here"))
10653 return true;
10654
10655 return false;
10656}
10657
10658/// GVFlags
10659/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10660/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10661/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10662/// 'canAutoHide' ':' Flag ',' ')'
10663bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10664 assert(Lex.getKind() == lltok::kw_flags);
10665 Lex.Lex();
10666
10667 if (parseToken(lltok::colon, "expected ':' here") ||
10668 parseToken(lltok::lparen, "expected '(' here"))
10669 return true;
10670
10671 do {
10672 unsigned Flag = 0;
10673 switch (Lex.getKind()) {
10674 case lltok::kw_linkage:
10675 Lex.Lex();
10676 if (parseToken(lltok::colon, "expected ':'"))
10677 return true;
10678 bool HasLinkage;
10679 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10680 assert(HasLinkage && "Linkage not optional in summary entry");
10681 Lex.Lex();
10682 break;
10684 Lex.Lex();
10685 if (parseToken(lltok::colon, "expected ':'"))
10686 return true;
10687 parseOptionalVisibility(Flag);
10688 GVFlags.Visibility = Flag;
10689 break;
10691 Lex.Lex();
10692 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10693 return true;
10694 GVFlags.NotEligibleToImport = Flag;
10695 break;
10696 case lltok::kw_live:
10697 Lex.Lex();
10698 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10699 return true;
10700 GVFlags.Live = Flag;
10701 break;
10702 case lltok::kw_dsoLocal:
10703 Lex.Lex();
10704 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10705 return true;
10706 GVFlags.DSOLocal = Flag;
10707 break;
10709 Lex.Lex();
10710 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10711 return true;
10712 GVFlags.CanAutoHide = Flag;
10713 break;
10715 Lex.Lex();
10716 if (parseToken(lltok::colon, "expected ':'"))
10717 return true;
10719 if (parseOptionalImportType(Lex.getKind(), IK))
10720 return true;
10721 GVFlags.ImportType = static_cast<unsigned>(IK);
10722 Lex.Lex();
10723 break;
10724 default:
10725 return error(Lex.getLoc(), "expected gv flag type");
10726 }
10727 } while (EatIfPresent(lltok::comma));
10728
10729 if (parseToken(lltok::rparen, "expected ')' here"))
10730 return true;
10731
10732 return false;
10733}
10734
10735/// GVarFlags
10736/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10737/// ',' 'writeonly' ':' Flag
10738/// ',' 'constant' ':' Flag ')'
10739bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10740 assert(Lex.getKind() == lltok::kw_varFlags);
10741 Lex.Lex();
10742
10743 if (parseToken(lltok::colon, "expected ':' here") ||
10744 parseToken(lltok::lparen, "expected '(' here"))
10745 return true;
10746
10747 auto ParseRest = [this](unsigned int &Val) {
10748 Lex.Lex();
10749 if (parseToken(lltok::colon, "expected ':'"))
10750 return true;
10751 return parseFlag(Val);
10752 };
10753
10754 do {
10755 unsigned Flag = 0;
10756 switch (Lex.getKind()) {
10757 case lltok::kw_readonly:
10758 if (ParseRest(Flag))
10759 return true;
10760 GVarFlags.MaybeReadOnly = Flag;
10761 break;
10762 case lltok::kw_writeonly:
10763 if (ParseRest(Flag))
10764 return true;
10765 GVarFlags.MaybeWriteOnly = Flag;
10766 break;
10767 case lltok::kw_constant:
10768 if (ParseRest(Flag))
10769 return true;
10770 GVarFlags.Constant = Flag;
10771 break;
10773 if (ParseRest(Flag))
10774 return true;
10775 GVarFlags.VCallVisibility = Flag;
10776 break;
10777 default:
10778 return error(Lex.getLoc(), "expected gvar flag type");
10779 }
10780 } while (EatIfPresent(lltok::comma));
10781 return parseToken(lltok::rparen, "expected ')' here");
10782}
10783
10784/// ModuleReference
10785/// ::= 'module' ':' UInt
10786bool LLParser::parseModuleReference(StringRef &ModulePath) {
10787 // parse module id.
10788 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10789 parseToken(lltok::colon, "expected ':' here") ||
10790 parseToken(lltok::SummaryID, "expected module ID"))
10791 return true;
10792
10793 unsigned ModuleID = Lex.getUIntVal();
10794 auto I = ModuleIdMap.find(ModuleID);
10795 // We should have already parsed all module IDs
10796 assert(I != ModuleIdMap.end());
10797 ModulePath = I->second;
10798 return false;
10799}
10800
10801/// GVReference
10802/// ::= SummaryID
10803bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10804 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10805 if (!ReadOnly)
10806 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10807 if (parseToken(lltok::SummaryID, "expected GV ID"))
10808 return true;
10809
10810 GVId = Lex.getUIntVal();
10811 // Check if we already have a VI for this GV
10812 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10813 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10814 VI = NumberedValueInfos[GVId];
10815 } else
10816 // We will create a forward reference to the stored location.
10817 VI = ValueInfo(false, FwdVIRef);
10818
10819 if (ReadOnly)
10820 VI.setReadOnly();
10821 if (WriteOnly)
10822 VI.setWriteOnly();
10823 return false;
10824}
10825
10826/// OptionalAllocs
10827/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10828/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10829/// ',' MemProfs ')'
10830/// Version ::= UInt32
10831bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10832 assert(Lex.getKind() == lltok::kw_allocs);
10833 Lex.Lex();
10834
10835 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10836 parseToken(lltok::lparen, "expected '(' in allocs"))
10837 return true;
10838
10839 // parse each alloc
10840 do {
10841 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10842 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10843 parseToken(lltok::colon, "expected ':'") ||
10844 parseToken(lltok::lparen, "expected '(' in versions"))
10845 return true;
10846
10847 SmallVector<uint8_t> Versions;
10848 do {
10849 uint8_t V = 0;
10850 if (parseAllocType(V))
10851 return true;
10852 Versions.push_back(V);
10853 } while (EatIfPresent(lltok::comma));
10854
10855 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10856 parseToken(lltok::comma, "expected ',' in alloc"))
10857 return true;
10858
10859 std::vector<MIBInfo> MIBs;
10860 if (parseMemProfs(MIBs))
10861 return true;
10862
10863 Allocs.push_back({Versions, MIBs});
10864
10865 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10866 return true;
10867 } while (EatIfPresent(lltok::comma));
10868
10869 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10870 return true;
10871
10872 return false;
10873}
10874
10875/// MemProfs
10876/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10877/// MemProf ::= '(' 'type' ':' AllocType
10878/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10879/// StackId ::= UInt64
10880bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10881 assert(Lex.getKind() == lltok::kw_memProf);
10882 Lex.Lex();
10883
10884 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10885 parseToken(lltok::lparen, "expected '(' in memprof"))
10886 return true;
10887
10888 // parse each MIB
10889 do {
10890 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10891 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10892 parseToken(lltok::colon, "expected ':'"))
10893 return true;
10894
10895 uint8_t AllocType;
10896 if (parseAllocType(AllocType))
10897 return true;
10898
10899 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10900 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10901 parseToken(lltok::colon, "expected ':'") ||
10902 parseToken(lltok::lparen, "expected '(' in stackIds"))
10903 return true;
10904
10905 SmallVector<unsigned> StackIdIndices;
10906 // Combined index alloc records may not have a stack id list.
10907 if (Lex.getKind() != lltok::rparen) {
10908 do {
10909 uint64_t StackId = 0;
10910 if (parseUInt64(StackId))
10911 return true;
10912 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10913 } while (EatIfPresent(lltok::comma));
10914 }
10915
10916 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10917 return true;
10918
10919 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10920
10921 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10922 return true;
10923 } while (EatIfPresent(lltok::comma));
10924
10925 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10926 return true;
10927
10928 return false;
10929}
10930
10931/// AllocType
10932/// := ('none'|'notcold'|'cold'|'hot')
10933bool LLParser::parseAllocType(uint8_t &AllocType) {
10934 switch (Lex.getKind()) {
10935 case lltok::kw_none:
10937 break;
10938 case lltok::kw_notcold:
10940 break;
10941 case lltok::kw_cold:
10943 break;
10944 case lltok::kw_hot:
10945 AllocType = (uint8_t)AllocationType::Hot;
10946 break;
10947 default:
10948 return error(Lex.getLoc(), "invalid alloc type");
10949 }
10950 Lex.Lex();
10951 return false;
10952}
10953
10954/// OptionalCallsites
10955/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10956/// Callsite ::= '(' 'callee' ':' GVReference
10957/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10958/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10959/// Version ::= UInt32
10960/// StackId ::= UInt64
10961bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10962 assert(Lex.getKind() == lltok::kw_callsites);
10963 Lex.Lex();
10964
10965 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10966 parseToken(lltok::lparen, "expected '(' in callsites"))
10967 return true;
10968
10969 IdToIndexMapType IdToIndexMap;
10970 // parse each callsite
10971 do {
10972 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10973 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10974 parseToken(lltok::colon, "expected ':'"))
10975 return true;
10976
10977 ValueInfo VI;
10978 unsigned GVId = 0;
10979 LocTy Loc = Lex.getLoc();
10980 if (!EatIfPresent(lltok::kw_null)) {
10981 if (parseGVReference(VI, GVId))
10982 return true;
10983 }
10984
10985 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10986 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10987 parseToken(lltok::colon, "expected ':'") ||
10988 parseToken(lltok::lparen, "expected '(' in clones"))
10989 return true;
10990
10991 SmallVector<unsigned> Clones;
10992 do {
10993 unsigned V = 0;
10994 if (parseUInt32(V))
10995 return true;
10996 Clones.push_back(V);
10997 } while (EatIfPresent(lltok::comma));
10998
10999 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11000 parseToken(lltok::comma, "expected ',' in callsite") ||
11001 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11002 parseToken(lltok::colon, "expected ':'") ||
11003 parseToken(lltok::lparen, "expected '(' in stackIds"))
11004 return true;
11005
11006 SmallVector<unsigned> StackIdIndices;
11007 // Synthesized callsite records will not have a stack id list.
11008 if (Lex.getKind() != lltok::rparen) {
11009 do {
11010 uint64_t StackId = 0;
11011 if (parseUInt64(StackId))
11012 return true;
11013 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11014 } while (EatIfPresent(lltok::comma));
11015 }
11016
11017 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11018 return true;
11019
11020 // Keep track of the Callsites array index needing a forward reference.
11021 // We will save the location of the ValueInfo needing an update, but
11022 // can only do so once the SmallVector is finalized.
11023 if (VI.getRef() == FwdVIRef)
11024 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11025 Callsites.push_back({VI, Clones, StackIdIndices});
11026
11027 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11028 return true;
11029 } while (EatIfPresent(lltok::comma));
11030
11031 // Now that the Callsites vector is finalized, it is safe to save the
11032 // locations of any forward GV references that need updating later.
11033 for (auto I : IdToIndexMap) {
11034 auto &Infos = ForwardRefValueInfos[I.first];
11035 for (auto P : I.second) {
11036 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11037 "Forward referenced ValueInfo expected to be empty");
11038 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11039 }
11040 }
11041
11042 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11043 return true;
11044
11045 return false;
11046}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:244
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:151
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:67
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1128
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1237
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:120
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
iterator begin() const
Definition ArrayRef.h:135
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:766
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:107
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:88
@ None
No attributes have been set.
Definition Attributes.h:90
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:472
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:367
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:536
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static 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:1274
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:131
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:157
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)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:194
unsigned size() const
Definition DenseMap.h:110
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:310
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:404
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:399
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:166
Argument * arg_iterator
Definition Function.h:72
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:836
void setPersonalityFn(Constant *Fn)
arg_iterator arg_begin()
Definition Function.h:866
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1038
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:355
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:274
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:598
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:655
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:214
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:245
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:93
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:251
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:228
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:524
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:566
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:65
lltok::Kind getKind() const
Definition LLLexer.h:71
LocTy getLoc() const
Definition LLLexer.h:70
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:123
LLLexer::LocTy LocTy
Definition LLParser.h:109
LLVMContext & getContext()
Definition LLParser.h:210
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:107
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:94
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:75
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1078
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1577
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1569
A single uniqued string.
Definition Metadata.h:721
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1537
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1546
static MemoryEffectsBase readOnly()
Definition ModRef.h:125
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:193
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:135
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:141
static MemoryEffectsBase writeOnly()
Definition ModRef.h:130
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:158
static MemoryEffectsBase none()
Definition ModRef.h:120
static MemoryEffectsBase unknown()
Definition ModRef.h:115
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:183
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:104
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:876
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:23
constexpr const char * getPointer() const
Definition SMLoc.h:34
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:414
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:620
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:704
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:539
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:441
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:914
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:288
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:62
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:145
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:282
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:250
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:295
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:198
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:304
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:142
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:294
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:258
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:503
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
static constexpr uint64_t MaximumAlignment
Definition Value.h:830
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:111
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:598
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:631
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:703
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:153
@ kw_riscv_vls_cc
Definition LLToken.h:189
@ kw_cxx_fast_tlscc
Definition LLToken.h:172
@ kw_extractvalue
Definition LLToken.h:364
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:499
@ kw_arm_apcscc
Definition LLToken.h:145
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:140
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:151
@ kw_provenance
Definition LLToken.h:220
@ kw_mustBeUnreachable
Definition LLToken.h:410
@ kw_internal
Definition LLToken.h:54
@ kw_no_sanitize_hwaddress
Definition LLToken.h:478
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:449
@ kw_canAutoHide
Definition LLToken.h:394
@ kw_alwaysInline
Definition LLToken.h:406
@ kw_insertelement
Definition LLToken.h:361
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:192
@ kw_inaccessiblememonly
Definition LLToken.h:213
@ kw_amdgpu_gfx
Definition LLToken.h:183
@ kw_getelementptr
Definition LLToken.h:358
@ kw_m68k_rtdcc
Definition LLToken.h:186
@ kw_preserve_nonecc
Definition LLToken.h:167
@ kw_x86_fastcallcc
Definition LLToken.h:141
@ kw_visibility
Definition LLToken.h:390
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:191
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:452
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:139
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:429
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:149
@ kw_amdgpu_kernel
Definition LLToken.h:182
@ kw_uselistorder
Definition LLToken.h:377
@ kw_blockcount
Definition LLToken.h:388
@ kw_notEligibleToImport
Definition LLToken.h:391
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:143
@ kw_ptx_device
Definition LLToken.h:157
@ kw_personality
Definition LLToken.h:333
@ DwarfEnumKind
Definition LLToken.h:512
@ kw_declaration
Definition LLToken.h:397
@ DwarfAttEncoding
Definition LLToken.h:498
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:158
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:409
@ kw_x86_intrcc
Definition LLToken.h:169
@ kw_addrspacecast
Definition LLToken.h:328
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:496
@ kw_x86_thiscallcc
Definition LLToken.h:142
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:190
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:378
@ NameTableKind
Definition LLToken.h:504
@ kw_inlineBits
Definition LLToken.h:447
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:212
@ kw_blockaddress
Definition LLToken.h:366
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:184
@ kw_landingpad
Definition LLToken.h:332
@ kw_aarch64_vector_pcs
Definition LLToken.h:148
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:428
@ FixedPointKind
Definition LLToken.h:505
@ kw_ptx_kernel
Definition LLToken.h:156
@ kw_extractelement
Definition LLToken.h:360
@ kw_branchFunnel
Definition LLToken.h:453
@ kw_typeidCompatibleVTable
Definition LLToken.h:434
@ kw_vTableFuncs
Definition LLToken.h:420
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:427
@ kw_no_sanitize_address
Definition LLToken.h:475
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:214
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:481
@ DwarfSourceLangName
Definition LLToken.h:501
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:181
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:346
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:146
@ kw_read_provenance
Definition LLToken.h:221
@ kw_cleanuppad
Definition LLToken.h:349
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:454
@ kw_swifttailcc
Definition LLToken.h:164
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:426
@ kw_attributes
Definition LLToken.h:195
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:457
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:443
@ kw_nodeduplicate
Definition LLToken.h:250
@ kw_avr_signalcc
Definition LLToken.h:155
@ kw_exactmatch
Definition LLToken.h:248
@ kw_unreachable
Definition LLToken.h:344
@ kw_intel_ocl_bicc
Definition LLToken.h:138
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:404
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:150
@ kw_preserve_allcc
Definition LLToken.h:166
@ kw_importType
Definition LLToken.h:395
@ kw_cleanupret
Definition LLToken.h:345
@ kw_shufflevector
Definition LLToken.h:362
@ kw_riscv_vector_cc
Definition LLToken.h:188
@ kw_avr_intrcc
Definition LLToken.h:154
@ kw_definition
Definition LLToken.h:396
@ kw_virtualConstProp
Definition LLToken.h:459
@ kw_vcall_visibility
Definition LLToken.h:448
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:208
@ kw_preserve_mostcc
Definition LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:147
@ kw_typeTestRes
Definition LLToken.h:436
@ kw_x86_regcallcc
Definition LLToken.h:144
@ kw_typeIdInfo
Definition LLToken.h:424
@ kw_amdgpu_cs_chain
Definition LLToken.h:180
@ kw_dso_local_equivalent
Definition LLToken.h:367
@ kw_x86_64_sysvcc
Definition LLToken.h:160
@ DbgRecordType
Definition LLToken.h:511
@ kw_address_is_null
Definition LLToken.h:219
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:152
@ kw_uniqueRetVal
Definition LLToken.h:458
@ kw_insertvalue
Definition LLToken.h:365
@ kw_indirectbr
Definition LLToken.h:341
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:577
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
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 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:1657
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:644
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:51
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
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:634
auto cast_or_null(const Y &Val)
Definition Casting.h:715
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:293
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:296
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:754
UWTableKind
Definition CodeGen.h:148
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:151
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:150
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:288
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1624
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:339
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:198
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:305
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:548
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:35
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:1956
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1869
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:560
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:315
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
static LLVM_ABI const fltSemantics & IEEEsingle() LLVM_READNONE
Definition APFloat.cpp:266
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:304
static LLVM_ABI const fltSemantics & IEEEdouble() LLVM_READNONE
Definition APFloat.cpp:267
static LLVM_ABI const fltSemantics & IEEEhalf() LLVM_READNONE
Definition APFloat.cpp:264
static LLVM_ABI const fltSemantics & BFloat() LLVM_READNONE
Definition APFloat.cpp:265
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:34
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:53
@ t_PackedConstantStruct
Definition LLParser.h:71
@ t_ConstantStruct
Definition LLParser.h:70
@ t_ConstantSplat
Definition LLParser.h:68
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:75
FunctionType * FTy
Definition LLParser.h:76
LLLexer::LocTy Loc
Definition LLParser.h:74
std::string StrVal
Definition LLParser.h:77
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.