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