LLVM 22.0.0git
AsmWriter.cpp
Go to the documentation of this file.
1//===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
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 library implements `print` family of functions in classes like
10// Module, Function, Value, etc. In-memory representation of those classes is
11// converted to IR strings.
12//
13// Note that these routines must be extremely tolerant of various errors in the
14// LLVM code, because it can be used for debugging transformations.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/APFloat.h"
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SetVector.h"
28#include "llvm/ADT/StringRef.h"
31#include "llvm/Config/llvm-config.h"
32#include "llvm/IR/Argument.h"
34#include "llvm/IR/Attributes.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CFG.h"
37#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Comdat.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GlobalAlias.h"
46#include "llvm/IR/GlobalIFunc.h"
48#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/InlineAsm.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
56#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/Metadata.h"
58#include "llvm/IR/Module.h"
61#include "llvm/IR/Operator.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/TypeFinder.h"
65#include "llvm/IR/Use.h"
66#include "llvm/IR/User.h"
67#include "llvm/IR/Value.h"
71#include "llvm/Support/Debug.h"
73#include "llvm/Support/Format.h"
77#include <cassert>
78#include <cctype>
79#include <cstddef>
80#include <cstdint>
81#include <iterator>
82#include <memory>
83#include <optional>
84#include <string>
85#include <tuple>
86#include <utility>
87#include <vector>
88
89using namespace llvm;
90
91static cl::opt<bool>
92 PrintInstAddrs("print-inst-addrs", cl::Hidden,
93 cl::desc("Print addresses of instructions when dumping"));
94
96 "print-inst-debug-locs", cl::Hidden,
97 cl::desc("Pretty print debug locations of instructions when dumping"));
98
100 "print-prof-data", cl::Hidden,
101 cl::desc("Pretty print perf data (branch weights, etc) when dumping"));
102
103// Make virtual table appear in this compilation unit.
105
106//===----------------------------------------------------------------------===//
107// Helper Functions
108//===----------------------------------------------------------------------===//
109
111
114
115/// Look for a value that might be wrapped as metadata, e.g. a value in a
116/// metadata operand. Returns the input value as-is if it is not wrapped.
117static const Value *skipMetadataWrapper(const Value *V) {
118 if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
119 if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
120 return VAM->getValue();
121 return V;
122}
123
124static void orderValue(const Value *V, OrderMap &OM) {
125 if (OM.lookup(V))
126 return;
127
128 if (const Constant *C = dyn_cast<Constant>(V)) {
129 if (isa<ConstantData>(C))
130 return;
131
132 if (C->getNumOperands() && !isa<GlobalValue>(C))
133 for (const Value *Op : C->operands())
134 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
135 orderValue(Op, OM);
136 }
137
138 // Note: we cannot cache this lookup above, since inserting into the map
139 // changes the map's size, and thus affects the other IDs.
140 unsigned ID = OM.size() + 1;
141 OM[V] = ID;
142}
143
144static OrderMap orderModule(const Module *M) {
145 OrderMap OM;
146
147 auto orderConstantValue = [&OM](const Value *V) {
148 if (isa<Constant>(V) || isa<InlineAsm>(V))
149 orderValue(V, OM);
150 };
151
152 auto OrderConstantFromMetadata = [&](Metadata *MD) {
153 if (const auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
154 orderConstantValue(VAM->getValue());
155 } else if (const auto *AL = dyn_cast<DIArgList>(MD)) {
156 for (const auto *VAM : AL->getArgs())
157 orderConstantValue(VAM->getValue());
158 }
159 };
160
161 for (const GlobalVariable &G : M->globals()) {
162 if (G.hasInitializer())
163 if (!isa<GlobalValue>(G.getInitializer()))
164 orderValue(G.getInitializer(), OM);
165 orderValue(&G, OM);
166 }
167 for (const GlobalAlias &A : M->aliases()) {
168 if (!isa<GlobalValue>(A.getAliasee()))
169 orderValue(A.getAliasee(), OM);
170 orderValue(&A, OM);
171 }
172 for (const GlobalIFunc &I : M->ifuncs()) {
173 if (!isa<GlobalValue>(I.getResolver()))
174 orderValue(I.getResolver(), OM);
175 orderValue(&I, OM);
176 }
177 for (const Function &F : *M) {
178 for (const Use &U : F.operands())
179 if (!isa<GlobalValue>(U.get()))
180 orderValue(U.get(), OM);
181
182 orderValue(&F, OM);
183
184 if (F.isDeclaration())
185 continue;
186
187 for (const Argument &A : F.args())
188 orderValue(&A, OM);
189 for (const BasicBlock &BB : F) {
190 orderValue(&BB, OM);
191 for (const Instruction &I : BB) {
192 // Debug records can contain Value references, that can then contain
193 // Values disconnected from the rest of the Value hierachy, if wrapped
194 // in some kind of constant-expression. Find and order any Values that
195 // are wrapped in debug-info.
196 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
197 OrderConstantFromMetadata(DVR.getRawLocation());
198 if (DVR.isDbgAssign())
199 OrderConstantFromMetadata(DVR.getRawAddress());
200 }
201
202 for (const Value *Op : I.operands()) {
204 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
205 isa<InlineAsm>(*Op))
206 orderValue(Op, OM);
207 }
208 orderValue(&I, OM);
209 }
210 }
211 }
212 return OM;
213}
214
215static std::vector<unsigned>
216predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
217 // Predict use-list order for this one.
218 using Entry = std::pair<const Use *, unsigned>;
220 for (const Use &U : V->uses())
221 // Check if this user will be serialized.
222 if (OM.lookup(U.getUser()))
223 List.push_back(std::make_pair(&U, List.size()));
224
225 if (List.size() < 2)
226 // We may have lost some users.
227 return {};
228
229 // When referencing a value before its declaration, a temporary value is
230 // created, which will later be RAUWed with the actual value. This reverses
231 // the use list. This happens for all values apart from basic blocks.
232 bool GetsReversed = !isa<BasicBlock>(V);
233 if (auto *BA = dyn_cast<BlockAddress>(V))
234 ID = OM.lookup(BA->getBasicBlock());
235 llvm::sort(List, [&](const Entry &L, const Entry &R) {
236 const Use *LU = L.first;
237 const Use *RU = R.first;
238 if (LU == RU)
239 return false;
240
241 auto LID = OM.lookup(LU->getUser());
242 auto RID = OM.lookup(RU->getUser());
243
244 // If ID is 4, then expect: 7 6 5 1 2 3.
245 if (LID < RID) {
246 if (GetsReversed)
247 if (RID <= ID)
248 return true;
249 return false;
250 }
251 if (RID < LID) {
252 if (GetsReversed)
253 if (LID <= ID)
254 return false;
255 return true;
256 }
257
258 // LID and RID are equal, so we have different operands of the same user.
259 // Assume operands are added in order for all instructions.
260 if (GetsReversed)
261 if (LID <= ID)
262 return LU->getOperandNo() < RU->getOperandNo();
263 return LU->getOperandNo() > RU->getOperandNo();
264 });
265
267 // Order is already correct.
268 return {};
269
270 // Store the shuffle.
271 std::vector<unsigned> Shuffle(List.size());
272 for (size_t I = 0, E = List.size(); I != E; ++I)
273 Shuffle[I] = List[I].second;
274 return Shuffle;
275}
276
278 OrderMap OM = orderModule(M);
279 UseListOrderMap ULOM;
280 for (const auto &Pair : OM) {
281 const Value *V = Pair.first;
282 if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
283 continue;
284
285 std::vector<unsigned> Shuffle =
286 predictValueUseListOrder(V, Pair.second, OM);
287 if (Shuffle.empty())
288 continue;
289
290 const Function *F = nullptr;
291 if (auto *I = dyn_cast<Instruction>(V))
292 F = I->getFunction();
293 if (auto *A = dyn_cast<Argument>(V))
294 F = A->getParent();
295 if (auto *BB = dyn_cast<BasicBlock>(V))
296 F = BB->getParent();
297 ULOM[F][V] = std::move(Shuffle);
298 }
299 return ULOM;
300}
301
302static const Module *getModuleFromVal(const Value *V) {
303 if (const Argument *MA = dyn_cast<Argument>(V))
304 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
305
306 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
307 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
308
309 if (const Instruction *I = dyn_cast<Instruction>(V)) {
310 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
311 return M ? M->getParent() : nullptr;
312 }
313
314 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
315 return GV->getParent();
316
317 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
318 for (const User *U : MAV->users())
319 if (isa<Instruction>(U))
320 if (const Module *M = getModuleFromVal(U))
321 return M;
322 return nullptr;
323 }
324
325 return nullptr;
326}
327
328static const Module *getModuleFromDPI(const DbgMarker *Marker) {
329 const Function *M =
330 Marker->getParent() ? Marker->getParent()->getParent() : nullptr;
331 return M ? M->getParent() : nullptr;
332}
333
334static const Module *getModuleFromDPI(const DbgRecord *DR) {
335 return DR->getMarker() ? getModuleFromDPI(DR->getMarker()) : nullptr;
336}
337
338static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
339 switch (cc) {
340 default: Out << "cc" << cc; break;
341 case CallingConv::Fast: Out << "fastcc"; break;
342 case CallingConv::Cold: Out << "coldcc"; break;
343 case CallingConv::AnyReg: Out << "anyregcc"; break;
344 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
345 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
346 case CallingConv::PreserveNone: Out << "preserve_nonecc"; break;
347 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
348 case CallingConv::GHC: Out << "ghccc"; break;
349 case CallingConv::Tail: Out << "tailcc"; break;
350 case CallingConv::GRAAL: Out << "graalcc"; break;
351 case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
352 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
353 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
354 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
355 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
356 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
357 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
358 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
359 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
360 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
361 case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
363 Out << "aarch64_sve_vector_pcs";
364 break;
366 Out << "aarch64_sme_preservemost_from_x0";
367 break;
369 Out << "aarch64_sme_preservemost_from_x1";
370 break;
372 Out << "aarch64_sme_preservemost_from_x2";
373 break;
374 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
375 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
376 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
377 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
378 case CallingConv::PTX_Device: Out << "ptx_device"; break;
379 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
380 case CallingConv::Win64: Out << "win64cc"; break;
381 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
382 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
383 case CallingConv::Swift: Out << "swiftcc"; break;
384 case CallingConv::SwiftTail: Out << "swifttailcc"; break;
385 case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
387 Out << "hhvmcc";
388 break;
390 Out << "hhvm_ccc";
391 break;
392 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
393 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
394 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
395 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
396 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
397 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
398 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
400 Out << "amdgpu_cs_chain";
401 break;
403 Out << "amdgpu_cs_chain_preserve";
404 break;
405 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
406 case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;
408 Out << "amdgpu_gfx_whole_wave";
409 break;
410 case CallingConv::M68k_RTD: Out << "m68k_rtdcc"; break;
412 Out << "riscv_vector_cc";
413 break;
414#define CC_VLS_CASE(ABI_VLEN) \
415 case CallingConv::RISCV_VLSCall_##ABI_VLEN: \
416 Out << "riscv_vls_cc(" #ABI_VLEN ")"; \
417 break;
418 CC_VLS_CASE(32)
419 CC_VLS_CASE(64)
420 CC_VLS_CASE(128)
421 CC_VLS_CASE(256)
422 CC_VLS_CASE(512)
423 CC_VLS_CASE(1024)
424 CC_VLS_CASE(2048)
425 CC_VLS_CASE(4096)
426 CC_VLS_CASE(8192)
427 CC_VLS_CASE(16384)
428 CC_VLS_CASE(32768)
429 CC_VLS_CASE(65536)
430#undef CC_VLS_CASE
431 }
432}
433
441
443 assert(!Name.empty() && "Cannot get empty name!");
444
445 // Scan the name to see if it needs quotes first.
446 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
447 if (!NeedsQuotes) {
448 for (unsigned char C : Name) {
449 // By making this unsigned, the value passed in to isalnum will always be
450 // in the range 0-255. This is important when building with MSVC because
451 // its implementation will assert. This situation can arise when dealing
452 // with UTF-8 multibyte characters.
453 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
454 NeedsQuotes = true;
455 break;
456 }
457 }
458 }
459
460 // If we didn't need any quotes, just write out the name in one blast.
461 if (!NeedsQuotes) {
462 OS << Name;
463 return;
464 }
465
466 // Okay, we need quotes. Output the quotes and escape any scary characters as
467 // needed.
468 OS << '"';
469 printEscapedString(Name, OS);
470 OS << '"';
471}
472
473/// Turn the specified name into an 'LLVM name', which is either prefixed with %
474/// (if the string only contains simple characters) or is surrounded with ""'s
475/// (if it has special chars in it). Print it out.
477 switch (Prefix) {
478 case NoPrefix:
479 break;
480 case GlobalPrefix:
481 OS << '@';
482 break;
483 case ComdatPrefix:
484 OS << '$';
485 break;
486 case LabelPrefix:
487 break;
488 case LocalPrefix:
489 OS << '%';
490 break;
491 }
493}
494
495/// Turn the specified name into an 'LLVM name', which is either prefixed with %
496/// (if the string only contains simple characters) or is surrounded with ""'s
497/// (if it has special chars in it). Print it out.
498static void PrintLLVMName(raw_ostream &OS, const Value *V) {
499 PrintLLVMName(OS, V->getName(),
500 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
501}
502
503static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
504 Out << ", <";
505 if (isa<ScalableVectorType>(Ty))
506 Out << "vscale x ";
507 Out << Mask.size() << " x i32> ";
508 bool FirstElt = true;
509 if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
510 Out << "zeroinitializer";
511 } else if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
512 Out << "poison";
513 } else {
514 Out << "<";
515 for (int Elt : Mask) {
516 if (FirstElt)
517 FirstElt = false;
518 else
519 Out << ", ";
520 Out << "i32 ";
521 if (Elt == PoisonMaskElem)
522 Out << "poison";
523 else
524 Out << Elt;
525 }
526 Out << ">";
527 }
528}
529
530namespace {
531
532class TypePrinting {
533public:
534 TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
535
536 TypePrinting(const TypePrinting &) = delete;
537 TypePrinting &operator=(const TypePrinting &) = delete;
538
539 /// The named types that are used by the current module.
540 TypeFinder &getNamedTypes();
541
542 /// The numbered types, number to type mapping.
543 std::vector<StructType *> &getNumberedTypes();
544
545 bool empty();
546
547 void print(Type *Ty, raw_ostream &OS);
548
549 void printStructBody(StructType *Ty, raw_ostream &OS);
550
551private:
552 void incorporateTypes();
553
554 /// A module to process lazily when needed. Set to nullptr as soon as used.
555 const Module *DeferredM;
556
557 TypeFinder NamedTypes;
558
559 // The numbered types, along with their value.
561
562 std::vector<StructType *> NumberedTypes;
563};
564
565} // end anonymous namespace
566
567TypeFinder &TypePrinting::getNamedTypes() {
568 incorporateTypes();
569 return NamedTypes;
570}
571
572std::vector<StructType *> &TypePrinting::getNumberedTypes() {
573 incorporateTypes();
574
575 // We know all the numbers that each type is used and we know that it is a
576 // dense assignment. Convert the map to an index table, if it's not done
577 // already (judging from the sizes):
578 if (NumberedTypes.size() == Type2Number.size())
579 return NumberedTypes;
580
581 NumberedTypes.resize(Type2Number.size());
582 for (const auto &P : Type2Number) {
583 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
584 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
585 NumberedTypes[P.second] = P.first;
586 }
587 return NumberedTypes;
588}
589
590bool TypePrinting::empty() {
591 incorporateTypes();
592 return NamedTypes.empty() && Type2Number.empty();
593}
594
595void TypePrinting::incorporateTypes() {
596 if (!DeferredM)
597 return;
598
599 NamedTypes.run(*DeferredM, false);
600 DeferredM = nullptr;
601
602 // The list of struct types we got back includes all the struct types, split
603 // the unnamed ones out to a numbering and remove the anonymous structs.
604 unsigned NextNumber = 0;
605
606 std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
607 for (StructType *STy : NamedTypes) {
608 // Ignore anonymous types.
609 if (STy->isLiteral())
610 continue;
611
612 if (STy->getName().empty())
613 Type2Number[STy] = NextNumber++;
614 else
615 *NextToUse++ = STy;
616 }
617
618 NamedTypes.erase(NextToUse, NamedTypes.end());
619}
620
621/// Write the specified type to the specified raw_ostream, making use of type
622/// names or up references to shorten the type name where possible.
623void TypePrinting::print(Type *Ty, raw_ostream &OS) {
624 switch (Ty->getTypeID()) {
625 case Type::VoidTyID: OS << "void"; return;
626 case Type::HalfTyID: OS << "half"; return;
627 case Type::BFloatTyID: OS << "bfloat"; return;
628 case Type::FloatTyID: OS << "float"; return;
629 case Type::DoubleTyID: OS << "double"; return;
630 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
631 case Type::FP128TyID: OS << "fp128"; return;
632 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
633 case Type::LabelTyID: OS << "label"; return;
635 OS << "metadata";
636 return;
637 case Type::X86_AMXTyID: OS << "x86_amx"; return;
638 case Type::TokenTyID: OS << "token"; return;
640 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
641 return;
642
643 case Type::FunctionTyID: {
644 FunctionType *FTy = cast<FunctionType>(Ty);
645 print(FTy->getReturnType(), OS);
646 OS << " (";
647 ListSeparator LS;
648 for (Type *Ty : FTy->params()) {
649 OS << LS;
650 print(Ty, OS);
651 }
652 if (FTy->isVarArg())
653 OS << LS << "...";
654 OS << ')';
655 return;
656 }
657 case Type::StructTyID: {
658 StructType *STy = cast<StructType>(Ty);
659
660 if (STy->isLiteral())
661 return printStructBody(STy, OS);
662
663 if (!STy->getName().empty())
664 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
665
666 incorporateTypes();
667 const auto I = Type2Number.find(STy);
668 if (I != Type2Number.end())
669 OS << '%' << I->second;
670 else // Not enumerated, print the hex address.
671 OS << "%\"type " << STy << '\"';
672 return;
673 }
674 case Type::PointerTyID: {
675 PointerType *PTy = cast<PointerType>(Ty);
676 OS << "ptr";
677 if (unsigned AddressSpace = PTy->getAddressSpace())
678 OS << " addrspace(" << AddressSpace << ')';
679 return;
680 }
681 case Type::ArrayTyID: {
682 ArrayType *ATy = cast<ArrayType>(Ty);
683 OS << '[' << ATy->getNumElements() << " x ";
684 print(ATy->getElementType(), OS);
685 OS << ']';
686 return;
687 }
690 VectorType *PTy = cast<VectorType>(Ty);
691 ElementCount EC = PTy->getElementCount();
692 OS << "<";
693 if (EC.isScalable())
694 OS << "vscale x ";
695 OS << EC.getKnownMinValue() << " x ";
696 print(PTy->getElementType(), OS);
697 OS << '>';
698 return;
699 }
701 TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
702 OS << "typedptr(" << *TPTy->getElementType() << ", "
703 << TPTy->getAddressSpace() << ")";
704 return;
705 }
707 TargetExtType *TETy = cast<TargetExtType>(Ty);
708 OS << "target(\"";
709 printEscapedString(Ty->getTargetExtName(), OS);
710 OS << "\"";
711 for (Type *Inner : TETy->type_params()) {
712 OS << ", ";
713 Inner->print(OS, /*IsForDebug=*/false, /*NoDetails=*/true);
714 }
715 for (unsigned IntParam : TETy->int_params())
716 OS << ", " << IntParam;
717 OS << ")";
718 return;
719 }
720 llvm_unreachable("Invalid TypeID");
721}
722
723void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
724 if (STy->isOpaque()) {
725 OS << "opaque";
726 return;
727 }
728
729 if (STy->isPacked())
730 OS << '<';
731
732 if (STy->getNumElements() == 0) {
733 OS << "{}";
734 } else {
735 OS << "{ ";
736 ListSeparator LS;
737 for (Type *Ty : STy->elements()) {
738 OS << LS;
739 print(Ty, OS);
740 }
741
742 OS << " }";
743 }
744 if (STy->isPacked())
745 OS << '>';
746}
747
749
750namespace llvm {
751
752//===----------------------------------------------------------------------===//
753// SlotTracker Class: Enumerate slot numbers for unnamed values
754//===----------------------------------------------------------------------===//
755/// This class provides computation of slot numbers for LLVM Assembly writing.
756///
758public:
759 /// ValueMap - A mapping of Values to slot numbers.
761
762private:
763 /// TheModule - The module for which we are holding slot numbers.
764 const Module* TheModule;
765
766 /// TheFunction - The function for which we are holding slot numbers.
767 const Function* TheFunction = nullptr;
768 bool FunctionProcessed = false;
769 bool ShouldInitializeAllMetadata;
770
771 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
772 ProcessModuleHookFn;
773 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
774 ProcessFunctionHookFn;
775
776 /// The summary index for which we are holding slot numbers.
777 const ModuleSummaryIndex *TheIndex = nullptr;
778
779 /// mMap - The slot map for the module level data.
780 ValueMap mMap;
781 unsigned mNext = 0;
782
783 /// fMap - The slot map for the function level data.
784 ValueMap fMap;
785 unsigned fNext = 0;
786
787 /// mdnMap - Map for MDNodes.
789 unsigned mdnNext = 0;
790
791 /// asMap - The slot map for attribute sets.
793 unsigned asNext = 0;
794
795 /// ModulePathMap - The slot map for Module paths used in the summary index.
796 StringMap<unsigned> ModulePathMap;
797 unsigned ModulePathNext = 0;
798
799 /// GUIDMap - The slot map for GUIDs used in the summary index.
801 unsigned GUIDNext = 0;
802
803 /// TypeIdMap - The slot map for type ids used in the summary index.
804 StringMap<unsigned> TypeIdMap;
805 unsigned TypeIdNext = 0;
806
807 /// TypeIdCompatibleVtableMap - The slot map for type compatible vtable ids
808 /// used in the summary index.
809 StringMap<unsigned> TypeIdCompatibleVtableMap;
810 unsigned TypeIdCompatibleVtableNext = 0;
811
812public:
813 /// Construct from a module.
814 ///
815 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
816 /// functions, giving correct numbering for metadata referenced only from
817 /// within a function (even if no functions have been initialized).
818 explicit SlotTracker(const Module *M,
819 bool ShouldInitializeAllMetadata = false);
820
821 /// Construct from a function, starting out in incorp state.
822 ///
823 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
824 /// functions, giving correct numbering for metadata referenced only from
825 /// within a function (even if no functions have been initialized).
826 explicit SlotTracker(const Function *F,
827 bool ShouldInitializeAllMetadata = false);
828
829 /// Construct from a module summary index.
830 explicit SlotTracker(const ModuleSummaryIndex *Index);
831
832 SlotTracker(const SlotTracker &) = delete;
834
835 ~SlotTracker() = default;
836
837 void setProcessHook(
838 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
839 void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
840 const Function *, bool)>);
841
842 unsigned getNextMetadataSlot() override { return mdnNext; }
843
844 void createMetadataSlot(const MDNode *N) override;
845
846 /// Return the slot number of the specified value in it's type
847 /// plane. If something is not in the SlotTracker, return -1.
848 int getLocalSlot(const Value *V);
849 int getGlobalSlot(const GlobalValue *V);
850 int getMetadataSlot(const MDNode *N) override;
854 int getTypeIdSlot(StringRef Id);
856
857 /// If you'd like to deal with a function instead of just a module, use
858 /// this method to get its data into the SlotTracker.
860 TheFunction = F;
861 FunctionProcessed = false;
862 }
863
864 const Function *getFunction() const { return TheFunction; }
865
866 /// After calling incorporateFunction, use this method to remove the
867 /// most recently incorporated function from the SlotTracker. This
868 /// will reset the state of the machine back to just the module contents.
869 void purgeFunction();
870
871 /// MDNode map iterators.
873
874 mdn_iterator mdn_begin() { return mdnMap.begin(); }
875 mdn_iterator mdn_end() { return mdnMap.end(); }
876 unsigned mdn_size() const { return mdnMap.size(); }
877 bool mdn_empty() const { return mdnMap.empty(); }
878
879 /// AttributeSet map iterators.
881
882 as_iterator as_begin() { return asMap.begin(); }
883 as_iterator as_end() { return asMap.end(); }
884 unsigned as_size() const { return asMap.size(); }
885 bool as_empty() const { return asMap.empty(); }
886
887 /// GUID map iterators.
889
890 /// These functions do the actual initialization.
891 inline void initializeIfNeeded();
893
894 // Implementation Details
895private:
896 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
897 void CreateModuleSlot(const GlobalValue *V);
898
899 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
900 void CreateMetadataSlot(const MDNode *N);
901
902 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
903 void CreateFunctionSlot(const Value *V);
904
905 /// Insert the specified AttributeSet into the slot table.
906 void CreateAttributeSetSlot(AttributeSet AS);
907
908 inline void CreateModulePathSlot(StringRef Path);
909 void CreateGUIDSlot(GlobalValue::GUID GUID);
910 void CreateTypeIdSlot(StringRef Id);
911 void CreateTypeIdCompatibleVtableSlot(StringRef Id);
912
913 /// Add all of the module level global variables (and their initializers)
914 /// and function declarations, but not the contents of those functions.
915 void processModule();
916 // Returns number of allocated slots
917 int processIndex();
918
919 /// Add all of the functions arguments, basic blocks, and instructions.
920 void processFunction();
921
922 /// Add the metadata directly attached to a GlobalObject.
923 void processGlobalObjectMetadata(const GlobalObject &GO);
924
925 /// Add all of the metadata from a function.
926 void processFunctionMetadata(const Function &F);
927
928 /// Add all of the metadata from an instruction.
929 void processInstructionMetadata(const Instruction &I);
930
931 /// Add all of the metadata from a DbgRecord.
932 void processDbgRecordMetadata(const DbgRecord &DVR);
933};
934
935} // end namespace llvm
936
938 const Function *F)
939 : M(M), F(F), Machine(&Machine) {}
940
942 bool ShouldInitializeAllMetadata)
943 : ShouldCreateStorage(M),
944 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
945
947
949 if (!ShouldCreateStorage)
950 return Machine;
951
952 ShouldCreateStorage = false;
953 MachineStorage =
954 std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
955 Machine = MachineStorage.get();
956 if (ProcessModuleHookFn)
957 Machine->setProcessHook(ProcessModuleHookFn);
958 if (ProcessFunctionHookFn)
959 Machine->setProcessHook(ProcessFunctionHookFn);
960 return Machine;
961}
962
964 // Using getMachine() may lazily create the slot tracker.
965 if (!getMachine())
966 return;
967
968 // Nothing to do if this is the right function already.
969 if (this->F == &F)
970 return;
971 if (this->F)
972 Machine->purgeFunction();
973 Machine->incorporateFunction(&F);
974 this->F = &F;
975}
976
978 assert(F && "No function incorporated");
979 return Machine->getLocalSlot(V);
980}
981
983 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
984 Fn) {
985 ProcessModuleHookFn = Fn;
986}
987
989 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
990 Fn) {
991 ProcessFunctionHookFn = Fn;
992}
993
995 if (const Argument *FA = dyn_cast<Argument>(V))
996 return new SlotTracker(FA->getParent());
997
998 if (const Instruction *I = dyn_cast<Instruction>(V))
999 if (I->getParent())
1000 return new SlotTracker(I->getParent()->getParent());
1001
1002 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
1003 return new SlotTracker(BB->getParent());
1004
1005 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1006 return new SlotTracker(GV->getParent());
1007
1008 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
1009 return new SlotTracker(GA->getParent());
1010
1011 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
1012 return new SlotTracker(GIF->getParent());
1013
1014 if (const Function *Func = dyn_cast<Function>(V))
1015 return new SlotTracker(Func);
1016
1017 return nullptr;
1018}
1019
1020#if 0
1021#define ST_DEBUG(X) dbgs() << X
1022#else
1023#define ST_DEBUG(X)
1024#endif
1025
1026// Module level constructor. Causes the contents of the Module (sans functions)
1027// to be added to the slot table.
1028SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
1029 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
1030
1031// Function level constructor. Causes the contents of the Module and the one
1032// function provided to be added to the slot table.
1033SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
1034 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
1035 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
1036
1038 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
1039
1041 if (TheModule) {
1042 processModule();
1043 TheModule = nullptr; ///< Prevent re-processing next time we're called.
1044 }
1045
1046 if (TheFunction && !FunctionProcessed)
1047 processFunction();
1048}
1049
1051 if (!TheIndex)
1052 return 0;
1053 int NumSlots = processIndex();
1054 TheIndex = nullptr; ///< Prevent re-processing next time we're called.
1055 return NumSlots;
1056}
1057
1058// Iterate through all the global variables, functions, and global
1059// variable initializers and create slots for them.
1060void SlotTracker::processModule() {
1061 ST_DEBUG("begin processModule!\n");
1062
1063 // Add all of the unnamed global variables to the value table.
1064 for (const GlobalVariable &Var : TheModule->globals()) {
1065 if (!Var.hasName())
1066 CreateModuleSlot(&Var);
1067 processGlobalObjectMetadata(Var);
1068 auto Attrs = Var.getAttributes();
1069 if (Attrs.hasAttributes())
1070 CreateAttributeSetSlot(Attrs);
1071 }
1072
1073 for (const GlobalAlias &A : TheModule->aliases()) {
1074 if (!A.hasName())
1075 CreateModuleSlot(&A);
1076 }
1077
1078 for (const GlobalIFunc &I : TheModule->ifuncs()) {
1079 if (!I.hasName())
1080 CreateModuleSlot(&I);
1081 }
1082
1083 // Add metadata used by named metadata.
1084 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
1085 for (const MDNode *N : NMD.operands())
1086 CreateMetadataSlot(N);
1087 }
1088
1089 for (const Function &F : *TheModule) {
1090 if (!F.hasName())
1091 // Add all the unnamed functions to the table.
1092 CreateModuleSlot(&F);
1093
1094 if (ShouldInitializeAllMetadata)
1095 processFunctionMetadata(F);
1096
1097 // Add all the function attributes to the table.
1098 // FIXME: Add attributes of other objects?
1099 AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
1100 if (FnAttrs.hasAttributes())
1101 CreateAttributeSetSlot(FnAttrs);
1102 }
1103
1104 if (ProcessModuleHookFn)
1105 ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
1106
1107 ST_DEBUG("end processModule!\n");
1108}
1109
1110// Process the arguments, basic blocks, and instructions of a function.
1111void SlotTracker::processFunction() {
1112 ST_DEBUG("begin processFunction!\n");
1113 fNext = 0;
1114
1115 // Process function metadata if it wasn't hit at the module-level.
1116 if (!ShouldInitializeAllMetadata)
1117 processFunctionMetadata(*TheFunction);
1118
1119 // Add all the function arguments with no names.
1120 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1121 AE = TheFunction->arg_end(); AI != AE; ++AI)
1122 if (!AI->hasName())
1123 CreateFunctionSlot(&*AI);
1124
1125 ST_DEBUG("Inserting Instructions:\n");
1126
1127 // Add all of the basic blocks and instructions with no names.
1128 for (auto &BB : *TheFunction) {
1129 if (!BB.hasName())
1130 CreateFunctionSlot(&BB);
1131
1132 for (auto &I : BB) {
1133 if (!I.getType()->isVoidTy() && !I.hasName())
1134 CreateFunctionSlot(&I);
1135
1136 // We allow direct calls to any llvm.foo function here, because the
1137 // target may not be linked into the optimizer.
1138 if (const auto *Call = dyn_cast<CallBase>(&I)) {
1139 // Add all the call attributes to the table.
1140 AttributeSet Attrs = Call->getAttributes().getFnAttrs();
1141 if (Attrs.hasAttributes())
1142 CreateAttributeSetSlot(Attrs);
1143 }
1144 }
1145 }
1146
1147 if (ProcessFunctionHookFn)
1148 ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
1149
1150 FunctionProcessed = true;
1151
1152 ST_DEBUG("end processFunction!\n");
1153}
1154
1155// Iterate through all the GUID in the index and create slots for them.
1156int SlotTracker::processIndex() {
1157 ST_DEBUG("begin processIndex!\n");
1158 assert(TheIndex);
1159
1160 // The first block of slots are just the module ids, which start at 0 and are
1161 // assigned consecutively. Since the StringMap iteration order isn't
1162 // guaranteed, order by path string before assigning slots.
1163 std::vector<StringRef> ModulePaths;
1164 for (auto &[ModPath, _] : TheIndex->modulePaths())
1165 ModulePaths.push_back(ModPath);
1166 llvm::sort(ModulePaths);
1167 for (auto &ModPath : ModulePaths)
1168 CreateModulePathSlot(ModPath);
1169
1170 // Start numbering the GUIDs after the module ids.
1171 GUIDNext = ModulePathNext;
1172
1173 for (auto &GlobalList : *TheIndex)
1174 CreateGUIDSlot(GlobalList.first);
1175
1176 // Start numbering the TypeIdCompatibleVtables after the GUIDs.
1177 TypeIdCompatibleVtableNext = GUIDNext;
1178 for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1179 CreateTypeIdCompatibleVtableSlot(TId.first);
1180
1181 // Start numbering the TypeIds after the TypeIdCompatibleVtables.
1182 TypeIdNext = TypeIdCompatibleVtableNext;
1183 for (const auto &TID : TheIndex->typeIds())
1184 CreateTypeIdSlot(TID.second.first);
1185
1186 ST_DEBUG("end processIndex!\n");
1187 return TypeIdNext;
1188}
1189
1190void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1192 GO.getAllMetadata(MDs);
1193 for (auto &MD : MDs)
1194 CreateMetadataSlot(MD.second);
1195}
1196
1197void SlotTracker::processFunctionMetadata(const Function &F) {
1198 processGlobalObjectMetadata(F);
1199 for (auto &BB : F) {
1200 for (auto &I : BB) {
1201 for (const DbgRecord &DR : I.getDbgRecordRange())
1202 processDbgRecordMetadata(DR);
1203 processInstructionMetadata(I);
1204 }
1205 }
1206}
1207
1208void SlotTracker::processDbgRecordMetadata(const DbgRecord &DR) {
1209 // Tolerate null metadata pointers: it's a completely illegal debug record,
1210 // but we can have faulty metadata from debug-intrinsic days being
1211 // autoupgraded into debug records. This gets caught by the verifier, which
1212 // then will print the faulty IR, hitting this code path.
1213 if (const DbgVariableRecord *DVR = dyn_cast<const DbgVariableRecord>(&DR)) {
1214 // Process metadata used by DbgRecords; we only specifically care about the
1215 // DILocalVariable, DILocation, and DIAssignID fields, as the Value and
1216 // Expression fields should only be printed inline and so do not use a slot.
1217 // Note: The above doesn't apply for empty-metadata operands.
1218 if (auto *Empty = dyn_cast_if_present<MDNode>(DVR->getRawLocation()))
1219 CreateMetadataSlot(Empty);
1220 if (DVR->getRawVariable())
1221 CreateMetadataSlot(DVR->getRawVariable());
1222 if (DVR->isDbgAssign()) {
1223 if (auto *AssignID = DVR->getRawAssignID())
1224 CreateMetadataSlot(cast<MDNode>(AssignID));
1225 if (auto *Empty = dyn_cast_if_present<MDNode>(DVR->getRawAddress()))
1226 CreateMetadataSlot(Empty);
1227 }
1228 } else if (const DbgLabelRecord *DLR = dyn_cast<const DbgLabelRecord>(&DR)) {
1229 CreateMetadataSlot(DLR->getRawLabel());
1230 } else {
1231 llvm_unreachable("unsupported DbgRecord kind");
1232 }
1233 if (DR.getDebugLoc())
1234 CreateMetadataSlot(DR.getDebugLoc().getAsMDNode());
1235}
1236
1237void SlotTracker::processInstructionMetadata(const Instruction &I) {
1238 // Process metadata used directly by intrinsics.
1239 if (const CallInst *CI = dyn_cast<CallInst>(&I))
1240 if (Function *F = CI->getCalledFunction())
1241 if (F->isIntrinsic())
1242 for (auto &Op : I.operands())
1243 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1244 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1245 CreateMetadataSlot(N);
1246
1247 // Process metadata attached to this instruction.
1249 I.getAllMetadata(MDs);
1250 for (auto &MD : MDs)
1251 CreateMetadataSlot(MD.second);
1252}
1253
1254/// Clean up after incorporating a function. This is the only way to get out of
1255/// the function incorporation state that affects get*Slot/Create*Slot. Function
1256/// incorporation state is indicated by TheFunction != 0.
1258 ST_DEBUG("begin purgeFunction!\n");
1259 fMap.clear(); // Simply discard the function level map
1260 TheFunction = nullptr;
1261 FunctionProcessed = false;
1262 ST_DEBUG("end purgeFunction!\n");
1263}
1264
1265/// getGlobalSlot - Get the slot number of a global value.
1267 // Check for uninitialized state and do lazy initialization.
1269
1270 // Find the value in the module map
1271 ValueMap::iterator MI = mMap.find(V);
1272 return MI == mMap.end() ? -1 : (int)MI->second;
1273}
1274
1276 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
1277 Fn) {
1278 ProcessModuleHookFn = Fn;
1279}
1280
1282 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
1283 Fn) {
1284 ProcessFunctionHookFn = Fn;
1285}
1286
1287/// getMetadataSlot - Get the slot number of a MDNode.
1288void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1289
1290/// getMetadataSlot - Get the slot number of a MDNode.
1292 // Check for uninitialized state and do lazy initialization.
1294
1295 // Find the MDNode in the module map
1296 mdn_iterator MI = mdnMap.find(N);
1297 return MI == mdnMap.end() ? -1 : (int)MI->second;
1298}
1299
1300/// getLocalSlot - Get the slot number for a value that is local to a function.
1302 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1303
1304 // Check for uninitialized state and do lazy initialization.
1306
1307 ValueMap::iterator FI = fMap.find(V);
1308 return FI == fMap.end() ? -1 : (int)FI->second;
1309}
1310
1312 // Check for uninitialized state and do lazy initialization.
1314
1315 // Find the AttributeSet in the module map.
1316 as_iterator AI = asMap.find(AS);
1317 return AI == asMap.end() ? -1 : (int)AI->second;
1318}
1319
1321 // Check for uninitialized state and do lazy initialization.
1323
1324 // Find the Module path in the map
1325 auto I = ModulePathMap.find(Path);
1326 return I == ModulePathMap.end() ? -1 : (int)I->second;
1327}
1328
1330 // Check for uninitialized state and do lazy initialization.
1332
1333 // Find the GUID in the map
1334 guid_iterator I = GUIDMap.find(GUID);
1335 return I == GUIDMap.end() ? -1 : (int)I->second;
1336}
1337
1339 // Check for uninitialized state and do lazy initialization.
1341
1342 // Find the TypeId string in the map
1343 auto I = TypeIdMap.find(Id);
1344 return I == TypeIdMap.end() ? -1 : (int)I->second;
1345}
1346
1348 // Check for uninitialized state and do lazy initialization.
1350
1351 // Find the TypeIdCompatibleVtable string in the map
1352 auto I = TypeIdCompatibleVtableMap.find(Id);
1353 return I == TypeIdCompatibleVtableMap.end() ? -1 : (int)I->second;
1354}
1355
1356/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1357void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1358 assert(V && "Can't insert a null Value into SlotTracker!");
1359 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1360 assert(!V->hasName() && "Doesn't need a slot!");
1361
1362 unsigned DestSlot = mNext++;
1363 mMap[V] = DestSlot;
1364
1365 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1366 DestSlot << " [");
1367 // G = Global, F = Function, A = Alias, I = IFunc, o = other
1368 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1369 (isa<Function>(V) ? 'F' :
1370 (isa<GlobalAlias>(V) ? 'A' :
1371 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1372}
1373
1374/// CreateSlot - Create a new slot for the specified value if it has no name.
1375void SlotTracker::CreateFunctionSlot(const Value *V) {
1376 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1377
1378 unsigned DestSlot = fNext++;
1379 fMap[V] = DestSlot;
1380
1381 // G = Global, F = Function, o = other
1382 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1383 DestSlot << " [o]\n");
1384}
1385
1386/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1387void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1388 assert(N && "Can't insert a null Value into SlotTracker!");
1389
1390 // Don't make slots for DIExpressions. We just print them inline everywhere.
1391 if (isa<DIExpression>(N))
1392 return;
1393
1394 unsigned DestSlot = mdnNext;
1395 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1396 return;
1397 ++mdnNext;
1398
1399 // Recursively add any MDNodes referenced by operands.
1400 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1401 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1402 CreateMetadataSlot(Op);
1403}
1404
1405void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1406 assert(AS.hasAttributes() && "Doesn't need a slot!");
1407
1408 if (asMap.try_emplace(AS, asNext).second)
1409 ++asNext;
1410}
1411
1412/// Create a new slot for the specified Module
1413void SlotTracker::CreateModulePathSlot(StringRef Path) {
1414 ModulePathMap[Path] = ModulePathNext++;
1415}
1416
1417/// Create a new slot for the specified GUID
1418void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1419 GUIDMap[GUID] = GUIDNext++;
1420}
1421
1422/// Create a new slot for the specified Id
1423void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1424 TypeIdMap[Id] = TypeIdNext++;
1425}
1426
1427/// Create a new slot for the specified Id
1428void SlotTracker::CreateTypeIdCompatibleVtableSlot(StringRef Id) {
1429 TypeIdCompatibleVtableMap[Id] = TypeIdCompatibleVtableNext++;
1430}
1431
1432namespace {
1433/// Common instances used by most of the printer functions.
1434struct AsmWriterContext {
1435 TypePrinting *TypePrinter = nullptr;
1436 SlotTracker *Machine = nullptr;
1437 const Module *Context = nullptr;
1438
1439 AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1440 : TypePrinter(TP), Machine(ST), Context(M) {}
1441
1442 static AsmWriterContext &getEmpty() {
1443 static AsmWriterContext EmptyCtx(nullptr, nullptr);
1444 return EmptyCtx;
1445 }
1446
1447 /// A callback that will be triggered when the underlying printer
1448 /// prints a Metadata as operand.
1449 virtual void onWriteMetadataAsOperand(const Metadata *) {}
1450
1451 virtual ~AsmWriterContext() = default;
1452};
1453} // end anonymous namespace
1454
1455//===----------------------------------------------------------------------===//
1456// AsmWriter Implementation
1457//===----------------------------------------------------------------------===//
1458
1459static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1460 AsmWriterContext &WriterCtx);
1461
1462static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1463 AsmWriterContext &WriterCtx,
1464 bool FromValue = false);
1465
1466static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1467 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1468 Out << FPO->getFastMathFlags();
1469
1470 if (const OverflowingBinaryOperator *OBO =
1471 dyn_cast<OverflowingBinaryOperator>(U)) {
1472 if (OBO->hasNoUnsignedWrap())
1473 Out << " nuw";
1474 if (OBO->hasNoSignedWrap())
1475 Out << " nsw";
1476 } else if (const PossiblyExactOperator *Div =
1477 dyn_cast<PossiblyExactOperator>(U)) {
1478 if (Div->isExact())
1479 Out << " exact";
1480 } else if (const PossiblyDisjointInst *PDI =
1481 dyn_cast<PossiblyDisjointInst>(U)) {
1482 if (PDI->isDisjoint())
1483 Out << " disjoint";
1484 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1485 if (GEP->isInBounds())
1486 Out << " inbounds";
1487 else if (GEP->hasNoUnsignedSignedWrap())
1488 Out << " nusw";
1489 if (GEP->hasNoUnsignedWrap())
1490 Out << " nuw";
1491 if (auto InRange = GEP->getInRange()) {
1492 Out << " inrange(" << InRange->getLower() << ", " << InRange->getUpper()
1493 << ")";
1494 }
1495 } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(U)) {
1496 if (NNI->hasNonNeg())
1497 Out << " nneg";
1498 } else if (const auto *TI = dyn_cast<TruncInst>(U)) {
1499 if (TI->hasNoUnsignedWrap())
1500 Out << " nuw";
1501 if (TI->hasNoSignedWrap())
1502 Out << " nsw";
1503 } else if (const auto *ICmp = dyn_cast<ICmpInst>(U)) {
1504 if (ICmp->hasSameSign())
1505 Out << " samesign";
1506 }
1507}
1508
1509static void WriteAPFloatInternal(raw_ostream &Out, const APFloat &APF) {
1510 if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1511 &APF.getSemantics() == &APFloat::IEEEdouble()) {
1512 // We would like to output the FP constant value in exponential notation,
1513 // but we cannot do this if doing so will lose precision. Check here to
1514 // make sure that we only output it in exponential format if we can parse
1515 // the value back and get the same value.
1516 //
1517 bool ignored;
1518 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1519 bool isInf = APF.isInfinity();
1520 bool isNaN = APF.isNaN();
1521
1522 if (!isInf && !isNaN) {
1523 double Val = APF.convertToDouble();
1524 SmallString<128> StrVal;
1525 APF.toString(StrVal, 6, 0, false);
1526 // Check to make sure that the stringized number is not some string like
1527 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1528 // that the string matches the "[-+]?[0-9]" regex.
1529 //
1530 assert((isDigit(StrVal[0]) ||
1531 ((StrVal[0] == '-' || StrVal[0] == '+') && isDigit(StrVal[1]))) &&
1532 "[-+]?[0-9] regex does not match!");
1533 // Reparse stringized version!
1534 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1535 Out << StrVal;
1536 return;
1537 }
1538 }
1539
1540 // Otherwise we could not reparse it to exactly the same value, so we must
1541 // output the string in hexadecimal format! Note that loading and storing
1542 // floating point types changes the bits of NaNs on some hosts, notably
1543 // x86, so we must not use these types.
1544 static_assert(sizeof(double) == sizeof(uint64_t),
1545 "assuming that double is 64 bits!");
1546 APFloat apf = APF;
1547
1548 // Floats are represented in ASCII IR as double, convert.
1549 // FIXME: We should allow 32-bit hex float and remove this.
1550 if (!isDouble) {
1551 // A signaling NaN is quieted on conversion, so we need to recreate the
1552 // expected value after convert (quiet bit of the payload is clear).
1553 bool IsSNAN = apf.isSignaling();
1555 &ignored);
1556 if (IsSNAN) {
1557 APInt Payload = apf.bitcastToAPInt();
1558 apf =
1560 }
1561 }
1562
1563 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1564 return;
1565 }
1566
1567 // Either half, bfloat or some form of long double.
1568 // These appear as a magic letter identifying the type, then a
1569 // fixed number of hex digits.
1570 Out << "0x";
1571 APInt API = APF.bitcastToAPInt();
1572 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1573 Out << 'K';
1574 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1575 /*Upper=*/true);
1576 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1577 /*Upper=*/true);
1578 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1579 Out << 'L';
1580 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1581 /*Upper=*/true);
1582 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1583 /*Upper=*/true);
1584 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1585 Out << 'M';
1586 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1587 /*Upper=*/true);
1588 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1589 /*Upper=*/true);
1590 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1591 Out << 'H';
1592 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1593 /*Upper=*/true);
1594 } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1595 Out << 'R';
1596 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1597 /*Upper=*/true);
1598 } else
1599 llvm_unreachable("Unsupported floating point type");
1600}
1601
1602static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1603 AsmWriterContext &WriterCtx) {
1604 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1605 Type *Ty = CI->getType();
1606
1607 if (Ty->isVectorTy()) {
1608 Out << "splat (";
1609 WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);
1610 Out << " ";
1611 }
1612
1613 if (Ty->getScalarType()->isIntegerTy(1))
1614 Out << (CI->getZExtValue() ? "true" : "false");
1615 else
1616 Out << CI->getValue();
1617
1618 if (Ty->isVectorTy())
1619 Out << ")";
1620
1621 return;
1622 }
1623
1624 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1625 Type *Ty = CFP->getType();
1626
1627 if (Ty->isVectorTy()) {
1628 Out << "splat (";
1629 WriterCtx.TypePrinter->print(Ty->getScalarType(), Out);
1630 Out << " ";
1631 }
1632
1633 WriteAPFloatInternal(Out, CFP->getValueAPF());
1634
1635 if (Ty->isVectorTy())
1636 Out << ")";
1637
1638 return;
1639 }
1640
1641 if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
1642 Out << "zeroinitializer";
1643 return;
1644 }
1645
1646 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1647 Out << "blockaddress(";
1648 WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
1649 Out << ", ";
1650 WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
1651 Out << ")";
1652 return;
1653 }
1654
1655 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1656 Out << "dso_local_equivalent ";
1657 WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1658 return;
1659 }
1660
1661 if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
1662 Out << "no_cfi ";
1663 WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
1664 return;
1665 }
1666
1667 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(CV)) {
1668 Out << "ptrauth (";
1669
1670 // ptrauth (ptr CST, i32 KEY[, i64 DISC[, ptr ADDRDISC]?]?)
1671 unsigned NumOpsToWrite = 2;
1672 if (!CPA->getOperand(2)->isNullValue())
1673 NumOpsToWrite = 3;
1674 if (!CPA->getOperand(3)->isNullValue())
1675 NumOpsToWrite = 4;
1676
1677 ListSeparator LS;
1678 for (unsigned i = 0, e = NumOpsToWrite; i != e; ++i) {
1679 Out << LS;
1680 WriterCtx.TypePrinter->print(CPA->getOperand(i)->getType(), Out);
1681 Out << ' ';
1682 WriteAsOperandInternal(Out, CPA->getOperand(i), WriterCtx);
1683 }
1684 Out << ')';
1685 return;
1686 }
1687
1688 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1689 Type *ETy = CA->getType()->getElementType();
1690 Out << '[';
1691 WriterCtx.TypePrinter->print(ETy, Out);
1692 Out << ' ';
1693 WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
1694 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1695 Out << ", ";
1696 WriterCtx.TypePrinter->print(ETy, Out);
1697 Out << ' ';
1698 WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
1699 }
1700 Out << ']';
1701 return;
1702 }
1703
1704 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1705 // As a special case, print the array as a string if it is an array of
1706 // i8 with ConstantInt values.
1707 if (CA->isString()) {
1708 Out << "c\"";
1709 printEscapedString(CA->getAsString(), Out);
1710 Out << '"';
1711 return;
1712 }
1713
1714 Type *ETy = CA->getType()->getElementType();
1715 Out << '[';
1716 WriterCtx.TypePrinter->print(ETy, Out);
1717 Out << ' ';
1718 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
1719 for (uint64_t i = 1, e = CA->getNumElements(); i != e; ++i) {
1720 Out << ", ";
1721 WriterCtx.TypePrinter->print(ETy, Out);
1722 Out << ' ';
1723 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
1724 }
1725 Out << ']';
1726 return;
1727 }
1728
1729 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1730 if (CS->getType()->isPacked())
1731 Out << '<';
1732 Out << '{';
1733 unsigned N = CS->getNumOperands();
1734 if (N) {
1735 Out << ' ';
1736 WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
1737 Out << ' ';
1738
1739 WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
1740
1741 for (unsigned i = 1; i < N; i++) {
1742 Out << ", ";
1743 WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
1744 Out << ' ';
1745
1746 WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
1747 }
1748 Out << ' ';
1749 }
1750
1751 Out << '}';
1752 if (CS->getType()->isPacked())
1753 Out << '>';
1754 return;
1755 }
1756
1757 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1758 auto *CVVTy = cast<FixedVectorType>(CV->getType());
1759 Type *ETy = CVVTy->getElementType();
1760
1761 // Use the same shorthand for splat vector (i.e. "splat(Ty val)") as is
1762 // permitted on IR input to reduce the output changes when enabling
1763 // UseConstant{Int,FP}ForFixedLengthSplat.
1764 // TODO: Remove this block when the UseConstant{Int,FP}ForFixedLengthSplat
1765 // options are removed.
1766 if (auto *SplatVal = CV->getSplatValue()) {
1767 if (isa<ConstantInt>(SplatVal) || isa<ConstantFP>(SplatVal)) {
1768 Out << "splat (";
1769 WriterCtx.TypePrinter->print(ETy, Out);
1770 Out << ' ';
1771 WriteAsOperandInternal(Out, SplatVal, WriterCtx);
1772 Out << ')';
1773 return;
1774 }
1775 }
1776
1777 Out << '<';
1778 WriterCtx.TypePrinter->print(ETy, Out);
1779 Out << ' ';
1780 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1781 for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1782 Out << ", ";
1783 WriterCtx.TypePrinter->print(ETy, Out);
1784 Out << ' ';
1785 WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
1786 }
1787 Out << '>';
1788 return;
1789 }
1790
1791 if (isa<ConstantPointerNull>(CV)) {
1792 Out << "null";
1793 return;
1794 }
1795
1796 if (isa<ConstantTokenNone>(CV)) {
1797 Out << "none";
1798 return;
1799 }
1800
1801 if (isa<PoisonValue>(CV)) {
1802 Out << "poison";
1803 return;
1804 }
1805
1806 if (isa<UndefValue>(CV)) {
1807 Out << "undef";
1808 return;
1809 }
1810
1811 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1812 // Use the same shorthand for splat vector (i.e. "splat(Ty val)") as is
1813 // permitted on IR input to reduce the output changes when enabling
1814 // UseConstant{Int,FP}ForScalableSplat.
1815 // TODO: Remove this block when the UseConstant{Int,FP}ForScalableSplat
1816 // options are removed.
1817 if (CE->getOpcode() == Instruction::ShuffleVector) {
1818 if (auto *SplatVal = CE->getSplatValue()) {
1819 if (isa<ConstantInt>(SplatVal) || isa<ConstantFP>(SplatVal)) {
1820 Out << "splat (";
1821 WriterCtx.TypePrinter->print(SplatVal->getType(), Out);
1822 Out << ' ';
1823 WriteAsOperandInternal(Out, SplatVal, WriterCtx);
1824 Out << ')';
1825 return;
1826 }
1827 }
1828 }
1829
1830 Out << CE->getOpcodeName();
1831 WriteOptimizationInfo(Out, CE);
1832 Out << " (";
1833
1834 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1835 WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
1836 Out << ", ";
1837 }
1838
1839 for (User::const_op_iterator OI = CE->op_begin(); OI != CE->op_end();
1840 ++OI) {
1841 WriterCtx.TypePrinter->print((*OI)->getType(), Out);
1842 Out << ' ';
1843 WriteAsOperandInternal(Out, *OI, WriterCtx);
1844 if (OI+1 != CE->op_end())
1845 Out << ", ";
1846 }
1847
1848 if (CE->isCast()) {
1849 Out << " to ";
1850 WriterCtx.TypePrinter->print(CE->getType(), Out);
1851 }
1852
1853 if (CE->getOpcode() == Instruction::ShuffleVector)
1854 PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1855
1856 Out << ')';
1857 return;
1858 }
1859
1860 Out << "<placeholder or erroneous Constant>";
1861}
1862
1863static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1864 AsmWriterContext &WriterCtx) {
1865 Out << "!{";
1866 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1867 const Metadata *MD = Node->getOperand(mi);
1868 if (!MD)
1869 Out << "null";
1870 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1871 Value *V = MDV->getValue();
1872 WriterCtx.TypePrinter->print(V->getType(), Out);
1873 Out << ' ';
1874 WriteAsOperandInternal(Out, V, WriterCtx);
1875 } else {
1876 WriteAsOperandInternal(Out, MD, WriterCtx);
1877 WriterCtx.onWriteMetadataAsOperand(MD);
1878 }
1879 if (mi + 1 != me)
1880 Out << ", ";
1881 }
1882
1883 Out << "}";
1884}
1885
1886namespace {
1887
1888struct FieldSeparator {
1889 bool Skip = true;
1890 const char *Sep;
1891
1892 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1893};
1894
1895raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1896 if (FS.Skip) {
1897 FS.Skip = false;
1898 return OS;
1899 }
1900 return OS << FS.Sep;
1901}
1902
1903struct MDFieldPrinter {
1904 raw_ostream &Out;
1905 FieldSeparator FS;
1906 AsmWriterContext &WriterCtx;
1907
1908 explicit MDFieldPrinter(raw_ostream &Out)
1909 : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1910 MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1911 : Out(Out), WriterCtx(Ctx) {}
1912
1913 void printTag(const DINode *N);
1914 void printMacinfoType(const DIMacroNode *N);
1915 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1916 void printString(StringRef Name, StringRef Value,
1917 bool ShouldSkipEmpty = true);
1918 void printMetadata(StringRef Name, const Metadata *MD,
1919 bool ShouldSkipNull = true);
1920 void printMetadataOrInt(StringRef Name, const Metadata *MD, bool IsUnsigned,
1921 bool ShouldSkipZero = true);
1922 template <class IntTy>
1923 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1924 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1925 bool ShouldSkipZero);
1926 void printBool(StringRef Name, bool Value,
1927 std::optional<bool> Default = std::nullopt);
1928 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1929 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1930 template <class IntTy, class Stringifier>
1931 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1932 bool ShouldSkipZero = true);
1933 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1934 void printNameTableKind(StringRef Name,
1936 void printFixedPointKind(StringRef Name, DIFixedPointType::FixedPointKind V);
1937};
1938
1939} // end anonymous namespace
1940
1941void MDFieldPrinter::printTag(const DINode *N) {
1942 Out << FS << "tag: ";
1943 auto Tag = dwarf::TagString(N->getTag());
1944 if (!Tag.empty())
1945 Out << Tag;
1946 else
1947 Out << N->getTag();
1948}
1949
1950void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1951 Out << FS << "type: ";
1952 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1953 if (!Type.empty())
1954 Out << Type;
1955 else
1956 Out << N->getMacinfoType();
1957}
1958
1959void MDFieldPrinter::printChecksum(
1960 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1961 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1962 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1963}
1964
1965void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1966 bool ShouldSkipEmpty) {
1967 if (ShouldSkipEmpty && Value.empty())
1968 return;
1969
1970 Out << FS << Name << ": \"";
1971 printEscapedString(Value, Out);
1972 Out << "\"";
1973}
1974
1975static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1976 AsmWriterContext &WriterCtx) {
1977 if (!MD) {
1978 Out << "null";
1979 return;
1980 }
1981 WriteAsOperandInternal(Out, MD, WriterCtx);
1982 WriterCtx.onWriteMetadataAsOperand(MD);
1983}
1984
1985void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1986 bool ShouldSkipNull) {
1987 if (ShouldSkipNull && !MD)
1988 return;
1989
1990 Out << FS << Name << ": ";
1991 writeMetadataAsOperand(Out, MD, WriterCtx);
1992}
1993
1994void MDFieldPrinter::printMetadataOrInt(StringRef Name, const Metadata *MD,
1995 bool IsUnsigned, bool ShouldSkipZero) {
1996 if (!MD)
1997 return;
1998
1999 if (auto *CI = dyn_cast<ConstantAsMetadata>(MD)) {
2000 auto *CV = cast<ConstantInt>(CI->getValue());
2001 if (IsUnsigned)
2002 printInt(Name, CV->getZExtValue(), ShouldSkipZero);
2003 else
2004 printInt(Name, CV->getSExtValue(), ShouldSkipZero);
2005 } else
2006 printMetadata(Name, MD);
2007}
2008
2009template <class IntTy>
2010void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
2011 if (ShouldSkipZero && !Int)
2012 return;
2013
2014 Out << FS << Name << ": " << Int;
2015}
2016
2017void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
2018 bool IsUnsigned, bool ShouldSkipZero) {
2019 if (ShouldSkipZero && Int.isZero())
2020 return;
2021
2022 Out << FS << Name << ": ";
2023 Int.print(Out, !IsUnsigned);
2024}
2025
2026void MDFieldPrinter::printBool(StringRef Name, bool Value,
2027 std::optional<bool> Default) {
2028 if (Default && Value == *Default)
2029 return;
2030 Out << FS << Name << ": " << (Value ? "true" : "false");
2031}
2032
2033void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
2034 if (!Flags)
2035 return;
2036
2037 Out << FS << Name << ": ";
2038
2040 auto Extra = DINode::splitFlags(Flags, SplitFlags);
2041
2042 FieldSeparator FlagsFS(" | ");
2043 for (auto F : SplitFlags) {
2044 auto StringF = DINode::getFlagString(F);
2045 assert(!StringF.empty() && "Expected valid flag");
2046 Out << FlagsFS << StringF;
2047 }
2048 if (Extra || SplitFlags.empty())
2049 Out << FlagsFS << Extra;
2050}
2051
2052void MDFieldPrinter::printDISPFlags(StringRef Name,
2054 // Always print this field, because no flags in the IR at all will be
2055 // interpreted as old-style isDefinition: true.
2056 Out << FS << Name << ": ";
2057
2058 if (!Flags) {
2059 Out << 0;
2060 return;
2061 }
2062
2064 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
2065
2066 FieldSeparator FlagsFS(" | ");
2067 for (auto F : SplitFlags) {
2068 auto StringF = DISubprogram::getFlagString(F);
2069 assert(!StringF.empty() && "Expected valid flag");
2070 Out << FlagsFS << StringF;
2071 }
2072 if (Extra || SplitFlags.empty())
2073 Out << FlagsFS << Extra;
2074}
2075
2076void MDFieldPrinter::printEmissionKind(StringRef Name,
2078 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
2079}
2080
2081void MDFieldPrinter::printNameTableKind(StringRef Name,
2084 return;
2085 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
2086}
2087
2088void MDFieldPrinter::printFixedPointKind(StringRef Name,
2090 Out << FS << Name << ": " << DIFixedPointType::fixedPointKindString(V);
2091}
2092
2093template <class IntTy, class Stringifier>
2094void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
2095 Stringifier toString, bool ShouldSkipZero) {
2096 if (ShouldSkipZero && !Value)
2097 return;
2098
2099 Out << FS << Name << ": ";
2100 auto S = toString(Value);
2101 if (!S.empty())
2102 Out << S;
2103 else
2104 Out << Value;
2105}
2106
2108 AsmWriterContext &WriterCtx) {
2109 Out << "!GenericDINode(";
2110 MDFieldPrinter Printer(Out, WriterCtx);
2111 Printer.printTag(N);
2112 Printer.printString("header", N->getHeader());
2113 if (N->getNumDwarfOperands()) {
2114 Out << Printer.FS << "operands: {";
2115 FieldSeparator IFS;
2116 for (auto &I : N->dwarf_operands()) {
2117 Out << IFS;
2118 writeMetadataAsOperand(Out, I, WriterCtx);
2119 }
2120 Out << "}";
2121 }
2122 Out << ")";
2123}
2124
2125static void writeDILocation(raw_ostream &Out, const DILocation *DL,
2126 AsmWriterContext &WriterCtx) {
2127 Out << "!DILocation(";
2128 MDFieldPrinter Printer(Out, WriterCtx);
2129 // Always output the line, since 0 is a relevant and important value for it.
2130 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
2131 Printer.printInt("column", DL->getColumn());
2132 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
2133 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
2134 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
2135 /* Default */ false);
2136 Printer.printInt("atomGroup", DL->getAtomGroup());
2137 Printer.printInt<unsigned>("atomRank", DL->getAtomRank());
2138 Out << ")";
2139}
2140
2141static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
2142 AsmWriterContext &WriterCtx) {
2143 Out << "!DIAssignID()";
2144 MDFieldPrinter Printer(Out, WriterCtx);
2145}
2146
2147static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
2148 AsmWriterContext &WriterCtx) {
2149 Out << "!DISubrange(";
2150 MDFieldPrinter Printer(Out, WriterCtx);
2151
2152 Printer.printMetadataOrInt("count", N->getRawCountNode(),
2153 /* IsUnsigned */ false,
2154 /* ShouldSkipZero */ false);
2155
2156 // A lowerBound of constant 0 should not be skipped, since it is different
2157 // from an unspecified lower bound (= nullptr).
2158 Printer.printMetadataOrInt("lowerBound", N->getRawLowerBound(),
2159 /* IsUnsigned */ false,
2160 /* ShouldSkipZero */ false);
2161 Printer.printMetadataOrInt("upperBound", N->getRawUpperBound(),
2162 /* IsUnsigned */ false,
2163 /* ShouldSkipZero */ false);
2164 Printer.printMetadataOrInt("stride", N->getRawStride(),
2165 /* IsUnsigned */ false,
2166 /* ShouldSkipZero */ false);
2167
2168 Out << ")";
2169}
2170
2172 AsmWriterContext &WriterCtx) {
2173 Out << "!DIGenericSubrange(";
2174 MDFieldPrinter Printer(Out, WriterCtx);
2175
2176 auto GetConstant = [&](Metadata *Bound) -> std::optional<int64_t> {
2177 auto *BE = dyn_cast_or_null<DIExpression>(Bound);
2178 if (!BE)
2179 return std::nullopt;
2180 if (BE->isConstant() &&
2182 *BE->isConstant()) {
2183 return static_cast<int64_t>(BE->getElement(1));
2184 }
2185 return std::nullopt;
2186 };
2187
2188 auto *Count = N->getRawCountNode();
2189 if (auto ConstantCount = GetConstant(Count))
2190 Printer.printInt("count", *ConstantCount,
2191 /* ShouldSkipZero */ false);
2192 else
2193 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
2194
2195 auto *LBound = N->getRawLowerBound();
2196 if (auto ConstantLBound = GetConstant(LBound))
2197 Printer.printInt("lowerBound", *ConstantLBound,
2198 /* ShouldSkipZero */ false);
2199 else
2200 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
2201
2202 auto *UBound = N->getRawUpperBound();
2203 if (auto ConstantUBound = GetConstant(UBound))
2204 Printer.printInt("upperBound", *ConstantUBound,
2205 /* ShouldSkipZero */ false);
2206 else
2207 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
2208
2209 auto *Stride = N->getRawStride();
2210 if (auto ConstantStride = GetConstant(Stride))
2211 Printer.printInt("stride", *ConstantStride,
2212 /* ShouldSkipZero */ false);
2213 else
2214 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
2215
2216 Out << ")";
2217}
2218
2220 AsmWriterContext &) {
2221 Out << "!DIEnumerator(";
2222 MDFieldPrinter Printer(Out);
2223 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
2224 Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
2225 /*ShouldSkipZero=*/false);
2226 if (N->isUnsigned())
2227 Printer.printBool("isUnsigned", true);
2228 Out << ")";
2229}
2230
2232 AsmWriterContext &WriterCtx) {
2233 Out << "!DIBasicType(";
2234 MDFieldPrinter Printer(Out, WriterCtx);
2235 if (N->getTag() != dwarf::DW_TAG_base_type)
2236 Printer.printTag(N);
2237 Printer.printString("name", N->getName());
2238 Printer.printMetadataOrInt("size", N->getRawSizeInBits(), true);
2239 Printer.printInt("align", N->getAlignInBits());
2240 Printer.printDwarfEnum("encoding", N->getEncoding(),
2242 Printer.printInt("num_extra_inhabitants", N->getNumExtraInhabitants());
2243 Printer.printDIFlags("flags", N->getFlags());
2244 Out << ")";
2245}
2246
2248 AsmWriterContext &WriterCtx) {
2249 Out << "!DIFixedPointType(";
2250 MDFieldPrinter Printer(Out, WriterCtx);
2251 if (N->getTag() != dwarf::DW_TAG_base_type)
2252 Printer.printTag(N);
2253 Printer.printString("name", N->getName());
2254 Printer.printMetadataOrInt("size", N->getRawSizeInBits(), true);
2255 Printer.printInt("align", N->getAlignInBits());
2256 Printer.printDwarfEnum("encoding", N->getEncoding(),
2258 Printer.printDIFlags("flags", N->getFlags());
2259 Printer.printFixedPointKind("kind", N->getKind());
2260 if (N->isRational()) {
2261 bool IsUnsigned = !N->isSigned();
2262 Printer.printAPInt("numerator", N->getNumerator(), IsUnsigned, false);
2263 Printer.printAPInt("denominator", N->getDenominator(), IsUnsigned, false);
2264 } else {
2265 Printer.printInt("factor", N->getFactor());
2266 }
2267 Out << ")";
2268}
2269
2271 AsmWriterContext &WriterCtx) {
2272 Out << "!DIStringType(";
2273 MDFieldPrinter Printer(Out, WriterCtx);
2274 if (N->getTag() != dwarf::DW_TAG_string_type)
2275 Printer.printTag(N);
2276 Printer.printString("name", N->getName());
2277 Printer.printMetadata("stringLength", N->getRawStringLength());
2278 Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2279 Printer.printMetadata("stringLocationExpression",
2280 N->getRawStringLocationExp());
2281 Printer.printMetadataOrInt("size", N->getRawSizeInBits(), true);
2282 Printer.printInt("align", N->getAlignInBits());
2283 Printer.printDwarfEnum("encoding", N->getEncoding(),
2285 Out << ")";
2286}
2287
2289 AsmWriterContext &WriterCtx) {
2290 Out << "!DIDerivedType(";
2291 MDFieldPrinter Printer(Out, WriterCtx);
2292 Printer.printTag(N);
2293 Printer.printString("name", N->getName());
2294 Printer.printMetadata("scope", N->getRawScope());
2295 Printer.printMetadata("file", N->getRawFile());
2296 Printer.printInt("line", N->getLine());
2297 Printer.printMetadata("baseType", N->getRawBaseType(),
2298 /* ShouldSkipNull */ false);
2299 Printer.printMetadataOrInt("size", N->getRawSizeInBits(), true);
2300 Printer.printInt("align", N->getAlignInBits());
2301 Printer.printMetadataOrInt("offset", N->getRawOffsetInBits(), true);
2302 Printer.printDIFlags("flags", N->getFlags());
2303 Printer.printMetadata("extraData", N->getRawExtraData());
2304 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2305 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2306 /* ShouldSkipZero */ false);
2307 Printer.printMetadata("annotations", N->getRawAnnotations());
2308 if (auto PtrAuthData = N->getPtrAuthData()) {
2309 Printer.printInt("ptrAuthKey", PtrAuthData->key());
2310 Printer.printBool("ptrAuthIsAddressDiscriminated",
2311 PtrAuthData->isAddressDiscriminated());
2312 Printer.printInt("ptrAuthExtraDiscriminator",
2313 PtrAuthData->extraDiscriminator());
2314 Printer.printBool("ptrAuthIsaPointer", PtrAuthData->isaPointer());
2315 Printer.printBool("ptrAuthAuthenticatesNullValues",
2316 PtrAuthData->authenticatesNullValues());
2317 }
2318 Out << ")";
2319}
2320
2322 AsmWriterContext &WriterCtx) {
2323 Out << "!DISubrangeType(";
2324 MDFieldPrinter Printer(Out, WriterCtx);
2325 Printer.printString("name", N->getName());
2326 Printer.printMetadata("scope", N->getRawScope());
2327 Printer.printMetadata("file", N->getRawFile());
2328 Printer.printInt("line", N->getLine());
2329 Printer.printMetadataOrInt("size", N->getRawSizeInBits(), true);
2330 Printer.printInt("align", N->getAlignInBits());
2331 Printer.printDIFlags("flags", N->getFlags());
2332 Printer.printMetadata("baseType", N->getRawBaseType(),
2333 /* ShouldSkipNull */ false);
2334 Printer.printMetadata("lowerBound", N->getRawLowerBound());
2335 Printer.printMetadata("upperBound", N->getRawUpperBound());
2336 Printer.printMetadata("stride", N->getRawStride());
2337 Printer.printMetadata("bias", N->getRawBias());
2338 Out << ")";
2339}
2340
2342 AsmWriterContext &WriterCtx) {
2343 Out << "!DICompositeType(";
2344 MDFieldPrinter Printer(Out, WriterCtx);
2345 Printer.printTag(N);
2346 Printer.printString("name", N->getName());
2347 Printer.printMetadata("scope", N->getRawScope());
2348 Printer.printMetadata("file", N->getRawFile());
2349 Printer.printInt("line", N->getLine());
2350 Printer.printMetadata("baseType", N->getRawBaseType());
2351 Printer.printMetadataOrInt("size", N->getRawSizeInBits(), true);
2352 Printer.printInt("align", N->getAlignInBits());
2353 Printer.printMetadataOrInt("offset", N->getRawOffsetInBits(), true);
2354 Printer.printInt("num_extra_inhabitants", N->getNumExtraInhabitants());
2355 Printer.printDIFlags("flags", N->getFlags());
2356 Printer.printMetadata("elements", N->getRawElements());
2357 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2359 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2360 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2361 Printer.printString("identifier", N->getIdentifier());
2362 Printer.printMetadata("discriminator", N->getRawDiscriminator());
2363 Printer.printMetadata("dataLocation", N->getRawDataLocation());
2364 Printer.printMetadata("associated", N->getRawAssociated());
2365 Printer.printMetadata("allocated", N->getRawAllocated());
2366 if (auto *RankConst = N->getRankConst())
2367 Printer.printInt("rank", RankConst->getSExtValue(),
2368 /* ShouldSkipZero */ false);
2369 else
2370 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2371 Printer.printMetadata("annotations", N->getRawAnnotations());
2372 if (auto *Specification = N->getRawSpecification())
2373 Printer.printMetadata("specification", Specification);
2374
2375 if (auto EnumKind = N->getEnumKind())
2376 Printer.printDwarfEnum("enumKind", *EnumKind, dwarf::EnumKindString,
2377 /*ShouldSkipZero=*/false);
2378
2379 Printer.printMetadata("bitStride", N->getRawBitStride());
2380 Out << ")";
2381}
2382
2384 AsmWriterContext &WriterCtx) {
2385 Out << "!DISubroutineType(";
2386 MDFieldPrinter Printer(Out, WriterCtx);
2387 Printer.printDIFlags("flags", N->getFlags());
2388 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2389 Printer.printMetadata("types", N->getRawTypeArray(),
2390 /* ShouldSkipNull */ false);
2391 Out << ")";
2392}
2393
2394static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2395 Out << "!DIFile(";
2396 MDFieldPrinter Printer(Out);
2397 Printer.printString("filename", N->getFilename(),
2398 /* ShouldSkipEmpty */ false);
2399 Printer.printString("directory", N->getDirectory(),
2400 /* ShouldSkipEmpty */ false);
2401 // Print all values for checksum together, or not at all.
2402 if (N->getChecksum())
2403 Printer.printChecksum(*N->getChecksum());
2404 if (N->getSource())
2405 Printer.printString("source", *N->getSource(),
2406 /* ShouldSkipEmpty */ false);
2407 Out << ")";
2408}
2409
2411 AsmWriterContext &WriterCtx) {
2412 Out << "!DICompileUnit(";
2413 MDFieldPrinter Printer(Out, WriterCtx);
2414 Printer.printDwarfEnum("language", N->getSourceLanguage(),
2415 dwarf::LanguageString, /* ShouldSkipZero */ false);
2416 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2417 Printer.printString("producer", N->getProducer());
2418 Printer.printBool("isOptimized", N->isOptimized());
2419 Printer.printString("flags", N->getFlags());
2420 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2421 /* ShouldSkipZero */ false);
2422 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2423 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2424 Printer.printMetadata("enums", N->getRawEnumTypes());
2425 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2426 Printer.printMetadata("globals", N->getRawGlobalVariables());
2427 Printer.printMetadata("imports", N->getRawImportedEntities());
2428 Printer.printMetadata("macros", N->getRawMacros());
2429 Printer.printInt("dwoId", N->getDWOId());
2430 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2431 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2432 false);
2433 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2434 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2435 Printer.printString("sysroot", N->getSysRoot());
2436 Printer.printString("sdk", N->getSDK());
2437 Out << ")";
2438}
2439
2441 AsmWriterContext &WriterCtx) {
2442 Out << "!DISubprogram(";
2443 MDFieldPrinter Printer(Out, WriterCtx);
2444 Printer.printString("name", N->getName());
2445 Printer.printString("linkageName", N->getLinkageName());
2446 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2447 Printer.printMetadata("file", N->getRawFile());
2448 Printer.printInt("line", N->getLine());
2449 Printer.printMetadata("type", N->getRawType());
2450 Printer.printInt("scopeLine", N->getScopeLine());
2451 Printer.printMetadata("containingType", N->getRawContainingType());
2452 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2453 N->getVirtualIndex() != 0)
2454 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2455 Printer.printInt("thisAdjustment", N->getThisAdjustment());
2456 Printer.printDIFlags("flags", N->getFlags());
2457 Printer.printDISPFlags("spFlags", N->getSPFlags());
2458 Printer.printMetadata("unit", N->getRawUnit());
2459 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2460 Printer.printMetadata("declaration", N->getRawDeclaration());
2461 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2462 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2463 Printer.printMetadata("annotations", N->getRawAnnotations());
2464 Printer.printString("targetFuncName", N->getTargetFuncName());
2465 Printer.printBool("keyInstructions", N->getKeyInstructionsEnabled(), false);
2466 Out << ")";
2467}
2468
2470 AsmWriterContext &WriterCtx) {
2471 Out << "!DILexicalBlock(";
2472 MDFieldPrinter Printer(Out, WriterCtx);
2473 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2474 Printer.printMetadata("file", N->getRawFile());
2475 Printer.printInt("line", N->getLine());
2476 Printer.printInt("column", N->getColumn());
2477 Out << ")";
2478}
2479
2481 const DILexicalBlockFile *N,
2482 AsmWriterContext &WriterCtx) {
2483 Out << "!DILexicalBlockFile(";
2484 MDFieldPrinter Printer(Out, WriterCtx);
2485 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2486 Printer.printMetadata("file", N->getRawFile());
2487 Printer.printInt("discriminator", N->getDiscriminator(),
2488 /* ShouldSkipZero */ false);
2489 Out << ")";
2490}
2491
2493 AsmWriterContext &WriterCtx) {
2494 Out << "!DINamespace(";
2495 MDFieldPrinter Printer(Out, WriterCtx);
2496 Printer.printString("name", N->getName());
2497 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2498 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2499 Out << ")";
2500}
2501
2503 AsmWriterContext &WriterCtx) {
2504 Out << "!DICommonBlock(";
2505 MDFieldPrinter Printer(Out, WriterCtx);
2506 Printer.printMetadata("scope", N->getRawScope(), false);
2507 Printer.printMetadata("declaration", N->getRawDecl(), false);
2508 Printer.printString("name", N->getName());
2509 Printer.printMetadata("file", N->getRawFile());
2510 Printer.printInt("line", N->getLineNo());
2511 Out << ")";
2512}
2513
2514static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2515 AsmWriterContext &WriterCtx) {
2516 Out << "!DIMacro(";
2517 MDFieldPrinter Printer(Out, WriterCtx);
2518 Printer.printMacinfoType(N);
2519 Printer.printInt("line", N->getLine());
2520 Printer.printString("name", N->getName());
2521 Printer.printString("value", N->getValue());
2522 Out << ")";
2523}
2524
2526 AsmWriterContext &WriterCtx) {
2527 Out << "!DIMacroFile(";
2528 MDFieldPrinter Printer(Out, WriterCtx);
2529 Printer.printInt("line", N->getLine());
2530 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2531 Printer.printMetadata("nodes", N->getRawElements());
2532 Out << ")";
2533}
2534
2535static void writeDIModule(raw_ostream &Out, const DIModule *N,
2536 AsmWriterContext &WriterCtx) {
2537 Out << "!DIModule(";
2538 MDFieldPrinter Printer(Out, WriterCtx);
2539 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2540 Printer.printString("name", N->getName());
2541 Printer.printString("configMacros", N->getConfigurationMacros());
2542 Printer.printString("includePath", N->getIncludePath());
2543 Printer.printString("apinotes", N->getAPINotesFile());
2544 Printer.printMetadata("file", N->getRawFile());
2545 Printer.printInt("line", N->getLineNo());
2546 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2547 Out << ")";
2548}
2549
2552 AsmWriterContext &WriterCtx) {
2553 Out << "!DITemplateTypeParameter(";
2554 MDFieldPrinter Printer(Out, WriterCtx);
2555 Printer.printString("name", N->getName());
2556 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2557 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2558 Out << ")";
2559}
2560
2563 AsmWriterContext &WriterCtx) {
2564 Out << "!DITemplateValueParameter(";
2565 MDFieldPrinter Printer(Out, WriterCtx);
2566 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2567 Printer.printTag(N);
2568 Printer.printString("name", N->getName());
2569 Printer.printMetadata("type", N->getRawType());
2570 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2571 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2572 Out << ")";
2573}
2574
2576 AsmWriterContext &WriterCtx) {
2577 Out << "!DIGlobalVariable(";
2578 MDFieldPrinter Printer(Out, WriterCtx);
2579 Printer.printString("name", N->getName());
2580 Printer.printString("linkageName", N->getLinkageName());
2581 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2582 Printer.printMetadata("file", N->getRawFile());
2583 Printer.printInt("line", N->getLine());
2584 Printer.printMetadata("type", N->getRawType());
2585 Printer.printBool("isLocal", N->isLocalToUnit());
2586 Printer.printBool("isDefinition", N->isDefinition());
2587 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2588 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2589 Printer.printInt("align", N->getAlignInBits());
2590 Printer.printMetadata("annotations", N->getRawAnnotations());
2591 Out << ")";
2592}
2593
2595 AsmWriterContext &WriterCtx) {
2596 Out << "!DILocalVariable(";
2597 MDFieldPrinter Printer(Out, WriterCtx);
2598 Printer.printString("name", N->getName());
2599 Printer.printInt("arg", N->getArg());
2600 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2601 Printer.printMetadata("file", N->getRawFile());
2602 Printer.printInt("line", N->getLine());
2603 Printer.printMetadata("type", N->getRawType());
2604 Printer.printDIFlags("flags", N->getFlags());
2605 Printer.printInt("align", N->getAlignInBits());
2606 Printer.printMetadata("annotations", N->getRawAnnotations());
2607 Out << ")";
2608}
2609
2610static void writeDILabel(raw_ostream &Out, const DILabel *N,
2611 AsmWriterContext &WriterCtx) {
2612 Out << "!DILabel(";
2613 MDFieldPrinter Printer(Out, WriterCtx);
2614 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2615 Printer.printString("name", N->getName());
2616 Printer.printMetadata("file", N->getRawFile());
2617 Printer.printInt("line", N->getLine());
2618 Printer.printInt("column", N->getColumn());
2619 Printer.printBool("isArtificial", N->isArtificial(), false);
2620 if (N->getCoroSuspendIdx())
2621 Printer.printInt("coroSuspendIdx", *N->getCoroSuspendIdx(),
2622 /* ShouldSkipZero */ false);
2623 Out << ")";
2624}
2625
2627 AsmWriterContext &WriterCtx) {
2628 Out << "!DIExpression(";
2629 FieldSeparator FS;
2630 if (N->isValid()) {
2631 for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2632 auto OpStr = dwarf::OperationEncodingString(Op.getOp());
2633 assert(!OpStr.empty() && "Expected valid opcode");
2634
2635 Out << FS << OpStr;
2636 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2637 Out << FS << Op.getArg(0);
2638 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
2639 } else {
2640 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2641 Out << FS << Op.getArg(A);
2642 }
2643 }
2644 } else {
2645 for (const auto &I : N->getElements())
2646 Out << FS << I;
2647 }
2648 Out << ")";
2649}
2650
2651static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2652 AsmWriterContext &WriterCtx,
2653 bool FromValue = false) {
2654 assert(FromValue &&
2655 "Unexpected DIArgList metadata outside of value argument");
2656 Out << "!DIArgList(";
2657 FieldSeparator FS;
2658 MDFieldPrinter Printer(Out, WriterCtx);
2659 for (Metadata *Arg : N->getArgs()) {
2660 Out << FS;
2661 WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2662 }
2663 Out << ")";
2664}
2665
2668 AsmWriterContext &WriterCtx) {
2669 Out << "!DIGlobalVariableExpression(";
2670 MDFieldPrinter Printer(Out, WriterCtx);
2671 Printer.printMetadata("var", N->getVariable());
2672 Printer.printMetadata("expr", N->getExpression());
2673 Out << ")";
2674}
2675
2677 AsmWriterContext &WriterCtx) {
2678 Out << "!DIObjCProperty(";
2679 MDFieldPrinter Printer(Out, WriterCtx);
2680 Printer.printString("name", N->getName());
2681 Printer.printMetadata("file", N->getRawFile());
2682 Printer.printInt("line", N->getLine());
2683 Printer.printString("setter", N->getSetterName());
2684 Printer.printString("getter", N->getGetterName());
2685 Printer.printInt("attributes", N->getAttributes());
2686 Printer.printMetadata("type", N->getRawType());
2687 Out << ")";
2688}
2689
2691 AsmWriterContext &WriterCtx) {
2692 Out << "!DIImportedEntity(";
2693 MDFieldPrinter Printer(Out, WriterCtx);
2694 Printer.printTag(N);
2695 Printer.printString("name", N->getName());
2696 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2697 Printer.printMetadata("entity", N->getRawEntity());
2698 Printer.printMetadata("file", N->getRawFile());
2699 Printer.printInt("line", N->getLine());
2700 Printer.printMetadata("elements", N->getRawElements());
2701 Out << ")";
2702}
2703
2705 AsmWriterContext &Ctx) {
2706 if (Node->isDistinct())
2707 Out << "distinct ";
2708 else if (Node->isTemporary())
2709 Out << "<temporary!> "; // Handle broken code.
2710
2711 switch (Node->getMetadataID()) {
2712 default:
2713 llvm_unreachable("Expected uniquable MDNode");
2714#define HANDLE_MDNODE_LEAF(CLASS) \
2715 case Metadata::CLASS##Kind: \
2716 write##CLASS(Out, cast<CLASS>(Node), Ctx); \
2717 break;
2718#include "llvm/IR/Metadata.def"
2719 }
2720}
2721
2722// Full implementation of printing a Value as an operand with support for
2723// TypePrinting, etc.
2724static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2725 AsmWriterContext &WriterCtx) {
2726 if (V->hasName()) {
2727 PrintLLVMName(Out, V);
2728 return;
2729 }
2730
2731 const Constant *CV = dyn_cast<Constant>(V);
2732 if (CV && !isa<GlobalValue>(CV)) {
2733 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2734 WriteConstantInternal(Out, CV, WriterCtx);
2735 return;
2736 }
2737
2738 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2739 Out << "asm ";
2740 if (IA->hasSideEffects())
2741 Out << "sideeffect ";
2742 if (IA->isAlignStack())
2743 Out << "alignstack ";
2744 // We don't emit the AD_ATT dialect as it's the assumed default.
2745 if (IA->getDialect() == InlineAsm::AD_Intel)
2746 Out << "inteldialect ";
2747 if (IA->canThrow())
2748 Out << "unwind ";
2749 Out << '"';
2750 printEscapedString(IA->getAsmString(), Out);
2751 Out << "\", \"";
2752 printEscapedString(IA->getConstraintString(), Out);
2753 Out << '"';
2754 return;
2755 }
2756
2757 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2758 WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2759 /* FromValue */ true);
2760 return;
2761 }
2762
2763 char Prefix = '%';
2764 int Slot;
2765 auto *Machine = WriterCtx.Machine;
2766 // If we have a SlotTracker, use it.
2767 if (Machine) {
2768 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2769 Slot = Machine->getGlobalSlot(GV);
2770 Prefix = '@';
2771 } else {
2772 Slot = Machine->getLocalSlot(V);
2773
2774 // If the local value didn't succeed, then we may be referring to a value
2775 // from a different function. Translate it, as this can happen when using
2776 // address of blocks.
2777 if (Slot == -1)
2778 if ((Machine = createSlotTracker(V))) {
2779 Slot = Machine->getLocalSlot(V);
2780 delete Machine;
2781 }
2782 }
2783 } else if ((Machine = createSlotTracker(V))) {
2784 // Otherwise, create one to get the # and then destroy it.
2785 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2786 Slot = Machine->getGlobalSlot(GV);
2787 Prefix = '@';
2788 } else {
2789 Slot = Machine->getLocalSlot(V);
2790 }
2791 delete Machine;
2792 Machine = nullptr;
2793 } else {
2794 Slot = -1;
2795 }
2796
2797 if (Slot != -1)
2798 Out << Prefix << Slot;
2799 else
2800 Out << "<badref>";
2801}
2802
2803static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2804 AsmWriterContext &WriterCtx,
2805 bool FromValue) {
2806 // Write DIExpressions and DIArgLists inline when used as a value. Improves
2807 // readability of debug info intrinsics.
2808 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2809 writeDIExpression(Out, Expr, WriterCtx);
2810 return;
2811 }
2812 if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2813 writeDIArgList(Out, ArgList, WriterCtx, FromValue);
2814 return;
2815 }
2816
2817 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2818 std::unique_ptr<SlotTracker> MachineStorage;
2819 SaveAndRestore SARMachine(WriterCtx.Machine);
2820 if (!WriterCtx.Machine) {
2821 MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2822 WriterCtx.Machine = MachineStorage.get();
2823 }
2824 int Slot = WriterCtx.Machine->getMetadataSlot(N);
2825 if (Slot == -1) {
2826 if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2827 writeDILocation(Out, Loc, WriterCtx);
2828 return;
2829 }
2830 // Give the pointer value instead of "badref", since this comes up all
2831 // the time when debugging.
2832 Out << "<" << N << ">";
2833 } else
2834 Out << '!' << Slot;
2835 return;
2836 }
2837
2838 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2839 Out << "!\"";
2840 printEscapedString(MDS->getString(), Out);
2841 Out << '"';
2842 return;
2843 }
2844
2845 auto *V = cast<ValueAsMetadata>(MD);
2846 assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
2847 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2848 "Unexpected function-local metadata outside of value argument");
2849
2850 WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
2851 Out << ' ';
2852 WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
2853}
2854
2855namespace {
2856
2857class AssemblyWriter {
2859 const Module *TheModule = nullptr;
2860 const ModuleSummaryIndex *TheIndex = nullptr;
2861 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2863 TypePrinting TypePrinter;
2864 AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2866 bool IsForDebug;
2867 bool ShouldPreserveUseListOrder;
2868 UseListOrderMap UseListOrders;
2870 /// Synchronization scope names registered with LLVMContext.
2873
2874public:
2875 /// Construct an AssemblyWriter with an external SlotTracker
2876 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2877 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2878 bool ShouldPreserveUseListOrder = false);
2879
2880 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2881 const ModuleSummaryIndex *Index, bool IsForDebug);
2882
2883 AsmWriterContext getContext() {
2884 return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2885 }
2886
2887 void printMDNodeBody(const MDNode *MD);
2888 void printNamedMDNode(const NamedMDNode *NMD);
2889
2890 void printModule(const Module *M);
2891
2892 void writeOperand(const Value *Op, bool PrintType);
2893 void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2894 void writeOperandBundles(const CallBase *Call);
2895 void writeSyncScope(const LLVMContext &Context,
2896 SyncScope::ID SSID);
2897 void writeAtomic(const LLVMContext &Context,
2898 AtomicOrdering Ordering,
2899 SyncScope::ID SSID);
2900 void writeAtomicCmpXchg(const LLVMContext &Context,
2901 AtomicOrdering SuccessOrdering,
2902 AtomicOrdering FailureOrdering,
2903 SyncScope::ID SSID);
2904
2905 void writeAllMDNodes();
2906 void writeMDNode(unsigned Slot, const MDNode *Node);
2907 void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2908 void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
2909 void writeAllAttributeGroups();
2910
2911 void printTypeIdentities();
2912 void printGlobal(const GlobalVariable *GV);
2913 void printAlias(const GlobalAlias *GA);
2914 void printIFunc(const GlobalIFunc *GI);
2915 void printComdat(const Comdat *C);
2916 void printFunction(const Function *F);
2917 void printArgument(const Argument *FA, AttributeSet Attrs);
2918 void printBasicBlock(const BasicBlock *BB);
2919 void printInstructionLine(const Instruction &I);
2920 void printInstruction(const Instruction &I);
2921 void printDbgMarker(const DbgMarker &DPI);
2922 void printDbgVariableRecord(const DbgVariableRecord &DVR);
2923 void printDbgLabelRecord(const DbgLabelRecord &DLR);
2924 void printDbgRecord(const DbgRecord &DR);
2925 void printDbgRecordLine(const DbgRecord &DR);
2926
2927 void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
2928 void printUseLists(const Function *F);
2929
2930 void printModuleSummaryIndex();
2931 void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2932 void printSummary(const GlobalValueSummary &Summary);
2933 void printAliasSummary(const AliasSummary *AS);
2934 void printGlobalVarSummary(const GlobalVarSummary *GS);
2935 void printFunctionSummary(const FunctionSummary *FS);
2936 void printTypeIdSummary(const TypeIdSummary &TIS);
2937 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2938 void printTypeTestResolution(const TypeTestResolution &TTRes);
2939 void printArgs(const std::vector<uint64_t> &Args);
2940 void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2941 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2942 void printVFuncId(const FunctionSummary::VFuncId VFId);
2943 void
2944 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
2945 const char *Tag);
2946 void
2947 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
2948 const char *Tag);
2949
2950private:
2951 /// Print out metadata attachments.
2952 void printMetadataAttachments(
2953 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2954 StringRef Separator);
2955
2956 // printInfoComment - Print a little comment after the instruction indicating
2957 // which slot it occupies.
2958 void printInfoComment(const Value &V);
2959
2960 // printGCRelocateComment - print comment after call to the gc.relocate
2961 // intrinsic indicating base and derived pointer names.
2962 void printGCRelocateComment(const GCRelocateInst &Relocate);
2963};
2964
2965} // end anonymous namespace
2966
2967AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2968 const Module *M, AssemblyAnnotationWriter *AAW,
2969 bool IsForDebug, bool ShouldPreserveUseListOrder)
2970 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2971 IsForDebug(IsForDebug),
2972 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2973 if (!TheModule)
2974 return;
2975 for (const GlobalObject &GO : TheModule->global_objects())
2976 if (const Comdat *C = GO.getComdat())
2977 Comdats.insert(C);
2978}
2979
2980AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2981 const ModuleSummaryIndex *Index, bool IsForDebug)
2982 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2983 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2984
2985void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2986 if (!Operand) {
2987 Out << "<null operand!>";
2988 return;
2989 }
2990 if (PrintType) {
2991 TypePrinter.print(Operand->getType(), Out);
2992 Out << ' ';
2993 }
2994 auto WriterCtx = getContext();
2995 WriteAsOperandInternal(Out, Operand, WriterCtx);
2996}
2997
2998void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2999 SyncScope::ID SSID) {
3000 switch (SSID) {
3001 case SyncScope::System: {
3002 break;
3003 }
3004 default: {
3005 if (SSNs.empty())
3006 Context.getSyncScopeNames(SSNs);
3007
3008 Out << " syncscope(\"";
3009 printEscapedString(SSNs[SSID], Out);
3010 Out << "\")";
3011 break;
3012 }
3013 }
3014}
3015
3016void AssemblyWriter::writeAtomic(const LLVMContext &Context,
3017 AtomicOrdering Ordering,
3018 SyncScope::ID SSID) {
3019 if (Ordering == AtomicOrdering::NotAtomic)
3020 return;
3021
3022 writeSyncScope(Context, SSID);
3023 Out << " " << toIRString(Ordering);
3024}
3025
3026void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
3027 AtomicOrdering SuccessOrdering,
3028 AtomicOrdering FailureOrdering,
3029 SyncScope::ID SSID) {
3030 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
3031 FailureOrdering != AtomicOrdering::NotAtomic);
3032
3033 writeSyncScope(Context, SSID);
3034 Out << " " << toIRString(SuccessOrdering);
3035 Out << " " << toIRString(FailureOrdering);
3036}
3037
3038void AssemblyWriter::writeParamOperand(const Value *Operand,
3039 AttributeSet Attrs) {
3040 if (!Operand) {
3041 Out << "<null operand!>";
3042 return;
3043 }
3044
3045 // Print the type
3046 TypePrinter.print(Operand->getType(), Out);
3047 // Print parameter attributes list
3048 if (Attrs.hasAttributes()) {
3049 Out << ' ';
3050 writeAttributeSet(Attrs);
3051 }
3052 Out << ' ';
3053 // Print the operand
3054 auto WriterCtx = getContext();
3055 WriteAsOperandInternal(Out, Operand, WriterCtx);
3056}
3057
3058void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
3059 if (!Call->hasOperandBundles())
3060 return;
3061
3062 Out << " [ ";
3063
3064 bool FirstBundle = true;
3065 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
3066 OperandBundleUse BU = Call->getOperandBundleAt(i);
3067
3068 if (!FirstBundle)
3069 Out << ", ";
3070 FirstBundle = false;
3071
3072 Out << '"';
3073 printEscapedString(BU.getTagName(), Out);
3074 Out << '"';
3075
3076 Out << '(';
3077
3078 bool FirstInput = true;
3079 auto WriterCtx = getContext();
3080 for (const auto &Input : BU.Inputs) {
3081 if (!FirstInput)
3082 Out << ", ";
3083 FirstInput = false;
3084
3085 if (Input == nullptr)
3086 Out << "<null operand bundle!>";
3087 else {
3088 TypePrinter.print(Input->getType(), Out);
3089 Out << " ";
3090 WriteAsOperandInternal(Out, Input, WriterCtx);
3091 }
3092 }
3093
3094 Out << ')';
3095 }
3096
3097 Out << " ]";
3098}
3099
3100void AssemblyWriter::printModule(const Module *M) {
3101 Machine.initializeIfNeeded();
3102
3103 if (ShouldPreserveUseListOrder)
3104 UseListOrders = predictUseListOrder(M);
3105
3106 if (!M->getModuleIdentifier().empty() &&
3107 // Don't print the ID if it will start a new line (which would
3108 // require a comment char before it).
3109 M->getModuleIdentifier().find('\n') == std::string::npos)
3110 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
3111
3112 if (!M->getSourceFileName().empty()) {
3113 Out << "source_filename = \"";
3114 printEscapedString(M->getSourceFileName(), Out);
3115 Out << "\"\n";
3116 }
3117
3118 const std::string &DL = M->getDataLayoutStr();
3119 if (!DL.empty())
3120 Out << "target datalayout = \"" << DL << "\"\n";
3121 if (!M->getTargetTriple().empty())
3122 Out << "target triple = \"" << M->getTargetTriple().str() << "\"\n";
3123
3124 if (!M->getModuleInlineAsm().empty()) {
3125 Out << '\n';
3126
3127 // Split the string into lines, to make it easier to read the .ll file.
3128 StringRef Asm = M->getModuleInlineAsm();
3129 do {
3130 StringRef Front;
3131 std::tie(Front, Asm) = Asm.split('\n');
3132
3133 // We found a newline, print the portion of the asm string from the
3134 // last newline up to this newline.
3135 Out << "module asm \"";
3136 printEscapedString(Front, Out);
3137 Out << "\"\n";
3138 } while (!Asm.empty());
3139 }
3140
3141 printTypeIdentities();
3142
3143 // Output all comdats.
3144 if (!Comdats.empty())
3145 Out << '\n';
3146 for (const Comdat *C : Comdats) {
3147 printComdat(C);
3148 if (C != Comdats.back())
3149 Out << '\n';
3150 }
3151
3152 // Output all globals.
3153 if (!M->global_empty()) Out << '\n';
3154 for (const GlobalVariable &GV : M->globals()) {
3155 printGlobal(&GV); Out << '\n';
3156 }
3157
3158 // Output all aliases.
3159 if (!M->alias_empty()) Out << "\n";
3160 for (const GlobalAlias &GA : M->aliases())
3161 printAlias(&GA);
3162
3163 // Output all ifuncs.
3164 if (!M->ifunc_empty()) Out << "\n";
3165 for (const GlobalIFunc &GI : M->ifuncs())
3166 printIFunc(&GI);
3167
3168 // Output all of the functions.
3169 for (const Function &F : *M) {
3170 Out << '\n';
3171 printFunction(&F);
3172 }
3173
3174 // Output global use-lists.
3175 printUseLists(nullptr);
3176
3177 // Output all attribute groups.
3178 if (!Machine.as_empty()) {
3179 Out << '\n';
3180 writeAllAttributeGroups();
3181 }
3182
3183 // Output named metadata.
3184 if (!M->named_metadata_empty()) Out << '\n';
3185
3186 for (const NamedMDNode &Node : M->named_metadata())
3187 printNamedMDNode(&Node);
3188
3189 // Output metadata.
3190 if (!Machine.mdn_empty()) {
3191 Out << '\n';
3192 writeAllMDNodes();
3193 }
3194}
3195
3196void AssemblyWriter::printModuleSummaryIndex() {
3197 assert(TheIndex);
3198 int NumSlots = Machine.initializeIndexIfNeeded();
3199
3200 Out << "\n";
3201
3202 // Print module path entries. To print in order, add paths to a vector
3203 // indexed by module slot.
3204 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
3205 std::string RegularLTOModuleName =
3207 moduleVec.resize(TheIndex->modulePaths().size());
3208 for (auto &[ModPath, ModHash] : TheIndex->modulePaths())
3209 moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
3210 // An empty module path is a special entry for a regular LTO module
3211 // created during the thin link.
3212 ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), ModHash);
3213
3214 unsigned i = 0;
3215 for (auto &ModPair : moduleVec) {
3216 Out << "^" << i++ << " = module: (";
3217 Out << "path: \"";
3218 printEscapedString(ModPair.first, Out);
3219 Out << "\", hash: (";
3220 FieldSeparator FS;
3221 for (auto Hash : ModPair.second)
3222 Out << FS << Hash;
3223 Out << "))\n";
3224 }
3225
3226 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
3227 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
3228 for (auto &GlobalList : *TheIndex) {
3229 auto GUID = GlobalList.first;
3230 for (auto &Summary : GlobalList.second.SummaryList)
3231 SummaryToGUIDMap[Summary.get()] = GUID;
3232 }
3233
3234 // Print the global value summary entries.
3235 for (auto &GlobalList : *TheIndex) {
3236 auto GUID = GlobalList.first;
3237 auto VI = TheIndex->getValueInfo(GlobalList);
3238 printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
3239 }
3240
3241 // Print the TypeIdMap entries.
3242 for (const auto &TID : TheIndex->typeIds()) {
3243 Out << "^" << Machine.getTypeIdSlot(TID.second.first)
3244 << " = typeid: (name: \"" << TID.second.first << "\"";
3245 printTypeIdSummary(TID.second.second);
3246 Out << ") ; guid = " << TID.first << "\n";
3247 }
3248
3249 // Print the TypeIdCompatibleVtableMap entries.
3250 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
3252 Out << "^" << Machine.getTypeIdCompatibleVtableSlot(TId.first)
3253 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
3254 printTypeIdCompatibleVtableSummary(TId.second);
3255 Out << ") ; guid = " << GUID << "\n";
3256 }
3257
3258 // Don't emit flags when it's not really needed (value is zero by default).
3259 if (TheIndex->getFlags()) {
3260 Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
3261 ++NumSlots;
3262 }
3263
3264 Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
3265 << "\n";
3266}
3267
3268static const char *
3270 switch (K) {
3272 return "indir";
3274 return "singleImpl";
3276 return "branchFunnel";
3277 }
3278 llvm_unreachable("invalid WholeProgramDevirtResolution kind");
3279}
3280
3283 switch (K) {
3285 return "indir";
3287 return "uniformRetVal";
3289 return "uniqueRetVal";
3291 return "virtualConstProp";
3292 }
3293 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
3294}
3295
3297 switch (K) {
3299 return "unknown";
3301 return "unsat";
3303 return "byteArray";
3305 return "inline";
3307 return "single";
3309 return "allOnes";
3310 }
3311 llvm_unreachable("invalid TypeTestResolution kind");
3312}
3313
3314void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
3315 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
3316 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
3317
3318 // The following fields are only used if the target does not support the use
3319 // of absolute symbols to store constants. Print only if non-zero.
3320 if (TTRes.AlignLog2)
3321 Out << ", alignLog2: " << TTRes.AlignLog2;
3322 if (TTRes.SizeM1)
3323 Out << ", sizeM1: " << TTRes.SizeM1;
3324 if (TTRes.BitMask)
3325 // BitMask is uint8_t which causes it to print the corresponding char.
3326 Out << ", bitMask: " << (unsigned)TTRes.BitMask;
3327 if (TTRes.InlineBits)
3328 Out << ", inlineBits: " << TTRes.InlineBits;
3329
3330 Out << ")";
3331}
3332
3333void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3334 Out << ", summary: (";
3335 printTypeTestResolution(TIS.TTRes);
3336 if (!TIS.WPDRes.empty()) {
3337 Out << ", wpdResolutions: (";
3338 FieldSeparator FS;
3339 for (auto &WPDRes : TIS.WPDRes) {
3340 Out << FS;
3341 Out << "(offset: " << WPDRes.first << ", ";
3342 printWPDRes(WPDRes.second);
3343 Out << ")";
3344 }
3345 Out << ")";
3346 }
3347 Out << ")";
3348}
3349
3350void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3351 const TypeIdCompatibleVtableInfo &TI) {
3352 Out << ", summary: (";
3353 FieldSeparator FS;
3354 for (auto &P : TI) {
3355 Out << FS;
3356 Out << "(offset: " << P.AddressPointOffset << ", ";
3357 Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
3358 Out << ")";
3359 }
3360 Out << ")";
3361}
3362
3363void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
3364 Out << "args: (";
3365 FieldSeparator FS;
3366 for (auto arg : Args) {
3367 Out << FS;
3368 Out << arg;
3369 }
3370 Out << ")";
3371}
3372
3373void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3374 Out << "wpdRes: (kind: ";
3376
3378 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3379
3380 if (!WPDRes.ResByArg.empty()) {
3381 Out << ", resByArg: (";
3382 FieldSeparator FS;
3383 for (auto &ResByArg : WPDRes.ResByArg) {
3384 Out << FS;
3385 printArgs(ResByArg.first);
3386 Out << ", byArg: (kind: ";
3387 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
3388 if (ResByArg.second.TheKind ==
3390 ResByArg.second.TheKind ==
3392 Out << ", info: " << ResByArg.second.Info;
3393
3394 // The following fields are only used if the target does not support the
3395 // use of absolute symbols to store constants. Print only if non-zero.
3396 if (ResByArg.second.Byte || ResByArg.second.Bit)
3397 Out << ", byte: " << ResByArg.second.Byte
3398 << ", bit: " << ResByArg.second.Bit;
3399
3400 Out << ")";
3401 }
3402 Out << ")";
3403 }
3404 Out << ")";
3405}
3406
3408 switch (SK) {
3410 return "alias";
3412 return "function";
3414 return "variable";
3415 }
3416 llvm_unreachable("invalid summary kind");
3417}
3418
3419void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3420 Out << ", aliasee: ";
3421 // The indexes emitted for distributed backends may not include the
3422 // aliasee summary (only if it is being imported directly). Handle
3423 // that case by just emitting "null" as the aliasee.
3424 if (AS->hasAliasee())
3425 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
3426 else
3427 Out << "null";
3428}
3429
3430void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3431 auto VTableFuncs = GS->vTableFuncs();
3432 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3433 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3434 << "constant: " << GS->VarFlags.Constant;
3435 if (!VTableFuncs.empty())
3436 Out << ", "
3437 << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3438 Out << ")";
3439
3440 if (!VTableFuncs.empty()) {
3441 Out << ", vTableFuncs: (";
3442 FieldSeparator FS;
3443 for (auto &P : VTableFuncs) {
3444 Out << FS;
3445 Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
3446 << ", offset: " << P.VTableOffset;
3447 Out << ")";
3448 }
3449 Out << ")";
3450 }
3451}
3452
3454 switch (LT) {
3456 return "external";
3458 return "private";
3460 return "internal";
3462 return "linkonce";
3464 return "linkonce_odr";
3466 return "weak";
3468 return "weak_odr";
3470 return "common";
3472 return "appending";
3474 return "extern_weak";
3476 return "available_externally";
3477 }
3478 llvm_unreachable("invalid linkage");
3479}
3480
3481// When printing the linkage types in IR where the ExternalLinkage is
3482// not printed, and other linkage types are expected to be printed with
3483// a space after the name.
3486 return "";
3487 return getLinkageName(LT) + " ";
3488}
3489
3491 switch (Vis) {
3493 return "default";
3495 return "hidden";
3497 return "protected";
3498 }
3499 llvm_unreachable("invalid visibility");
3500}
3501
3503 switch (IK) {
3505 return "definition";
3507 return "declaration";
3508 }
3509 llvm_unreachable("invalid import kind");
3510}
3511
3512void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3513 Out << ", insts: " << FS->instCount();
3514 if (FS->fflags().anyFlagSet())
3515 Out << ", " << FS->fflags();
3516
3517 if (!FS->calls().empty()) {
3518 Out << ", calls: (";
3519 FieldSeparator IFS;
3520 for (auto &Call : FS->calls()) {
3521 Out << IFS;
3522 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
3523 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3524 Out << ", hotness: " << getHotnessName(Call.second.getHotness());
3525 else if (Call.second.RelBlockFreq)
3526 Out << ", relbf: " << Call.second.RelBlockFreq;
3527 // Follow the convention of emitting flags as a boolean value, but only
3528 // emit if true to avoid unnecessary verbosity and test churn.
3529 if (Call.second.HasTailCall)
3530 Out << ", tail: 1";
3531 Out << ")";
3532 }
3533 Out << ")";
3534 }
3535
3536 if (const auto *TIdInfo = FS->getTypeIdInfo())
3537 printTypeIdInfo(*TIdInfo);
3538
3539 // The AllocationType identifiers capture the profiled context behavior
3540 // reaching a specific static allocation site (possibly cloned).
3541 auto AllocTypeName = [](uint8_t Type) -> const char * {
3542 switch (Type) {
3543 case (uint8_t)AllocationType::None:
3544 return "none";
3545 case (uint8_t)AllocationType::NotCold:
3546 return "notcold";
3547 case (uint8_t)AllocationType::Cold:
3548 return "cold";
3549 case (uint8_t)AllocationType::Hot:
3550 return "hot";
3551 }
3552 llvm_unreachable("Unexpected alloc type");
3553 };
3554
3555 if (!FS->allocs().empty()) {
3556 Out << ", allocs: (";
3557 FieldSeparator AFS;
3558 for (auto &AI : FS->allocs()) {
3559 Out << AFS;
3560 Out << "(versions: (";
3561 FieldSeparator VFS;
3562 for (auto V : AI.Versions) {
3563 Out << VFS;
3564 Out << AllocTypeName(V);
3565 }
3566 Out << "), memProf: (";
3567 FieldSeparator MIBFS;
3568 for (auto &MIB : AI.MIBs) {
3569 Out << MIBFS;
3570 Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3571 Out << ", stackIds: (";
3572 FieldSeparator SIDFS;
3573 for (auto Id : MIB.StackIdIndices) {
3574 Out << SIDFS;
3575 Out << TheIndex->getStackIdAtIndex(Id);
3576 }
3577 Out << "))";
3578 }
3579 Out << "))";
3580 }
3581 Out << ")";
3582 }
3583
3584 if (!FS->callsites().empty()) {
3585 Out << ", callsites: (";
3586 FieldSeparator SNFS;
3587 for (auto &CI : FS->callsites()) {
3588 Out << SNFS;
3589 if (CI.Callee)
3590 Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3591 else
3592 Out << "(callee: null";
3593 Out << ", clones: (";
3594 FieldSeparator VFS;
3595 for (auto V : CI.Clones) {
3596 Out << VFS;
3597 Out << V;
3598 }
3599 Out << "), stackIds: (";
3600 FieldSeparator SIDFS;
3601 for (auto Id : CI.StackIdIndices) {
3602 Out << SIDFS;
3603 Out << TheIndex->getStackIdAtIndex(Id);
3604 }
3605 Out << "))";
3606 }
3607 Out << ")";
3608 }
3609
3610 auto PrintRange = [&](const ConstantRange &Range) {
3611 Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3612 };
3613
3614 if (!FS->paramAccesses().empty()) {
3615 Out << ", params: (";
3616 FieldSeparator IFS;
3617 for (auto &PS : FS->paramAccesses()) {
3618 Out << IFS;
3619 Out << "(param: " << PS.ParamNo;
3620 Out << ", offset: ";
3621 PrintRange(PS.Use);
3622 if (!PS.Calls.empty()) {
3623 Out << ", calls: (";
3624 FieldSeparator IFS;
3625 for (auto &Call : PS.Calls) {
3626 Out << IFS;
3627 Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3628 Out << ", param: " << Call.ParamNo;
3629 Out << ", offset: ";
3630 PrintRange(Call.Offsets);
3631 Out << ")";
3632 }
3633 Out << ")";
3634 }
3635 Out << ")";
3636 }
3637 Out << ")";
3638 }
3639}
3640
3641void AssemblyWriter::printTypeIdInfo(
3642 const FunctionSummary::TypeIdInfo &TIDInfo) {
3643 Out << ", typeIdInfo: (";
3644 FieldSeparator TIDFS;
3645 if (!TIDInfo.TypeTests.empty()) {
3646 Out << TIDFS;
3647 Out << "typeTests: (";
3648 FieldSeparator FS;
3649 for (auto &GUID : TIDInfo.TypeTests) {
3650 auto TidIter = TheIndex->typeIds().equal_range(GUID);
3651 if (TidIter.first == TidIter.second) {
3652 Out << FS;
3653 Out << GUID;
3654 continue;
3655 }
3656 // Print all type id that correspond to this GUID.
3657 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
3658 Out << FS;
3659 auto Slot = Machine.getTypeIdSlot(TypeIdPair.first);
3660 assert(Slot != -1);
3661 Out << "^" << Slot;
3662 }
3663 }
3664 Out << ")";
3665 }
3666 if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3667 Out << TIDFS;
3668 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3669 }
3670 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3671 Out << TIDFS;
3672 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3673 }
3674 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3675 Out << TIDFS;
3676 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3677 "typeTestAssumeConstVCalls");
3678 }
3679 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3680 Out << TIDFS;
3681 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3682 "typeCheckedLoadConstVCalls");
3683 }
3684 Out << ")";
3685}
3686
3687void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3688 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3689 if (TidIter.first == TidIter.second) {
3690 Out << "vFuncId: (";
3691 Out << "guid: " << VFId.GUID;
3692 Out << ", offset: " << VFId.Offset;
3693 Out << ")";
3694 return;
3695 }
3696 // Print all type id that correspond to this GUID.
3697 FieldSeparator FS;
3698 for (const auto &[GUID, TypeIdPair] : make_range(TidIter)) {
3699 Out << FS;
3700 Out << "vFuncId: (";
3701 auto Slot = Machine.getTypeIdSlot(TypeIdPair.first);
3702 assert(Slot != -1);
3703 Out << "^" << Slot;
3704 Out << ", offset: " << VFId.Offset;
3705 Out << ")";
3706 }
3707}
3708
3709void AssemblyWriter::printNonConstVCalls(
3710 const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
3711 Out << Tag << ": (";
3712 FieldSeparator FS;
3713 for (auto &VFuncId : VCallList) {
3714 Out << FS;
3715 printVFuncId(VFuncId);
3716 }
3717 Out << ")";
3718}
3719
3720void AssemblyWriter::printConstVCalls(
3721 const std::vector<FunctionSummary::ConstVCall> &VCallList,
3722 const char *Tag) {
3723 Out << Tag << ": (";
3724 FieldSeparator FS;
3725 for (auto &ConstVCall : VCallList) {
3726 Out << FS;
3727 Out << "(";
3728 printVFuncId(ConstVCall.VFunc);
3729 if (!ConstVCall.Args.empty()) {
3730 Out << ", ";
3731 printArgs(ConstVCall.Args);
3732 }
3733 Out << ")";
3734 }
3735 Out << ")";
3736}
3737
3738void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3739 GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3741 Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3742 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3743 << ", flags: (";
3744 Out << "linkage: " << getLinkageName(LT);
3745 Out << ", visibility: "
3747 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3748 Out << ", live: " << GVFlags.Live;
3749 Out << ", dsoLocal: " << GVFlags.DSOLocal;
3750 Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3751 Out << ", importType: "
3753 Out << ")";
3754
3755 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3756 printAliasSummary(cast<AliasSummary>(&Summary));
3757 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3758 printFunctionSummary(cast<FunctionSummary>(&Summary));
3759 else
3760 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3761
3762 auto RefList = Summary.refs();
3763 if (!RefList.empty()) {
3764 Out << ", refs: (";
3765 FieldSeparator FS;
3766 for (auto &Ref : RefList) {
3767 Out << FS;
3768 if (Ref.isReadOnly())
3769 Out << "readonly ";
3770 else if (Ref.isWriteOnly())
3771 Out << "writeonly ";
3772 Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3773 }
3774 Out << ")";
3775 }
3776
3777 Out << ")";
3778}
3779
3780void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3781 Out << "^" << Slot << " = gv: (";
3782 if (VI.hasName() && !VI.name().empty())
3783 Out << "name: \"" << VI.name() << "\"";
3784 else
3785 Out << "guid: " << VI.getGUID();
3786 if (!VI.getSummaryList().empty()) {
3787 Out << ", summaries: (";
3788 FieldSeparator FS;
3789 for (auto &Summary : VI.getSummaryList()) {
3790 Out << FS;
3791 printSummary(*Summary);
3792 }
3793 Out << ")";
3794 }
3795 Out << ")";
3796 if (VI.hasName() && !VI.name().empty())
3797 Out << " ; guid = " << VI.getGUID();
3798 Out << "\n";
3799}
3800
3802 formatted_raw_ostream &Out) {
3803 if (Name.empty()) {
3804 Out << "<empty name> ";
3805 } else {
3806 unsigned char FirstC = static_cast<unsigned char>(Name[0]);
3807 if (isalpha(FirstC) || FirstC == '-' || FirstC == '$' || FirstC == '.' ||
3808 FirstC == '_')
3809 Out << FirstC;
3810 else
3811 Out << '\\' << hexdigit(FirstC >> 4) << hexdigit(FirstC & 0x0F);
3812 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3813 unsigned char C = Name[i];
3814 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
3815 Out << C;
3816 else
3817 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3818 }
3819 }
3820}
3821
3822void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3823 Out << '!';
3824 printMetadataIdentifier(NMD->getName(), Out);
3825 Out << " = !{";
3826 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3827 if (i)
3828 Out << ", ";
3829
3830 // Write DIExpressions inline.
3831 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3832 MDNode *Op = NMD->getOperand(i);
3833 if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3834 writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
3835 continue;
3836 }
3837
3838 int Slot = Machine.getMetadataSlot(Op);
3839 if (Slot == -1)
3840 Out << "<badref>";
3841 else
3842 Out << '!' << Slot;
3843 }
3844 Out << "}\n";
3845}
3846
3848 formatted_raw_ostream &Out) {
3849 switch (Vis) {
3851 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
3852 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3853 }
3854}
3855
3856static void PrintDSOLocation(const GlobalValue &GV,
3857 formatted_raw_ostream &Out) {
3858 if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3859 Out << "dso_local ";
3860}
3861
3863 formatted_raw_ostream &Out) {
3864 switch (SCT) {
3866 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3867 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3868 }
3869}
3870
3872 formatted_raw_ostream &Out) {
3873 switch (TLM) {
3874 case GlobalVariable::NotThreadLocal:
3875 break;
3876 case GlobalVariable::GeneralDynamicTLSModel:
3877 Out << "thread_local ";
3878 break;
3879 case GlobalVariable::LocalDynamicTLSModel:
3880 Out << "thread_local(localdynamic) ";
3881 break;
3882 case GlobalVariable::InitialExecTLSModel:
3883 Out << "thread_local(initialexec) ";
3884 break;
3885 case GlobalVariable::LocalExecTLSModel:
3886 Out << "thread_local(localexec) ";
3887 break;
3888 }
3889}
3890
3892 switch (UA) {
3893 case GlobalVariable::UnnamedAddr::None:
3894 return "";
3895 case GlobalVariable::UnnamedAddr::Local:
3896 return "local_unnamed_addr";
3897 case GlobalVariable::UnnamedAddr::Global:
3898 return "unnamed_addr";
3899 }
3900 llvm_unreachable("Unknown UnnamedAddr");
3901}
3902
3904 const GlobalObject &GO) {
3905 const Comdat *C = GO.getComdat();
3906 if (!C)
3907 return;
3908
3909 if (isa<GlobalVariable>(GO))
3910 Out << ',';
3911 Out << " comdat";
3912
3913 if (GO.getName() == C->getName())
3914 return;
3915
3916 Out << '(';
3917 PrintLLVMName(Out, C->getName(), ComdatPrefix);
3918 Out << ')';
3919}
3920
3921void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3922 if (GV->isMaterializable())
3923 Out << "; Materializable\n";
3924
3925 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3926 WriteAsOperandInternal(Out, GV, WriterCtx);
3927 Out << " = ";
3928
3929 if (!GV->hasInitializer() && GV->hasExternalLinkage())
3930 Out << "external ";
3931
3932 Out << getLinkageNameWithSpace(GV->getLinkage());
3933 PrintDSOLocation(*GV, Out);
3934 PrintVisibility(GV->getVisibility(), Out);
3938 if (!UA.empty())
3939 Out << UA << ' ';
3940
3941 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3942 Out << "addrspace(" << AddressSpace << ") ";
3943 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3944 Out << (GV->isConstant() ? "constant " : "global ");
3945 TypePrinter.print(GV->getValueType(), Out);
3946
3947 if (GV->hasInitializer()) {
3948 Out << ' ';
3949 writeOperand(GV->getInitializer(), false);
3950 }
3951
3952 if (GV->hasSection()) {
3953 Out << ", section \"";
3954 printEscapedString(GV->getSection(), Out);
3955 Out << '"';
3956 }
3957 if (GV->hasPartition()) {
3958 Out << ", partition \"";
3959 printEscapedString(GV->getPartition(), Out);
3960 Out << '"';
3961 }
3962 if (auto CM = GV->getCodeModel()) {
3963 Out << ", code_model \"";
3964 switch (*CM) {
3965 case CodeModel::Tiny:
3966 Out << "tiny";
3967 break;
3968 case CodeModel::Small:
3969 Out << "small";
3970 break;
3971 case CodeModel::Kernel:
3972 Out << "kernel";
3973 break;
3974 case CodeModel::Medium:
3975 Out << "medium";
3976 break;
3977 case CodeModel::Large:
3978 Out << "large";
3979 break;
3980 }
3981 Out << '"';
3982 }
3983
3985 if (GV->hasSanitizerMetadata()) {
3987 if (MD.NoAddress)
3988 Out << ", no_sanitize_address";
3989 if (MD.NoHWAddress)
3990 Out << ", no_sanitize_hwaddress";
3991 if (MD.Memtag)
3992 Out << ", sanitize_memtag";
3993 if (MD.IsDynInit)
3994 Out << ", sanitize_address_dyninit";
3995 }
3996
3997 maybePrintComdat(Out, *GV);
3998 if (MaybeAlign A = GV->getAlign())
3999 Out << ", align " << A->value();
4000
4002 GV->getAllMetadata(MDs);
4003 printMetadataAttachments(MDs, ", ");
4004
4005 auto Attrs = GV->getAttributes();
4006 if (Attrs.hasAttributes())
4007 Out << " #" << Machine.getAttributeGroupSlot(Attrs);
4008
4009 printInfoComment(*GV);
4010}
4011
4012void AssemblyWriter::printAlias(const GlobalAlias *GA) {
4013 if (GA->isMaterializable())
4014 Out << "; Materializable\n";
4015
4016 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
4017 WriteAsOperandInternal(Out, GA, WriterCtx);
4018 Out << " = ";
4019
4020 Out << getLinkageNameWithSpace(GA->getLinkage());
4021 PrintDSOLocation(*GA, Out);
4022 PrintVisibility(GA->getVisibility(), Out);
4026 if (!UA.empty())
4027 Out << UA << ' ';
4028
4029 Out << "alias ";
4030
4031 TypePrinter.print(GA->getValueType(), Out);
4032 Out << ", ";
4033
4034 if (const Constant *Aliasee = GA->getAliasee()) {
4035 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
4036 } else {
4037 TypePrinter.print(GA->getType(), Out);
4038 Out << " <<NULL ALIASEE>>";
4039 }
4040
4041 if (GA->hasPartition()) {
4042 Out << ", partition \"";
4043 printEscapedString(GA->getPartition(), Out);
4044 Out << '"';
4045 }
4046
4047 printInfoComment(*GA);
4048 Out << '\n';
4049}
4050
4051void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
4052 if (GI->isMaterializable())
4053 Out << "; Materializable\n";
4054
4055 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
4056 WriteAsOperandInternal(Out, GI, WriterCtx);
4057 Out << " = ";
4058
4059 Out << getLinkageNameWithSpace(GI->getLinkage());
4060 PrintDSOLocation(*GI, Out);
4061 PrintVisibility(GI->getVisibility(), Out);
4062
4063 Out << "ifunc ";
4064
4065 TypePrinter.print(GI->getValueType(), Out);
4066 Out << ", ";
4067
4068 if (const Constant *Resolver = GI->getResolver()) {
4069 writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
4070 } else {
4071 TypePrinter.print(GI->getType(), Out);
4072 Out << " <<NULL RESOLVER>>";
4073 }
4074
4075 if (GI->hasPartition()) {
4076 Out << ", partition \"";
4077 printEscapedString(GI->getPartition(), Out);
4078 Out << '"';
4079 }
4080
4081 printInfoComment(*GI);
4082 Out << '\n';
4083}
4084
4085void AssemblyWriter::printComdat(const Comdat *C) {
4086 C->print(Out);
4087}
4088
4089void AssemblyWriter::printTypeIdentities() {
4090 if (TypePrinter.empty())
4091 return;
4092
4093 Out << '\n';
4094
4095 // Emit all numbered types.
4096 auto &NumberedTypes = TypePrinter.getNumberedTypes();
4097 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
4098 Out << '%' << I << " = type ";
4099
4100 // Make sure we print out at least one level of the type structure, so
4101 // that we do not get %2 = type %2
4102 TypePrinter.printStructBody(NumberedTypes[I], Out);
4103 Out << '\n';
4104 }
4105
4106 auto &NamedTypes = TypePrinter.getNamedTypes();
4107 for (StructType *NamedType : NamedTypes) {
4108 PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
4109 Out << " = type ";
4110
4111 // Make sure we print out at least one level of the type structure, so
4112 // that we do not get %FILE = type %FILE
4113 TypePrinter.printStructBody(NamedType, Out);
4114 Out << '\n';
4115 }
4116}
4117
4118/// printFunction - Print all aspects of a function.
4119void AssemblyWriter::printFunction(const Function *F) {
4120 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
4121
4122 if (F->isMaterializable())
4123 Out << "; Materializable\n";
4124
4125 const AttributeList &Attrs = F->getAttributes();
4126 if (Attrs.hasFnAttrs()) {
4127 AttributeSet AS = Attrs.getFnAttrs();
4128 std::string AttrStr;
4129
4130 for (const Attribute &Attr : AS) {
4131 if (!Attr.isStringAttribute()) {
4132 if (!AttrStr.empty()) AttrStr += ' ';
4133 AttrStr += Attr.getAsString();
4134 }
4135 }
4136
4137 if (!AttrStr.empty())
4138 Out << "; Function Attrs: " << AttrStr << '\n';
4139 }
4140
4141 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::not_intrinsic)
4142 Out << "; Unknown intrinsic\n";
4143
4144 Machine.incorporateFunction(F);
4145
4146 if (F->isDeclaration()) {
4147 Out << "declare";
4149 F->getAllMetadata(MDs);
4150 printMetadataAttachments(MDs, " ");
4151 Out << ' ';
4152 } else
4153 Out << "define ";
4154
4155 Out << getLinkageNameWithSpace(F->getLinkage());
4156 PrintDSOLocation(*F, Out);
4157 PrintVisibility(F->getVisibility(), Out);
4158 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
4159
4160 // Print the calling convention.
4161 if (F->getCallingConv() != CallingConv::C) {
4162 PrintCallingConv(F->getCallingConv(), Out);
4163 Out << " ";
4164 }
4165
4166 FunctionType *FT = F->getFunctionType();
4167 if (Attrs.hasRetAttrs())
4168 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
4169 TypePrinter.print(F->getReturnType(), Out);
4170 AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
4171 Out << ' ';
4172 WriteAsOperandInternal(Out, F, WriterCtx);
4173 Out << '(';
4174
4175 // Loop over the arguments, printing them...
4176 if (F->isDeclaration() && !IsForDebug) {
4177 // We're only interested in the type here - don't print argument names.
4178 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
4179 // Insert commas as we go... the first arg doesn't get a comma
4180 if (I)
4181 Out << ", ";
4182 // Output type...
4183 TypePrinter.print(FT->getParamType(I), Out);
4184
4185 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
4186 if (ArgAttrs.hasAttributes()) {
4187 Out << ' ';
4188 writeAttributeSet(ArgAttrs);
4189 }
4190 }
4191 } else {
4192 // The arguments are meaningful here, print them in detail.
4193 for (const Argument &Arg : F->args()) {
4194 // Insert commas as we go... the first arg doesn't get a comma
4195 if (Arg.getArgNo() != 0)
4196 Out << ", ";
4197 printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
4198 }
4199 }
4200
4201 // Finish printing arguments...
4202 if (FT->isVarArg()) {
4203 if (FT->getNumParams()) Out << ", ";
4204 Out << "..."; // Output varargs portion of signature!
4205 }
4206 Out << ')';
4207 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
4208 if (!UA.empty())
4209 Out << ' ' << UA;
4210 // We print the function address space if it is non-zero or if we are writing
4211 // a module with a non-zero program address space or if there is no valid
4212 // Module* so that the file can be parsed without the datalayout string.
4213 const Module *Mod = F->getParent();
4214 if (F->getAddressSpace() != 0 || !Mod ||
4215 Mod->getDataLayout().getProgramAddressSpace() != 0)
4216 Out << " addrspace(" << F->getAddressSpace() << ")";
4217 if (Attrs.hasFnAttrs())
4218 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
4219 if (F->hasSection()) {
4220 Out << " section \"";
4221 printEscapedString(F->getSection(), Out);
4222 Out << '"';
4223 }
4224 if (F->hasPartition()) {
4225 Out << " partition \"";
4226 printEscapedString(F->getPartition(), Out);
4227 Out << '"';
4228 }
4229 maybePrintComdat(Out, *F);
4230 if (MaybeAlign A = F->getAlign())
4231 Out << " align " << A->value();
4232 if (F->hasGC())
4233 Out << " gc \"" << F->getGC() << '"';
4234 if (F->hasPrefixData()) {
4235 Out << " prefix ";
4236 writeOperand(F->getPrefixData(), true);
4237 }
4238 if (F->hasPrologueData()) {
4239 Out << " prologue ";
4240 writeOperand(F->getPrologueData(), true);
4241 }
4242 if (F->hasPersonalityFn()) {
4243 Out << " personality ";
4244 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
4245 }
4246
4247 if (PrintProfData) {
4248 if (auto *MDProf = F->getMetadata(LLVMContext::MD_prof)) {
4249 Out << " ";
4250 MDProf->print(Out, TheModule, /*IsForDebug=*/true);
4251 }
4252 }
4253
4254 if (F->isDeclaration()) {
4255 Out << '\n';
4256 } else {
4258 F->getAllMetadata(MDs);
4259 printMetadataAttachments(MDs, " ");
4260
4261 Out << " {";
4262 // Output all of the function's basic blocks.
4263 for (const BasicBlock &BB : *F)
4264 printBasicBlock(&BB);
4265
4266 // Output the function's use-lists.
4267 printUseLists(F);
4268
4269 Out << "}\n";
4270 }
4271
4272 Machine.purgeFunction();
4273}
4274
4275/// printArgument - This member is called for every argument that is passed into
4276/// the function. Simply print it out
4277void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
4278 // Output type...
4279 TypePrinter.print(Arg->getType(), Out);
4280
4281 // Output parameter attributes list
4282 if (Attrs.hasAttributes()) {
4283 Out << ' ';
4284 writeAttributeSet(Attrs);
4285 }
4286
4287 // Output name, if available...
4288 if (Arg->hasName()) {
4289 Out << ' ';
4290 PrintLLVMName(Out, Arg);
4291 } else {
4292 int Slot = Machine.getLocalSlot(Arg);
4293 assert(Slot != -1 && "expect argument in function here");
4294 Out << " %" << Slot;
4295 }
4296}
4297
4298/// printBasicBlock - This member is called for each basic block in a method.
4299void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
4300 bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
4301 if (BB->hasName()) { // Print out the label if it exists...
4302 Out << "\n";
4303 PrintLLVMName(Out, BB->getName(), LabelPrefix);
4304 Out << ':';
4305 } else if (!IsEntryBlock) {
4306 Out << "\n";
4307 int Slot = Machine.getLocalSlot(BB);
4308 if (Slot != -1)
4309 Out << Slot << ":";
4310 else
4311 Out << "<badref>:";
4312 }
4313
4314 if (!IsEntryBlock) {
4315 // Output predecessors for the block.
4316 Out.PadToColumn(50);
4317 Out << ";";
4318 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
4319
4320 if (PI == PE) {
4321 Out << " No predecessors!";
4322 } else {
4323 Out << " preds = ";
4324 writeOperand(*PI, false);
4325 for (++PI; PI != PE; ++PI) {
4326 Out << ", ";
4327 writeOperand(*PI, false);
4328 }
4329 }
4330 }
4331
4332 Out << "\n";
4333
4334 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
4335
4336 // Output all of the instructions in the basic block...
4337 for (const Instruction &I : *BB) {
4338 for (const DbgRecord &DR : I.getDbgRecordRange())
4339 printDbgRecordLine(DR);
4340 printInstructionLine(I);
4341 }
4342
4343 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
4344}
4345
4346/// printInstructionLine - Print an instruction and a newline character.
4347void AssemblyWriter::printInstructionLine(const Instruction &I) {
4348 printInstruction(I);
4349 Out << '\n';
4350}
4351
4352/// printGCRelocateComment - print comment after call to the gc.relocate
4353/// intrinsic indicating base and derived pointer names.
4354void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
4355 Out << " ; (";
4356 writeOperand(Relocate.getBasePtr(), false);
4357 Out << ", ";
4358 writeOperand(Relocate.getDerivedPtr(), false);
4359 Out << ")";
4360}
4361
4362/// printInfoComment - Print a little comment after the instruction indicating
4363/// which slot it occupies.
4364void AssemblyWriter::printInfoComment(const Value &V) {
4365 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
4366 printGCRelocateComment(*Relocate);
4367
4368 if (AnnotationWriter) {
4369 AnnotationWriter->printInfoComment(V, Out);
4370 }
4371
4372 if (PrintInstDebugLocs) {
4373 if (auto *I = dyn_cast<Instruction>(&V)) {
4374 if (I->getDebugLoc()) {
4375 Out << " ; ";
4376 I->getDebugLoc().print(Out);
4377 }
4378 }
4379 }
4380 if (PrintProfData) {
4381 if (auto *I = dyn_cast<Instruction>(&V)) {
4382 if (auto *MD = I->getMetadata(LLVMContext::MD_prof)) {
4383 Out << " ; ";
4384 MD->print(Out, TheModule, /*IsForDebug=*/true);
4385 }
4386 }
4387 }
4388
4389 if (PrintInstAddrs)
4390 Out << " ; " << &V;
4391}
4392
4393static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
4394 raw_ostream &Out) {
4395 // We print the address space of the call if it is non-zero.
4396 if (Operand == nullptr) {
4397 Out << " <cannot get addrspace!>";
4398 return;
4399 }
4400 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
4401 bool PrintAddrSpace = CallAddrSpace != 0;
4402 if (!PrintAddrSpace) {
4403 const Module *Mod = getModuleFromVal(I);
4404 // We also print it if it is zero but not equal to the program address space
4405 // or if we can't find a valid Module* to make it possible to parse
4406 // the resulting file even without a datalayout string.
4407 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
4408 PrintAddrSpace = true;
4409 }
4410 if (PrintAddrSpace)
4411 Out << " addrspace(" << CallAddrSpace << ")";
4412}
4413
4414// This member is called for each Instruction in a function..
4415void AssemblyWriter::printInstruction(const Instruction &I) {
4416 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
4417
4418 // Print out indentation for an instruction.
4419 Out << " ";
4420
4421 // Print out name if it exists...
4422 if (I.hasName()) {
4423 PrintLLVMName(Out, &I);
4424 Out << " = ";
4425 } else if (!I.getType()->isVoidTy()) {
4426 // Print out the def slot taken.
4427 int SlotNum = Machine.getLocalSlot(&I);
4428 if (SlotNum == -1)
4429 Out << "<badref> = ";
4430 else
4431 Out << '%' << SlotNum << " = ";
4432 }
4433
4434 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4435 if (CI->isMustTailCall())
4436 Out << "musttail ";
4437 else if (CI->isTailCall())
4438 Out << "tail ";
4439 else if (CI->isNoTailCall())
4440 Out << "notail ";
4441 }
4442
4443 // Print out the opcode...
4444 Out << I.getOpcodeName();
4445
4446 // If this is an atomic load or store, print out the atomic marker.
4447 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
4448 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
4449 Out << " atomic";
4450
4451 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
4452 Out << " weak";
4453
4454 // If this is a volatile operation, print out the volatile marker.
4455 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
4456 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
4457 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
4458 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
4459 Out << " volatile";
4460
4461 // Print out optimization information.
4462 WriteOptimizationInfo(Out, &I);
4463
4464 // Print out the compare instruction predicates
4465 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
4466 Out << ' ' << CI->getPredicate();
4467
4468 // Print out the atomicrmw operation
4469 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
4470 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
4471
4472 // Print out the type of the operands...
4473 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
4474
4475 // Special case conditional branches to swizzle the condition out to the front
4476 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
4477 const BranchInst &BI(cast<BranchInst>(I));
4478 Out << ' ';
4479 writeOperand(BI.getCondition(), true);
4480 Out << ", ";
4481 writeOperand(BI.getSuccessor(0), true);
4482 Out << ", ";
4483 writeOperand(BI.getSuccessor(1), true);
4484
4485 } else if (isa<SwitchInst>(I)) {
4486 const SwitchInst& SI(cast<SwitchInst>(I));
4487 // Special case switch instruction to get formatting nice and correct.
4488 Out << ' ';
4489 writeOperand(SI.getCondition(), true);
4490 Out << ", ";
4491 writeOperand(SI.getDefaultDest(), true);
4492 Out << " [";
4493 for (auto Case : SI.cases()) {
4494 Out << "\n ";
4495 writeOperand(Case.getCaseValue(), true);
4496 Out << ", ";
4497 writeOperand(Case.getCaseSuccessor(), true);
4498 }
4499 Out << "\n ]";
4500 } else if (isa<IndirectBrInst>(I)) {
4501 // Special case indirectbr instruction to get formatting nice and correct.
4502 Out << ' ';
4503 writeOperand(Operand, true);
4504 Out << ", [";
4505
4506 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
4507 if (i != 1)
4508 Out << ", ";
4509 writeOperand(I.getOperand(i), true);
4510 }
4511 Out << ']';
4512 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
4513 Out << ' ';
4514 TypePrinter.print(I.getType(), Out);
4515 Out << ' ';
4516
4517 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
4518 if (op) Out << ", ";
4519 Out << "[ ";
4520 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
4521 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
4522 }
4523 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
4524 Out << ' ';
4525 writeOperand(I.getOperand(0), true);
4526 for (unsigned i : EVI->indices())
4527 Out << ", " << i;
4528 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
4529 Out << ' ';
4530 writeOperand(I.getOperand(0), true); Out << ", ";
4531 writeOperand(I.getOperand(1), true);
4532 for (unsigned i : IVI->indices())
4533 Out << ", " << i;
4534 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
4535 Out << ' ';
4536 TypePrinter.print(I.getType(), Out);
4537 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4538 Out << '\n';
4539
4540 if (LPI->isCleanup())
4541 Out << " cleanup";
4542
4543 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4544 if (i != 0 || LPI->isCleanup()) Out << "\n";
4545 if (LPI->isCatch(i))
4546 Out << " catch ";
4547 else
4548 Out << " filter ";
4549
4550 writeOperand(LPI->getClause(i), true);
4551 }
4552 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
4553 Out << " within ";
4554 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
4555 Out << " [";
4556 unsigned Op = 0;
4557 for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4558 if (Op > 0)
4559 Out << ", ";
4560 writeOperand(PadBB, /*PrintType=*/true);
4561 ++Op;
4562 }
4563 Out << "] unwind ";
4564 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4565 writeOperand(UnwindDest, /*PrintType=*/true);
4566 else
4567 Out << "to caller";
4568 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
4569 Out << " within ";
4570 writeOperand(FPI->getParentPad(), /*PrintType=*/false);
4571 Out << " [";
4572 for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
4573 if (Op > 0)
4574 Out << ", ";
4575 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
4576 }
4577 Out << ']';
4578 } else if (isa<ReturnInst>(I) && !Operand) {
4579 Out << " void";
4580 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
4581 Out << " from ";
4582 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4583
4584 Out << " to ";
4585 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4586 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
4587 Out << " from ";
4588 writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4589
4590 Out << " unwind ";
4591 if (CRI->hasUnwindDest())
4592 writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4593 else
4594 Out << "to caller";
4595 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4596 // Print the calling convention being used.
4597 if (CI->getCallingConv() != CallingConv::C) {
4598 Out << " ";
4599 PrintCallingConv(CI->getCallingConv(), Out);
4600 }
4601
4602 Operand = CI->getCalledOperand();
4603 FunctionType *FTy = CI->getFunctionType();
4604 Type *RetTy = FTy->getReturnType();
4605 const AttributeList &PAL = CI->getAttributes();
4606
4607 if (PAL.hasRetAttrs())
4608 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4609
4610 // Only print addrspace(N) if necessary:
4611 maybePrintCallAddrSpace(Operand, &I, Out);
4612
4613 // If possible, print out the short form of the call instruction. We can
4614 // only do this if the first argument is a pointer to a nonvararg function,
4615 // and if the return type is not a pointer to a function.
4616 Out << ' ';
4617 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4618 Out << ' ';
4619 writeOperand(Operand, false);
4620 Out << '(';
4621 for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
4622 if (op > 0)
4623 Out << ", ";
4624 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
4625 }
4626
4627 // Emit an ellipsis if this is a musttail call in a vararg function. This
4628 // is only to aid readability, musttail calls forward varargs by default.
4629 if (CI->isMustTailCall() && CI->getParent() &&
4630 CI->getParent()->getParent() &&
4631 CI->getParent()->getParent()->isVarArg()) {
4632 if (CI->arg_size() > 0)
4633 Out << ", ";
4634 Out << "...";
4635 }
4636
4637 Out << ')';
4638 if (PAL.hasFnAttrs())
4639 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4640
4641 writeOperandBundles(CI);
4642 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4643 Operand = II->getCalledOperand();
4644 FunctionType *FTy = II->getFunctionType();
4645 Type *RetTy = FTy->getReturnType();
4646 const AttributeList &PAL = II->getAttributes();
4647
4648 // Print the calling convention being used.
4649 if (II->getCallingConv() != CallingConv::C) {
4650 Out << " ";
4651 PrintCallingConv(II->getCallingConv(), Out);
4652 }
4653
4654 if (PAL.hasRetAttrs())
4655 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4656
4657 // Only print addrspace(N) if necessary:
4658 maybePrintCallAddrSpace(Operand, &I, Out);
4659
4660 // If possible, print out the short form of the invoke instruction. We can
4661 // only do this if the first argument is a pointer to a nonvararg function,
4662 // and if the return type is not a pointer to a function.
4663 //
4664 Out << ' ';
4665 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4666 Out << ' ';
4667 writeOperand(Operand, false);
4668 Out << '(';
4669 for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
4670 if (op)
4671 Out << ", ";
4672 writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
4673 }
4674
4675 Out << ')';
4676 if (PAL.hasFnAttrs())
4677 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4678
4679 writeOperandBundles(II);
4680
4681 Out << "\n to ";
4682 writeOperand(II->getNormalDest(), true);
4683 Out << " unwind ";
4684 writeOperand(II->getUnwindDest(), true);
4685 } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4686 Operand = CBI->getCalledOperand();
4687 FunctionType *FTy = CBI->getFunctionType();
4688 Type *RetTy = FTy->getReturnType();
4689 const AttributeList &PAL = CBI->getAttributes();
4690
4691 // Print the calling convention being used.
4692 if (CBI->getCallingConv() != CallingConv::C) {
4693 Out << " ";
4694 PrintCallingConv(CBI->getCallingConv(), Out);
4695 }
4696
4697 if (PAL.hasRetAttrs())
4698 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4699
4700 // If possible, print out the short form of the callbr instruction. We can
4701 // only do this if the first argument is a pointer to a nonvararg function,
4702 // and if the return type is not a pointer to a function.
4703 //
4704 Out << ' ';
4705 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4706 Out << ' ';
4707 writeOperand(Operand, false);
4708 Out << '(';
4709 for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
4710 if (op)
4711 Out << ", ";
4712 writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
4713 }
4714
4715 Out << ')';
4716 if (PAL.hasFnAttrs())
4717 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
4718
4719 writeOperandBundles(CBI);
4720
4721 Out << "\n to ";
4722 writeOperand(CBI->getDefaultDest(), true);
4723 Out << " [";
4724 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
4725 if (i != 0)
4726 Out << ", ";
4727 writeOperand(CBI->getIndirectDest(i), true);
4728 }
4729 Out << ']';
4730 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4731 Out << ' ';
4732 if (AI->isUsedWithInAlloca())
4733 Out << "inalloca ";
4734 if (AI->isSwiftError())
4735 Out << "swifterror ";
4736 TypePrinter.print(AI->getAllocatedType(), Out);
4737
4738 // Explicitly write the array size if the code is broken, if it's an array
4739 // allocation, or if the type is not canonical for scalar allocations. The
4740 // latter case prevents the type from mutating when round-tripping through
4741 // assembly.
4742 if (!AI->getArraySize() || AI->isArrayAllocation() ||
4743 !AI->getArraySize()->getType()->isIntegerTy(32)) {
4744 Out << ", ";
4745 writeOperand(AI->getArraySize(), true);
4746 }
4747 if (MaybeAlign A = AI->getAlign()) {
4748 Out << ", align " << A->value();
4749 }
4750
4751 unsigned AddrSpace = AI->getAddressSpace();
4752 if (AddrSpace != 0) {
4753 Out << ", addrspace(" << AddrSpace << ')';
4754 }
4755 } else if (isa<CastInst>(I)) {
4756 if (Operand) {
4757 Out << ' ';
4758 writeOperand(Operand, true); // Work with broken code
4759 }
4760 Out << " to ";
4761 TypePrinter.print(I.getType(), Out);
4762 } else if (isa<VAArgInst>(I)) {
4763 if (Operand) {
4764 Out << ' ';
4765 writeOperand(Operand, true); // Work with broken code
4766 }
4767 Out << ", ";
4768 TypePrinter.print(I.getType(), Out);
4769 } else if (Operand) { // Print the normal way.
4770 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4771 Out << ' ';
4772 TypePrinter.print(GEP->getSourceElementType(), Out);
4773 Out << ',';
4774 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4775 Out << ' ';
4776 TypePrinter.print(LI->getType(), Out);
4777 Out << ',';
4778 }
4779
4780 // PrintAllTypes - Instructions who have operands of all the same type
4781 // omit the type from all but the first operand. If the instruction has
4782 // different type operands (for example br), then they are all printed.
4783 bool PrintAllTypes = false;
4784 Type *TheType = Operand->getType();
4785
4786 // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4787 // types.
4788 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4789 isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
4790 isa<AtomicRMWInst>(I)) {
4791 PrintAllTypes = true;
4792 } else {
4793 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4794 Operand = I.getOperand(i);
4795 // note that Operand shouldn't be null, but the test helps make dump()
4796 // more tolerant of malformed IR
4797 if (Operand && Operand->getType() != TheType) {
4798 PrintAllTypes = true; // We have differing types! Print them all!
4799 break;
4800 }
4801 }
4802 }
4803
4804 if (!PrintAllTypes) {
4805 Out << ' ';
4806 TypePrinter.print(TheType, Out);
4807 }
4808
4809 Out << ' ';
4810 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4811 if (i) Out << ", ";
4812 writeOperand(I.getOperand(i), PrintAllTypes);
4813 }
4814 }
4815
4816 // Print atomic ordering/alignment for memory operations
4817 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4818 if (LI->isAtomic())
4819 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4820 if (MaybeAlign A = LI->getAlign())
4821 Out << ", align " << A->value();
4822 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4823 if (SI->isAtomic())
4824 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4825 if (MaybeAlign A = SI->getAlign())
4826 Out << ", align " << A->value();
4827 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4828 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4829 CXI->getFailureOrdering(), CXI->getSyncScopeID());
4830 Out << ", align " << CXI->getAlign().value();
4831 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4832 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4833 RMWI->getSyncScopeID());
4834 Out << ", align " << RMWI->getAlign().value();
4835 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4836 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4837 } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4838 PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
4839 }
4840
4841 // Print Metadata info.
4843 I.getAllMetadata(InstMD);
4844 printMetadataAttachments(InstMD, ", ");
4845
4846 // Print a nice comment.
4847 printInfoComment(I);
4848}
4849
4850void AssemblyWriter::printDbgMarker(const DbgMarker &Marker) {
4851 // There's no formal representation of a DbgMarker -- print purely as a
4852 // debugging aid.
4853 for (const DbgRecord &DPR : Marker.StoredDbgRecords) {
4854 printDbgRecord(DPR);
4855 Out << "\n";
4856 }
4857
4858 Out << " DbgMarker -> { ";
4859 printInstruction(*Marker.MarkedInstr);
4860 Out << " }";
4861}
4862
4863void AssemblyWriter::printDbgRecord(const DbgRecord &DR) {
4864 if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR))
4865 printDbgVariableRecord(*DVR);
4866 else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR))
4867 printDbgLabelRecord(*DLR);
4868 else
4869 llvm_unreachable("Unexpected DbgRecord kind");
4870}
4871
4872void AssemblyWriter::printDbgVariableRecord(const DbgVariableRecord &DVR) {
4873 auto WriterCtx = getContext();
4874 Out << "#dbg_";
4875 switch (DVR.getType()) {
4876 case DbgVariableRecord::LocationType::Value:
4877 Out << "value";
4878 break;
4879 case DbgVariableRecord::LocationType::Declare:
4880 Out << "declare";
4881 break;
4882 case DbgVariableRecord::LocationType::Assign:
4883 Out << "assign";
4884 break;
4885 default:
4887 "Tried to print a DbgVariableRecord with an invalid LocationType!");
4888 }
4889
4890 auto PrintOrNull = [&](Metadata *M) {
4891 if (!M)
4892 Out << "(null)";
4893 else
4894 WriteAsOperandInternal(Out, M, WriterCtx, true);
4895 };
4896
4897 Out << "(";
4898 PrintOrNull(DVR.getRawLocation());
4899 Out << ", ";
4900 PrintOrNull(DVR.getRawVariable());
4901 Out << ", ";
4902 PrintOrNull(DVR.getRawExpression());
4903 Out << ", ";
4904 if (DVR.isDbgAssign()) {
4905 PrintOrNull(DVR.getRawAssignID());
4906 Out << ", ";
4907 PrintOrNull(DVR.getRawAddress());
4908 Out << ", ";
4909 PrintOrNull(DVR.getRawAddressExpression());
4910 Out << ", ";
4911 }
4912 PrintOrNull(DVR.getDebugLoc().getAsMDNode());
4913 Out << ")";
4914}
4915
4916/// printDbgRecordLine - Print a DbgRecord with indentation and a newline
4917/// character.
4918void AssemblyWriter::printDbgRecordLine(const DbgRecord &DR) {
4919 // Print lengthier indentation to bring out-of-line with instructions.
4920 Out << " ";
4921 printDbgRecord(DR);
4922 Out << '\n';
4923}
4924
4925void AssemblyWriter::printDbgLabelRecord(const DbgLabelRecord &Label) {
4926 auto WriterCtx = getContext();
4927 Out << "#dbg_label(";
4928 WriteAsOperandInternal(Out, Label.getRawLabel(), WriterCtx, true);
4929 Out << ", ";
4930 WriteAsOperandInternal(Out, Label.getDebugLoc(), WriterCtx, true);
4931 Out << ")";
4932}
4933
4934void AssemblyWriter::printMetadataAttachments(
4935 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4936 StringRef Separator) {
4937 if (MDs.empty())
4938 return;
4939
4940 if (MDNames.empty())
4941 MDs[0].second->getContext().getMDKindNames(MDNames);
4942
4943 auto WriterCtx = getContext();
4944 for (const auto &I : MDs) {
4945 unsigned Kind = I.first;
4946 Out << Separator;
4947 if (Kind < MDNames.size()) {
4948 Out << "!";
4949 printMetadataIdentifier(MDNames[Kind], Out);
4950 } else
4951 Out << "!<unknown kind #" << Kind << ">";
4952 Out << ' ';
4953 WriteAsOperandInternal(Out, I.second, WriterCtx);
4954 }
4955}
4956
4957void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4958 Out << '!' << Slot << " = ";
4959 printMDNodeBody(Node);
4960 Out << "\n";
4961}
4962
4963void AssemblyWriter::writeAllMDNodes() {
4965 Nodes.resize(Machine.mdn_size());
4966 for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
4967 Nodes[I.second] = cast<MDNode>(I.first);
4968
4969 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4970 writeMDNode(i, Nodes[i]);
4971 }
4972}
4973
4974void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4975 auto WriterCtx = getContext();
4976 WriteMDNodeBodyInternal(Out, Node, WriterCtx);
4977}
4978
4979void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4980 if (!Attr.isTypeAttribute()) {
4981 Out << Attr.getAsString(InAttrGroup);
4982 return;
4983 }
4984
4986 if (Type *Ty = Attr.getValueAsType()) {
4987 Out << '(';
4988 TypePrinter.print(Ty, Out);
4989 Out << ')';
4990 }
4991}
4992
4993void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4994 bool InAttrGroup) {
4995 bool FirstAttr = true;
4996 for (const auto &Attr : AttrSet) {
4997 if (!FirstAttr)
4998 Out << ' ';
4999 writeAttribute(Attr, InAttrGroup);
5000 FirstAttr = false;
5001 }
5002}
5003
5004void AssemblyWriter::writeAllAttributeGroups() {
5005 std::vector<std::pair<AttributeSet, unsigned>> asVec;
5006 asVec.resize(Machine.as_size());
5007
5008 for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
5009 asVec[I.second] = I;
5010
5011 for (const auto &I : asVec)
5012 Out << "attributes #" << I.second << " = { "
5013 << I.first.getAsString(true) << " }\n";
5014}
5015
5016void AssemblyWriter::printUseListOrder(const Value *V,
5017 const std::vector<unsigned> &Shuffle) {
5018 bool IsInFunction = Machine.getFunction();
5019 if (IsInFunction)
5020 Out << " ";
5021
5022 Out << "uselistorder";
5023 if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
5024 Out << "_bb ";
5025 writeOperand(BB->getParent(), false);
5026 Out << ", ";
5027 writeOperand(BB, false);
5028 } else {
5029 Out << " ";
5030 writeOperand(V, true);
5031 }
5032
5033 assert(Shuffle.size() >= 2 && "Shuffle too small");
5034 Out << ", { " << llvm::interleaved(Shuffle) << " }\n";
5035}
5036
5037void AssemblyWriter::printUseLists(const Function *F) {
5038 auto It = UseListOrders.find(F);
5039 if (It == UseListOrders.end())
5040 return;
5041
5042 Out << "\n; uselistorder directives\n";
5043 for (const auto &Pair : It->second)
5044 printUseListOrder(Pair.first, Pair.second);
5045}
5046
5047//===----------------------------------------------------------------------===//
5048// External Interface declarations
5049//===----------------------------------------------------------------------===//
5050
5052 bool ShouldPreserveUseListOrder,
5053 bool IsForDebug) const {
5054 SlotTracker SlotTable(this->getParent());
5056 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
5057 IsForDebug,
5058 ShouldPreserveUseListOrder);
5059 W.printFunction(this);
5060}
5061
5063 bool ShouldPreserveUseListOrder,
5064 bool IsForDebug) const {
5065 SlotTracker SlotTable(this->getParent());
5067 AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
5068 IsForDebug,
5069 ShouldPreserveUseListOrder);
5070 W.printBasicBlock(this);
5071}
5072
5074 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
5075 SlotTracker SlotTable(this);
5077 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
5078 ShouldPreserveUseListOrder);
5079 W.printModule(this);
5080}
5081
5082void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
5083 SlotTracker SlotTable(getParent());
5085 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
5086 W.printNamedMDNode(this);
5087}
5088
5090 bool IsForDebug) const {
5091 std::optional<SlotTracker> LocalST;
5092 SlotTracker *SlotTable;
5093 if (auto *ST = MST.getMachine())
5094 SlotTable = ST;
5095 else {
5096 LocalST.emplace(getParent());
5097 SlotTable = &*LocalST;
5098 }
5099
5101 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
5102 W.printNamedMDNode(this);
5103}
5104
5105void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
5107 ROS << " = comdat ";
5108
5109 switch (getSelectionKind()) {
5110 case Comdat::Any:
5111 ROS << "any";
5112 break;
5113 case Comdat::ExactMatch:
5114 ROS << "exactmatch";
5115 break;
5116 case Comdat::Largest:
5117 ROS << "largest";
5118 break;
5120 ROS << "nodeduplicate";
5121 break;
5122 case Comdat::SameSize:
5123 ROS << "samesize";
5124 break;
5125 }
5126
5127 ROS << '\n';
5128}
5129
5130void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
5131 TypePrinting TP;
5132 TP.print(const_cast<Type*>(this), OS);
5133
5134 if (NoDetails)
5135 return;
5136
5137 // If the type is a named struct type, print the body as well.
5138 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
5139 if (!STy->isLiteral()) {
5140 OS << " = type ";
5141 TP.printStructBody(STy, OS);
5142 }
5143}
5144
5145static bool isReferencingMDNode(const Instruction &I) {
5146 if (const auto *CI = dyn_cast<CallInst>(&I))
5147 if (Function *F = CI->getCalledFunction())
5148 if (F->isIntrinsic())
5149 for (auto &Op : I.operands())
5150 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
5151 if (isa<MDNode>(V->getMetadata()))
5152 return true;
5153 return false;
5154}
5155
5156void DbgMarker::print(raw_ostream &ROS, bool IsForDebug) const {
5157
5158 ModuleSlotTracker MST(getModuleFromDPI(this), true);
5159 print(ROS, MST, IsForDebug);
5160}
5161
5162void DbgVariableRecord::print(raw_ostream &ROS, bool IsForDebug) const {
5163
5164 ModuleSlotTracker MST(getModuleFromDPI(this), true);
5165 print(ROS, MST, IsForDebug);
5166}
5167
5169 bool IsForDebug) const {
5171 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5172 SlotTracker &SlotTable =
5173 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5174 auto incorporateFunction = [&](const Function *F) {
5175 if (F)
5176 MST.incorporateFunction(*F);
5177 };
5178 incorporateFunction(getParent() ? getParent()->getParent() : nullptr);
5179 AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5180 W.printDbgMarker(*this);
5181}
5182
5183void DbgLabelRecord::print(raw_ostream &ROS, bool IsForDebug) const {
5184
5185 ModuleSlotTracker MST(getModuleFromDPI(this), true);
5186 print(ROS, MST, IsForDebug);
5187}
5188
5190 bool IsForDebug) const {
5192 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5193 SlotTracker &SlotTable =
5194 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5195 auto incorporateFunction = [&](const Function *F) {
5196 if (F)
5197 MST.incorporateFunction(*F);
5198 };
5199 incorporateFunction(Marker && Marker->getParent()
5200 ? Marker->getParent()->getParent()
5201 : nullptr);
5202 AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5203 W.printDbgVariableRecord(*this);
5204}
5205
5207 bool IsForDebug) const {
5209 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5210 SlotTracker &SlotTable =
5211 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5212 auto incorporateFunction = [&](const Function *F) {
5213 if (F)
5214 MST.incorporateFunction(*F);
5215 };
5216 incorporateFunction(Marker->getParent() ? Marker->getParent()->getParent()
5217 : nullptr);
5218 AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
5219 W.printDbgLabelRecord(*this);
5220}
5221
5222void Value::print(raw_ostream &ROS, bool IsForDebug) const {
5223 bool ShouldInitializeAllMetadata = false;
5224 if (auto *I = dyn_cast<Instruction>(this))
5225 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
5226 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
5227 ShouldInitializeAllMetadata = true;
5228
5229 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
5230 print(ROS, MST, IsForDebug);
5231}
5232
5234 bool IsForDebug) const {
5236 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
5237 SlotTracker &SlotTable =
5238 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
5239 auto incorporateFunction = [&](const Function *F) {
5240 if (F)
5241 MST.incorporateFunction(*F);
5242 };
5243
5244 if (const Instruction *I = dyn_cast<Instruction>(this)) {
5245 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
5246 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
5247 W.printInstruction(*I);
5248 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
5249 incorporateFunction(BB->getParent());
5250 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
5251 W.printBasicBlock(BB);
5252 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
5253 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
5254 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
5255 W.printGlobal(V);
5256 else if (const Function *F = dyn_cast<Function>(GV))
5257 W.printFunction(F);
5258 else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
5259 W.printAlias(A);
5260 else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
5261 W.printIFunc(I);
5262 else
5263 llvm_unreachable("Unknown GlobalValue to print out!");
5264 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
5265 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
5266 } else if (const Constant *C = dyn_cast<Constant>(this)) {
5267 TypePrinting TypePrinter;
5268 TypePrinter.print(C->getType(), OS);
5269 OS << ' ';
5270 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
5271 WriteConstantInternal(OS, C, WriterCtx);
5272 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
5273 this->printAsOperand(OS, /* PrintType */ true, MST);
5274 } else {
5275 llvm_unreachable("Unknown value to print out!");
5276 }
5277}
5278
5279/// Print without a type, skipping the TypePrinting object.
5280///
5281/// \return \c true iff printing was successful.
5282static bool printWithoutType(const Value &V, raw_ostream &O,
5283 SlotTracker *Machine, const Module *M) {
5284 if (V.hasName() || isa<GlobalValue>(V) ||
5285 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
5286 AsmWriterContext WriterCtx(nullptr, Machine, M);
5287 WriteAsOperandInternal(O, &V, WriterCtx);
5288 return true;
5289 }
5290 return false;
5291}
5292
5293static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
5294 ModuleSlotTracker &MST) {
5295 TypePrinting TypePrinter(MST.getModule());
5296 if (PrintType) {
5297 TypePrinter.print(V.getType(), O);
5298 O << ' ';
5299 }
5300
5301 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
5302 WriteAsOperandInternal(O, &V, WriterCtx);
5303}
5304
5305void Value::printAsOperand(raw_ostream &O, bool PrintType,
5306 const Module *M) const {
5307 if (!M)
5308 M = getModuleFromVal(this);
5309
5310 if (!PrintType)
5311 if (printWithoutType(*this, O, nullptr, M))
5312 return;
5313
5315 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
5316 ModuleSlotTracker MST(Machine, M);
5317 printAsOperandImpl(*this, O, PrintType, MST);
5318}
5319
5320void Value::printAsOperand(raw_ostream &O, bool PrintType,
5321 ModuleSlotTracker &MST) const {
5322 if (!PrintType)
5323 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
5324 return;
5325
5326 printAsOperandImpl(*this, O, PrintType, MST);
5327}
5328
5329/// Recursive version of printMetadataImpl.
5330static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
5331 AsmWriterContext &WriterCtx) {
5333 WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
5334
5335 auto *N = dyn_cast<MDNode>(&MD);
5336 if (!N || isa<DIExpression>(MD))
5337 return;
5338
5339 OS << " = ";
5340 WriteMDNodeBodyInternal(OS, N, WriterCtx);
5341}
5342
5343namespace {
5344struct MDTreeAsmWriterContext : public AsmWriterContext {
5345 unsigned Level;
5346 // {Level, Printed string}
5347 using EntryTy = std::pair<unsigned, std::string>;
5349
5350 // Used to break the cycle in case there is any.
5352
5353 raw_ostream &MainOS;
5354
5355 MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
5356 raw_ostream &OS, const Metadata *InitMD)
5357 : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
5358
5359 void onWriteMetadataAsOperand(const Metadata *MD) override {
5360 if (!Visited.insert(MD).second)
5361 return;
5362
5363 std::string Str;
5365 ++Level;
5366 // A placeholder entry to memorize the correct
5367 // position in buffer.
5368 Buffer.emplace_back(std::make_pair(Level, ""));
5369 unsigned InsertIdx = Buffer.size() - 1;
5370
5371 printMetadataImplRec(SS, *MD, *this);
5372 Buffer[InsertIdx].second = std::move(SS.str());
5373 --Level;
5374 }
5375
5376 ~MDTreeAsmWriterContext() {
5377 for (const auto &Entry : Buffer) {
5378 MainOS << "\n";
5379 unsigned NumIndent = Entry.first * 2U;
5380 MainOS.indent(NumIndent) << Entry.second;
5381 }
5382 }
5383};
5384} // end anonymous namespace
5385
5386static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
5387 ModuleSlotTracker &MST, const Module *M,
5388 bool OnlyAsOperand, bool PrintAsTree = false) {
5390
5391 TypePrinting TypePrinter(M);
5392
5393 std::unique_ptr<AsmWriterContext> WriterCtx;
5394 if (PrintAsTree && !OnlyAsOperand)
5395 WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
5396 &TypePrinter, MST.getMachine(), M, OS, &MD);
5397 else
5398 WriterCtx =
5399 std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
5400
5401 WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
5402
5403 auto *N = dyn_cast<MDNode>(&MD);
5404 if (OnlyAsOperand || !N || isa<DIExpression>(MD))
5405 return;
5406
5407 OS << " = ";
5408 WriteMDNodeBodyInternal(OS, N, *WriterCtx);
5409}
5410
5412 ModuleSlotTracker MST(M, isa<MDNode>(this));
5413 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
5414}
5415
5417 const Module *M) const {
5418 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
5419}
5420
5422 bool /*IsForDebug*/) const {
5423 ModuleSlotTracker MST(M, isa<MDNode>(this));
5424 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
5425}
5426
5428 const Module *M, bool /*IsForDebug*/) const {
5429 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
5430}
5431
5432void MDNode::printTree(raw_ostream &OS, const Module *M) const {
5433 ModuleSlotTracker MST(M, true);
5434 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5435 /*PrintAsTree=*/true);
5436}
5437
5439 const Module *M) const {
5440 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5441 /*PrintAsTree=*/true);
5442}
5443
5444void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
5445 SlotTracker SlotTable(this);
5447 AssemblyWriter W(OS, SlotTable, this, IsForDebug);
5448 W.printModuleSummaryIndex();
5449}
5450
5452 unsigned UB) const {
5453 SlotTracker *ST = MachineStorage.get();
5454 if (!ST)
5455 return;
5456
5457 for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
5458 if (I.second >= LB && I.second < UB)
5459 L.push_back(std::make_pair(I.second, I.first));
5460}
5461
5462#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5463// Value::dump - allow easy printing of Values from the debugger.
5465void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5466
5467// Value::dump - allow easy printing of Values from the debugger.
5469void DbgMarker::dump() const {
5470 print(dbgs(), /*IsForDebug=*/true);
5471 dbgs() << '\n';
5472}
5473
5474// Value::dump - allow easy printing of Values from the debugger.
5476void DbgRecord::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5477
5478// Type::dump - allow easy printing of Types from the debugger.
5480void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5481
5482// Module::dump() - Allow printing of Modules from the debugger.
5484void Module::dump() const {
5485 print(dbgs(), nullptr,
5486 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
5487}
5488
5489// Allow printing of Comdats from the debugger.
5491void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5492
5493// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
5495void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5496
5498void Metadata::dump() const { dump(nullptr); }
5499
5501void Metadata::dump(const Module *M) const {
5502 print(dbgs(), M, /*IsForDebug=*/true);
5503 dbgs() << '\n';
5504}
5505
5507void MDNode::dumpTree() const { dumpTree(nullptr); }
5508
5510void MDNode::dumpTree(const Module *M) const {
5511 printTree(dbgs(), M);
5512 dbgs() << '\n';
5513}
5514
5515// Allow printing of ModuleSummaryIndex from the debugger.
5517void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
5518#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static void writeDIMacro(raw_ostream &Out, const DIMacro *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2514
static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1975
static void writeDIGlobalVariableExpression(raw_ostream &Out, const DIGlobalVariableExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2666
MapVector< const Value *, unsigned > OrderMap
Definition: AsmWriter.cpp:110
static void PrintCallingConv(unsigned cc, raw_ostream &Out)
Definition: AsmWriter.cpp:338
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2341
static void writeDIFixedPointType(raw_ostream &Out, const DIFixedPointType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2247
static const char * getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K)
Definition: AsmWriter.cpp:3269
static void writeDISubrangeType(raw_ostream &Out, const DISubrangeType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2321
static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, ModuleSlotTracker &MST, const Module *M, bool OnlyAsOperand, bool PrintAsTree=false)
Definition: AsmWriter.cpp:5386
static void WriteOptimizationInfo(raw_ostream &Out, const User *U)
Definition: AsmWriter.cpp:1466
static void writeDIStringType(raw_ostream &Out, const DIStringType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2270
static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT)
Definition: AsmWriter.cpp:3484
static std::vector< unsigned > predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM)
Definition: AsmWriter.cpp:216
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2575
static void orderValue(const Value *V, OrderMap &OM)
Definition: AsmWriter.cpp:124
static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3871
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2231
static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix)
Turn the specified name into an 'LLVM name', which is either prefixed with % (if the string only cont...
Definition: AsmWriter.cpp:476
static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA)
Definition: AsmWriter.cpp:3891
static const char * getWholeProgDevirtResByArgKindName(WholeProgramDevirtResolution::ByArg::Kind K)
Definition: AsmWriter.cpp:3281
static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef< int > Mask)
Definition: AsmWriter.cpp:503
static void writeDIModule(raw_ostream &Out, const DIModule *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2535
static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2394
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2383
static bool isReferencingMDNode(const Instruction &I)
Definition: AsmWriter.cpp:5145
#define CC_VLS_CASE(ABI_VLEN)
static void writeDILabel(raw_ostream &Out, const DILabel *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2610
static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, AsmWriterContext &Ctx)
Definition: AsmWriter.cpp:2704
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2288
static void printMetadataIdentifier(StringRef Name, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3801
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2690
static const Module * getModuleFromDPI(const DbgMarker *Marker)
Definition: AsmWriter.cpp:328
static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, ModuleSlotTracker &MST)
Definition: AsmWriter.cpp:5293
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2676
static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3862
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2440
static const char * getSummaryKindName(GlobalValueSummary::SummaryKind SK)
Definition: AsmWriter.cpp:3407
static OrderMap orderModule(const Module *M)
Definition: AsmWriter.cpp:144
static const char * getVisibilityName(GlobalValue::VisibilityTypes Vis)
Definition: AsmWriter.cpp:3490
static cl::opt< bool > PrintInstDebugLocs("print-inst-debug-locs", cl::Hidden, cl::desc("Pretty print debug locations of instructions when dumping"))
static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD, AsmWriterContext &WriterCtx)
Recursive version of printMetadataImpl.
Definition: AsmWriter.cpp:5330
static SlotTracker * createSlotTracker(const Value *V)
Definition: AsmWriter.cpp:994
static void WriteAPFloatInternal(raw_ostream &Out, const APFloat &APF)
Definition: AsmWriter.cpp:1509
static void writeDILocation(raw_ostream &Out, const DILocation *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2125
static void writeDINamespace(raw_ostream &Out, const DINamespace *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2492
static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2502
static UseListOrderMap predictUseListOrder(const Module *M)
Definition: AsmWriter.cpp:277
static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1602
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2724
static std::string getLinkageName(GlobalValue::LinkageTypes LT)
Definition: AsmWriter.cpp:3453
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2107
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2594
static const char * getTTResKindName(TypeTestResolution::Kind K)
Definition: AsmWriter.cpp:3296
static void writeDITemplateTypeParameter(raw_ostream &Out, const DITemplateTypeParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2550
static const char * getImportTypeName(GlobalValueSummary::ImportKind IK)
Definition: AsmWriter.cpp:3502
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2410
static const Module * getModuleFromVal(const Value *V)
Definition: AsmWriter.cpp:302
static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I, raw_ostream &Out)
Definition: AsmWriter.cpp:4393
static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2171
static void writeDISubrange(raw_ostream &Out, const DISubrange *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2147
static void PrintVisibility(GlobalValue::VisibilityTypes Vis, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3847
static void writeDILexicalBlockFile(raw_ostream &Out, const DILexicalBlockFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2480
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, AsmWriterContext &)
Definition: AsmWriter.cpp:2219
static cl::opt< bool > PrintProfData("print-prof-data", cl::Hidden, cl::desc("Pretty print perf data (branch weights, etc) when dumping"))
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:1863
static void writeDIExpression(raw_ostream &Out, const DIExpression *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2626
static void PrintDSOLocation(const GlobalValue &GV, formatted_raw_ostream &Out)
Definition: AsmWriter.cpp:3856
static cl::opt< bool > PrintInstAddrs("print-inst-addrs", cl::Hidden, cl::desc("Print addresses of instructions when dumping"))
static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2141
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2469
PrefixType
Definition: AsmWriter.cpp:434
@ GlobalPrefix
Definition: AsmWriter.cpp:435
@ LabelPrefix
Definition: AsmWriter.cpp:437
@ LocalPrefix
Definition: AsmWriter.cpp:438
@ NoPrefix
Definition: AsmWriter.cpp:439
@ ComdatPrefix
Definition: AsmWriter.cpp:436
static void maybePrintComdat(formatted_raw_ostream &Out, const GlobalObject &GO)
Definition: AsmWriter.cpp:3903
static bool printWithoutType(const Value &V, raw_ostream &O, SlotTracker *Machine, const Module *M)
Print without a type, skipping the TypePrinting object.
Definition: AsmWriter.cpp:5282
#define ST_DEBUG(X)
Definition: AsmWriter.cpp:1023
static void writeDIArgList(raw_ostream &Out, const DIArgList *N, AsmWriterContext &WriterCtx, bool FromValue=false)
Definition: AsmWriter.cpp:2651
static void writeDITemplateValueParameter(raw_ostream &Out, const DITemplateValueParameter *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2561
static const Value * skipMetadataWrapper(const Value *V)
Look for a value that might be wrapped as metadata, e.g.
Definition: AsmWriter.cpp:117
static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, AsmWriterContext &WriterCtx)
Definition: AsmWriter.cpp:2525
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:390
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:638
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil pretty DXIL Metadata Pretty Printer
return RetTy
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
This file defines the DenseMap class.
@ Default
Definition: DwarfDebug.cpp:86
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint32_t Index
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
#define op(i)
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This file contains an interface for creating legacy passes to print out IR in various granularities.
Module.h This file contains the declarations for the Module class.
This defines the Use class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
if(PassOpts->AAPipeline)
const NodeList & List
Definition: RDFGraph.cpp:200
static bool isDigit(const char C)
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file provides utility classes that use RAII to save and restore values.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:1128
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:6057
bool isNegative() const
Definition: APFloat.h:1449
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition: APFloat.cpp:6115
void toString(SmallVectorImpl< char > &Str, unsigned FormatPrecision=0, unsigned FormatMaxPadding=3, bool TruncateZero=true) const
Definition: APFloat.h:1478
const fltSemantics & getSemantics() const
Definition: APFloat.h:1457
bool isNaN() const
Definition: APFloat.h:1447
bool isSignaling() const
Definition: APFloat.h:1451
APInt bitcastToAPInt() const
Definition: APFloat.h:1353
bool isInfinity() const
Definition: APFloat.h:1446
Class for arbitrary precision integers.
Definition: APInt.h:78
LLVM_ABI APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition: APInt.cpp:644
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1540
LLVM_ABI APInt getHiBits(unsigned numBits) const
Compute an APInt containing numBits highbits from this APInt.
Definition: APInt.cpp:639
Abstract interface of slot tracker storage.
Alias summary information.
const GlobalValueSummary & getAliasee() const
an instruction to allocate memory on the stack
Definition: Instructions.h:64
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
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:506
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:709
static LLVM_ABI StringRef getOperationName(BinOp Op)
LLVM_ABI AttributeSet getFnAttrs() const
The function attributes are returned.
LLVM_ABI std::string getAsString(unsigned Index, bool InAttrGrp=false) const
Return the attributes at the index as a string.
bool hasRetAttrs() const
Return true if attributes exist for the return value.
Definition: Attributes.h:870
LLVM_ABI AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
bool hasFnAttrs() const
Return true the attributes exist for the function.
Definition: Attributes.h:879
LLVM_ABI AttributeSet getParamAttrs(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
bool hasAttributes() const
Return true if attributes exists in this set.
Definition: Attributes.h:427
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
The Attribute is converted to a string of equivalent mnemonic.
Definition: Attributes.cpp:536
LLVM_ABI Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
Definition: Attributes.cpp:372
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
Definition: Attributes.cpp:322
LLVM_ABI bool isTypeAttribute() const
Return true if the attribute is a type attribute.
Definition: Attributes.cpp:360
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
Definition: Attributes.cpp:407
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
LLVM_ABI void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:5062
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:549
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:213
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:248
The address of a basic block.
Definition: Constants.h:899
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:666
LLVM_ABI void print(raw_ostream &OS, bool IsForDebug=false) const
Definition: AsmWriter.cpp:5105
LLVM_ABI StringRef getName() const
Definition: Comdat.cpp:28
LLVM_ABI void dump() const
Definition: AsmWriter.cpp:5491
@ 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
SelectionKind getSelectionKind() const
Definition: Comdat.h:47
ConstantArray - Constant Array Declarations.
Definition: Constants.h:433
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:702
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1120
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:277
This is the shared class of boolean and integer constants.
Definition: Constants.h:87
A signed pointer, in the ptrauth sense.
Definition: Constants.h:1032
This class represents a range of values.
Definition: ConstantRange.h:47
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
This is an important base class in LLVM.
Definition: Constant.h:43
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
Definition: Constants.cpp:1713
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:435
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
Assignment ID.
Basic type, like 'int' or 'float'.
Debug common block.
static LLVM_ABI const char * nameTableKindString(DebugNameTableKind PK)
static LLVM_ABI const char * emissionKindString(DebugEmissionKind EK)
Enumeration value.
A lightweight wrapper around an expression operand.
DWARF expression.
static LLVM_ABI const char * fixedPointKindString(FixedPointKind)
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Debug lexical block.
Debug location.
Macro Info DWARF-like metadata node.
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
Tagged DWARF-like metadata node.
static LLVM_ABI DIFlags splitFlags(DIFlags Flags, SmallVectorImpl< DIFlags > &SplitFlags)
Split up a flags bitfield.
static LLVM_ABI StringRef getFlagString(DIFlags Flag)
DIFlags
Debug info flags.
String type, Fortran CHARACTER(n)
Subprogram description. Uses SubclassData1.
static LLVM_ABI DISPFlags splitFlags(DISPFlags Flags, SmallVectorImpl< DISPFlags > &SplitFlags)
Split up a flags bitfield for easier printing.
static LLVM_ABI StringRef getFlagString(DISPFlags Flag)
DISPFlags
Debug info subprogram flags.
Array subrange.
Type array for a subprogram.
This class represents an Operation in the Expression.
Records a position in IR for a source label (DILabel).
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Definition: AsmWriter.cpp:5183
Per-instruction record of debug-info.
LLVM_ABI void dump() const
Definition: AsmWriter.cpp:5469
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on DbgMarker.
Definition: AsmWriter.cpp:5156
LLVM_ABI const BasicBlock * getParent() const
simple_ilist< DbgRecord > StoredDbgRecords
List of DbgRecords, the non-instruction equivalent of llvm.dbg.
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
DebugLoc getDebugLoc() const
LLVM_ABI void dump() const
Definition: AsmWriter.cpp:5476
DbgMarker * Marker
Marker that this DbgRecord is linked into.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Definition: AsmWriter.cpp:5162
MDNode * getRawAddressExpression() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition: DebugLoc.h:291
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:245
unsigned size() const
Definition: DenseMap.h:120
bool empty() const
Definition: DenseMap.h:119
iterator begin()
Definition: DenseMap.h:78
iterator end()
Definition: DenseMap.h:87
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
This instruction extracts a struct member or array element value from an aggregate value.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition: Operator.h:200
An instruction for ordering other memory operations.
Definition: Instructions.h:429
Function summary information to aid decisions and implementation of importing.
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the function to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:5051
arg_iterator arg_end()
Definition: Function.h:875
arg_iterator arg_begin()
Definition: Function.h:866
Represents calls to the gc.relocate intrinsic.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
Generic tagged DWARF-like metadata node.
const Constant * getAliasee() const
Definition: GlobalAlias.h:87
const Constant * getResolver() const
Definition: GlobalIFunc.h:73
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:114
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
Definition: Metadata.cpp:1561
const Comdat * getComdat() const
Definition: GlobalObject.h:131
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:106
Function and variable summary information to aid decisions and implementation of importing.
SummaryKind
Sububclass discriminator (for dyn_cast<> et al.)
bool hasPartition() const
Definition: GlobalValue.h:311
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
bool hasExternalLinkage() const
Definition: GlobalValue.h:513
bool isDSOLocal() const
Definition: GlobalValue.h:307
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:250
bool isImplicitDSOLocal() const
Definition: GlobalValue.h:300
LinkageTypes getLinkage() const
Definition: GlobalValue.h:548
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:273
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
Definition: GlobalValue.h:357
LLVM_ABI StringRef getPartition() const
Definition: Globals.cpp:222
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:663
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:296
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
LLVM_ABI bool isMaterializable() const
If this function's Module is being lazily streamed in functions from disk or some other source,...
Definition: Globals.cpp:44
UnnamedAddr getUnnamedAddr() const
Definition: GlobalValue.h:230
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
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:277
Type * getValueType() const
Definition: GlobalValue.h:298
Global variable summary information to aid decisions and implementation of importing.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isExternallyInitialized() const
bool hasInitializer() const
Definitions have initializers, declarations don't.
AttributeSet getAttributes() const
Return the attribute set for this global.
std::optional< CodeModel::Model > getCodeModel() const
Get the custom code model of this global if it has one.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This instruction inserts a struct field of array element value into an aggregate value.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
The landingpad instruction holds all of the information necessary to generate correct exception handl...
An instruction for reading from memory.
Definition: Instructions.h:180
Metadata node.
Definition: Metadata.h:1077
LLVM_ABI void printTree(raw_ostream &OS, const Module *M=nullptr) const
Print in tree shape.
Definition: AsmWriter.cpp:5432
LLVM_ABI void dumpTree() const
User-friendly dump in tree shape.
Definition: AsmWriter.cpp:5507
A single uniqued string.
Definition: Metadata.h:720
Tuple of metadata.
Definition: Metadata.h:1493
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:182
Root of the metadata hierarchy.
Definition: Metadata.h:63
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
Definition: AsmWriter.cpp:5421
LLVM_ABI void printAsOperand(raw_ostream &OS, const Module *M=nullptr) const
Print as operand.
Definition: AsmWriter.cpp:5411
LLVM_ABI void dump() const
User-friendly dump.
Definition: AsmWriter.cpp:5498
Manage lifetime of a slot tracker for printing IR.
std::vector< std::pair< unsigned, const MDNode * > > MachineMDNodeListType
const Module * getModule() const
ModuleSlotTracker(SlotTracker &Machine, const Module *M, const Function *F=nullptr)
Wrap a preinitialized SlotTracker.
Definition: AsmWriter.cpp:937
virtual ~ModuleSlotTracker()
Destructor to clean up storage.
int getLocalSlot(const Value *V)
Return the slot number of the specified local value.
Definition: AsmWriter.cpp:977
void collectMDNodes(MachineMDNodeListType &L, unsigned LB, unsigned UB) const
Definition: AsmWriter.cpp:5451
SlotTracker * getMachine()
Lazily creates a slot tracker.
Definition: AsmWriter.cpp:948
void setProcessHook(std::function< void(AbstractSlotTrackerStorage *, const Module *, bool)>)
Definition: AsmWriter.cpp:982
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:963
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static constexpr const char * getRegularLTOModuleName()
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
LLVM_ABI void dump() const
Dump to stderr (for debugging).
Definition: AsmWriter.cpp:5517
LLVM_ABI void print(raw_ostream &OS, bool IsForDebug=false) const
Print to an output stream.
Definition: AsmWriter.cpp:5444
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
iterator_range< ifunc_iterator > ifuncs()
Definition: Module.h:742
iterator_range< named_metadata_iterator > named_metadata()
Definition: Module.h:789
iterator_range< alias_iterator > aliases()
Definition: Module.h:724
iterator_range< global_iterator > globals()
Definition: Module.h:684
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:5073
void dump() const
Dump the module to stderr (for debugging).
Definition: AsmWriter.cpp:5484
A tuple of MDNodes.
Definition: Metadata.h:1753
LLVM_ABI void dump() const
Definition: AsmWriter.cpp:5495
LLVM_ABI StringRef getName() const
Definition: Metadata.cpp:1482
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
Definition: AsmWriter.cpp:5082
LLVM_ABI MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1465
LLVM_ABI unsigned getNumOperands() const
Definition: Metadata.cpp:1461
Module * getParent()
Get the module that holds this named metadata collection.
Definition: Metadata.h:1823
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:78
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:740
An or instruction, which can be marked as "disjoint", indicating that the inputs don't have a 1 in th...
Definition: InstrTypes.h:404
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition: Operator.h:154
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2196
A vector that has set insertion semantics.
Definition: SetVector.h:59
This instruction constructs a fixed permutation of two input vectors.
This class provides computation of slot numbers for LLVM Assembly writing.
Definition: AsmWriter.cpp:757
bool mdn_empty() const
Definition: AsmWriter.cpp:877
int getMetadataSlot(const MDNode *N) override
getMetadataSlot - Get the slot number of a MDNode.
Definition: AsmWriter.cpp:1291
int getTypeIdCompatibleVtableSlot(StringRef Id)
Definition: AsmWriter.cpp:1347
int getModulePathSlot(StringRef Path)
Definition: AsmWriter.cpp:1320
bool as_empty() const
Definition: AsmWriter.cpp:885
unsigned mdn_size() const
Definition: AsmWriter.cpp:876
SlotTracker(const SlotTracker &)=delete
void purgeFunction()
After calling incorporateFunction, use this method to remove the most recently incorporated function ...
Definition: AsmWriter.cpp:1257
mdn_iterator mdn_end()
Definition: AsmWriter.cpp:875
int getTypeIdSlot(StringRef Id)
Definition: AsmWriter.cpp:1338
void initializeIfNeeded()
These functions do the actual initialization.
Definition: AsmWriter.cpp:1040
int getGlobalSlot(const GlobalValue *V)
getGlobalSlot - Get the slot number of a global value.
Definition: AsmWriter.cpp:1266
as_iterator as_begin()
Definition: AsmWriter.cpp:882
const Function * getFunction() const
Definition: AsmWriter.cpp:864
unsigned getNextMetadataSlot() override
Definition: AsmWriter.cpp:842
void incorporateFunction(const Function *F)
If you'd like to deal with a function instead of just a module, use this method to get its data into ...
Definition: AsmWriter.cpp:859
int getLocalSlot(const Value *V)
Return the slot number of the specified value in it's type plane.
Definition: AsmWriter.cpp:1301
int getAttributeGroupSlot(AttributeSet AS)
Definition: AsmWriter.cpp:1311
SlotTracker(const Module *M, bool ShouldInitializeAllMetadata=false)
Construct from a module.
Definition: AsmWriter.cpp:1028
void createMetadataSlot(const MDNode *N) override
getMetadataSlot - Get the slot number of a MDNode.
Definition: AsmWriter.cpp:1288
void setProcessHook(std::function< void(AbstractSlotTrackerStorage *, const Module *, bool)>)
Definition: AsmWriter.cpp:1275
~SlotTracker()=default
as_iterator as_end()
Definition: AsmWriter.cpp:883
unsigned as_size() const
Definition: AsmWriter.cpp:884
SlotTracker & operator=(const SlotTracker &)=delete
int getGUIDSlot(GlobalValue::GUID GUID)
Definition: AsmWriter.cpp:1329
mdn_iterator mdn_begin()
Definition: AsmWriter.cpp:874
int initializeIndexIfNeeded()
Definition: AsmWriter.cpp:1050
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void resize(size_type N)
Definition: SmallVector.h:639
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
An instruction for storing to memory.
Definition: Instructions.h:296
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:133
iterator end()
Definition: StringMap.h:224
iterator find(StringRef Key)
Definition: StringMap.h:237
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:151
Class to represent struct types.
Definition: DerivedTypes.h:218
ArrayRef< Type * > elements() const
Definition: DerivedTypes.h:360
bool isPacked() const
Definition: DerivedTypes.h:286
unsigned getNumElements() const
Random access to the elements.
Definition: DerivedTypes.h:368
bool isLiteral() const
Return true if this type is uniqued by structural equivalence, false if it is a struct definition.
Definition: DerivedTypes.h:290
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:294
LLVM_ABI StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:697
Multiway switch.
Class to represent target extensions types, which are generally unintrospectable from target-independ...
Definition: DerivedTypes.h:781
ArrayRef< Type * > type_params() const
Return the type parameters for this particular target extension type.
Definition: DerivedTypes.h:818
ArrayRef< unsigned > int_params() const
Return the integer parameters for this particular target extension type.
Definition: DerivedTypes.h:833
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
Definition: TypeFinder.h:31
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:273
LLVM_ABI void dump() const
LLVM_ABI StringRef getTargetExtName() const
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition: Type.h:66
@ FunctionTyID
Functions.
Definition: Type.h:71
@ ArrayTyID
Arrays.
Definition: Type.h:74
@ TypedPointerTyID
Typed pointer used by some GPU targets.
Definition: Type.h:77
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ TargetExtTyID
Target extension type.
Definition: Type.h:78
@ VoidTyID
type with no size
Definition: Type.h:63
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:76
@ LabelTyID
Labels.
Definition: Type.h:64
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:70
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:75
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition: Type.h:57
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition: Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition: Type.h:62
@ MetadataTyID
Metadata.
Definition: Type.h:65
@ TokenTyID
Tokens.
Definition: Type.h:67
@ PointerTyID
Pointers.
Definition: Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition: Type.h:61
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:240
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:136
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:352
A few GPU targets, such as DXIL and SPIR-V, have typed pointers.
Type * getElementType() const
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:5222
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:5305
bool hasName() const
Definition: Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:5465
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
LLVM_ABI StringRef EnumKindString(unsigned EnumKind)
Definition: Dwarf.cpp:393
LLVM_ABI StringRef LanguageString(unsigned Language)
Definition: Dwarf.cpp:412
LLVM_ABI StringRef AttributeEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:263
LLVM_ABI StringRef ConventionString(unsigned Convention)
Definition: Dwarf.cpp:489
LLVM_ABI StringRef MacinfoString(unsigned Encoding)
Definition: Dwarf.cpp:553
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:138
LLVM_ABI StringRef TagString(unsigned Tag)
Definition: Dwarf.cpp:21
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
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 Attrs[]
Key for Kernel::Metadata::mAttrs.
@ 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.
Definition: CallingConv.h:221
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:151
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
Definition: CallingConv.h:268
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
Definition: CallingConv.h:188
@ AVR_SIGNAL
Used for AVR signal routines.
Definition: CallingConv.h:179
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
Definition: CallingConv.h:224
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
Definition: CallingConv.h:107
@ 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.
Definition: CallingConv.h:176
@ 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.
Definition: CallingConv.h:232
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
Definition: CallingConv.h:166
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:249
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:206
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:111
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:241
@ CXX_FAST_TLS
Used for access functions.
Definition: CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
Definition: CallingConv.h:173
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:238
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:245
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition: CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ 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.
Definition: CallingConv.h:271
@ X86_ThisCall
Similar to X86_StdCall.
Definition: CallingConv.h:122
@ PTX_Device
Call to a PTX device function.
Definition: CallingConv.h:129
@ SPIR_KERNEL
Used for SPIR kernel functions.
Definition: CallingConv.h:144
@ 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.
Definition: CallingConv.h:138
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
Definition: CallingConv.h:117
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:163
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
Definition: CallingConv.h:147
@ 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.
Definition: CallingConv.h:218
@ 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.
Definition: CallingConv.h:159
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
Definition: CallingConv.h:125
@ 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.
Definition: CallingConv.h:255
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:213
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
Definition: CallingConv.h:114
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
Definition: CallingConv.h:203
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
Definition: CallingConv.h:252
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
Definition: CallingConv.h:103
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:58
@ SS
Definition: X86.h:215
@ FS
Definition: X86.h:214
@ GS
Definition: X86.h:213
@ DW_OP_LLVM_convert
Only used in LLVM metadata.
Definition: Dwarf.h:144
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1744
auto pred_end(const MachineBasicBlock *BB)
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
const char * getHotnessName(CalleeInfo::HotnessType HT)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
const char * toIRString(AtomicOrdering ao)
String used by LLVM IR to represent atomic ordering.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition: STLExtras.h:1939
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:188
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:201
constexpr int PoisonMaskElem
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:312
auto pred_begin(const MachineBasicBlock *BB)
const char * toString(DWARFSectionKind Kind)
@ Default
The result values are uniform if and only if all operands are uniform.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
LLVM_ABI void printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name)
Print out a name of an LLVM value without any prefixes.
Definition: AsmWriter.cpp:442
#define N
#define NC
Definition: regutils.h:42
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 & PPCDoubleDouble() LLVM_READNONE
Definition: APFloat.cpp:269
static LLVM_ABI const fltSemantics & x87DoubleExtended() LLVM_READNONE
Definition: APFloat.cpp:289
static LLVM_ABI const fltSemantics & IEEEquad() LLVM_READNONE
Definition: APFloat.cpp:268
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
A single checksum, represented by a Kind and a Value (a string).
T Value
The string value of the checksum.
StringRef getKindAsString() const
All type identifier related information.
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....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
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:117
A lightweight accessor for an operand bundle meant to be passed around by value.
Definition: InstrTypes.h:1011
StringRef getTagName() const
Return the tag of this operand bundle as a string.
Definition: InstrTypes.h:1030
ArrayRef< Use > Inputs
Definition: InstrTypes.h:1012
A utility class that uses RAII to save and restore the value of a variable.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
@ 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
Struct that holds a reference to a particular GUID in a global value summary.
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
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.
Function object to check whether the second component of a container supported by std::get (like std:...
Definition: STLExtras.h:1481