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