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