109467b48Spatrick //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This library implements `print` family of functions in classes like
1009467b48Spatrick // Module, Function, Value, etc. In-memory representation of those classes is
1109467b48Spatrick // converted to IR strings.
1209467b48Spatrick //
1309467b48Spatrick // Note that these routines must be extremely tolerant of various errors in the
1409467b48Spatrick // LLVM code, because it can be used for debugging transformations.
1509467b48Spatrick //
1609467b48Spatrick //===----------------------------------------------------------------------===//
1709467b48Spatrick
1809467b48Spatrick #include "llvm/ADT/APFloat.h"
1909467b48Spatrick #include "llvm/ADT/APInt.h"
2009467b48Spatrick #include "llvm/ADT/ArrayRef.h"
2109467b48Spatrick #include "llvm/ADT/DenseMap.h"
2209467b48Spatrick #include "llvm/ADT/STLExtras.h"
2309467b48Spatrick #include "llvm/ADT/SetVector.h"
24*d415bd75Srobert #include "llvm/ADT/SmallPtrSet.h"
2509467b48Spatrick #include "llvm/ADT/SmallString.h"
2609467b48Spatrick #include "llvm/ADT/SmallVector.h"
2709467b48Spatrick #include "llvm/ADT/StringExtras.h"
2809467b48Spatrick #include "llvm/ADT/StringRef.h"
2909467b48Spatrick #include "llvm/ADT/iterator_range.h"
3009467b48Spatrick #include "llvm/BinaryFormat/Dwarf.h"
3109467b48Spatrick #include "llvm/Config/llvm-config.h"
3209467b48Spatrick #include "llvm/IR/Argument.h"
3309467b48Spatrick #include "llvm/IR/AssemblyAnnotationWriter.h"
3409467b48Spatrick #include "llvm/IR/Attributes.h"
3509467b48Spatrick #include "llvm/IR/BasicBlock.h"
3609467b48Spatrick #include "llvm/IR/CFG.h"
3709467b48Spatrick #include "llvm/IR/CallingConv.h"
3809467b48Spatrick #include "llvm/IR/Comdat.h"
3909467b48Spatrick #include "llvm/IR/Constant.h"
4009467b48Spatrick #include "llvm/IR/Constants.h"
4109467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h"
4209467b48Spatrick #include "llvm/IR/DerivedTypes.h"
4309467b48Spatrick #include "llvm/IR/Function.h"
4409467b48Spatrick #include "llvm/IR/GlobalAlias.h"
4509467b48Spatrick #include "llvm/IR/GlobalIFunc.h"
4609467b48Spatrick #include "llvm/IR/GlobalObject.h"
4709467b48Spatrick #include "llvm/IR/GlobalValue.h"
4809467b48Spatrick #include "llvm/IR/GlobalVariable.h"
4909467b48Spatrick #include "llvm/IR/IRPrintingPasses.h"
5009467b48Spatrick #include "llvm/IR/InlineAsm.h"
5109467b48Spatrick #include "llvm/IR/InstrTypes.h"
5209467b48Spatrick #include "llvm/IR/Instruction.h"
5309467b48Spatrick #include "llvm/IR/Instructions.h"
5473471bf0Spatrick #include "llvm/IR/IntrinsicInst.h"
5509467b48Spatrick #include "llvm/IR/LLVMContext.h"
5609467b48Spatrick #include "llvm/IR/Metadata.h"
5709467b48Spatrick #include "llvm/IR/Module.h"
5809467b48Spatrick #include "llvm/IR/ModuleSlotTracker.h"
5909467b48Spatrick #include "llvm/IR/ModuleSummaryIndex.h"
6009467b48Spatrick #include "llvm/IR/Operator.h"
6109467b48Spatrick #include "llvm/IR/Type.h"
6209467b48Spatrick #include "llvm/IR/TypeFinder.h"
63*d415bd75Srobert #include "llvm/IR/TypedPointerType.h"
6409467b48Spatrick #include "llvm/IR/Use.h"
6509467b48Spatrick #include "llvm/IR/User.h"
6609467b48Spatrick #include "llvm/IR/Value.h"
6709467b48Spatrick #include "llvm/Support/AtomicOrdering.h"
6809467b48Spatrick #include "llvm/Support/Casting.h"
6909467b48Spatrick #include "llvm/Support/Compiler.h"
7009467b48Spatrick #include "llvm/Support/Debug.h"
7109467b48Spatrick #include "llvm/Support/ErrorHandling.h"
7209467b48Spatrick #include "llvm/Support/Format.h"
7309467b48Spatrick #include "llvm/Support/FormattedStream.h"
74*d415bd75Srobert #include "llvm/Support/SaveAndRestore.h"
7509467b48Spatrick #include "llvm/Support/raw_ostream.h"
7609467b48Spatrick #include <algorithm>
7709467b48Spatrick #include <cassert>
7809467b48Spatrick #include <cctype>
7909467b48Spatrick #include <cstddef>
8009467b48Spatrick #include <cstdint>
8109467b48Spatrick #include <iterator>
8209467b48Spatrick #include <memory>
83*d415bd75Srobert #include <optional>
8409467b48Spatrick #include <string>
8509467b48Spatrick #include <tuple>
8609467b48Spatrick #include <utility>
8709467b48Spatrick #include <vector>
8809467b48Spatrick
8909467b48Spatrick using namespace llvm;
9009467b48Spatrick
9109467b48Spatrick // Make virtual table appear in this compilation unit.
9209467b48Spatrick AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
9309467b48Spatrick
9409467b48Spatrick //===----------------------------------------------------------------------===//
9509467b48Spatrick // Helper Functions
9609467b48Spatrick //===----------------------------------------------------------------------===//
9709467b48Spatrick
9873471bf0Spatrick using OrderMap = MapVector<const Value *, unsigned>;
9909467b48Spatrick
10073471bf0Spatrick using UseListOrderMap =
10173471bf0Spatrick DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;
10209467b48Spatrick
10373471bf0Spatrick /// Look for a value that might be wrapped as metadata, e.g. a value in a
10473471bf0Spatrick /// metadata operand. Returns the input value as-is if it is not wrapped.
skipMetadataWrapper(const Value * V)10573471bf0Spatrick static const Value *skipMetadataWrapper(const Value *V) {
10673471bf0Spatrick if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
10773471bf0Spatrick if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
10873471bf0Spatrick return VAM->getValue();
10973471bf0Spatrick return V;
11009467b48Spatrick }
11109467b48Spatrick
orderValue(const Value * V,OrderMap & OM)11209467b48Spatrick static void orderValue(const Value *V, OrderMap &OM) {
11373471bf0Spatrick if (OM.lookup(V))
11409467b48Spatrick return;
11509467b48Spatrick
11609467b48Spatrick if (const Constant *C = dyn_cast<Constant>(V))
11709467b48Spatrick if (C->getNumOperands() && !isa<GlobalValue>(C))
11809467b48Spatrick for (const Value *Op : C->operands())
11909467b48Spatrick if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
12009467b48Spatrick orderValue(Op, OM);
12109467b48Spatrick
12209467b48Spatrick // Note: we cannot cache this lookup above, since inserting into the map
12309467b48Spatrick // changes the map's size, and thus affects the other IDs.
12473471bf0Spatrick unsigned ID = OM.size() + 1;
12573471bf0Spatrick OM[V] = ID;
12609467b48Spatrick }
12709467b48Spatrick
orderModule(const Module * M)12809467b48Spatrick static OrderMap orderModule(const Module *M) {
12909467b48Spatrick OrderMap OM;
13009467b48Spatrick
13109467b48Spatrick for (const GlobalVariable &G : M->globals()) {
13209467b48Spatrick if (G.hasInitializer())
13309467b48Spatrick if (!isa<GlobalValue>(G.getInitializer()))
13409467b48Spatrick orderValue(G.getInitializer(), OM);
13509467b48Spatrick orderValue(&G, OM);
13609467b48Spatrick }
13709467b48Spatrick for (const GlobalAlias &A : M->aliases()) {
13809467b48Spatrick if (!isa<GlobalValue>(A.getAliasee()))
13909467b48Spatrick orderValue(A.getAliasee(), OM);
14009467b48Spatrick orderValue(&A, OM);
14109467b48Spatrick }
14209467b48Spatrick for (const GlobalIFunc &I : M->ifuncs()) {
14309467b48Spatrick if (!isa<GlobalValue>(I.getResolver()))
14409467b48Spatrick orderValue(I.getResolver(), OM);
14509467b48Spatrick orderValue(&I, OM);
14609467b48Spatrick }
14709467b48Spatrick for (const Function &F : *M) {
14809467b48Spatrick for (const Use &U : F.operands())
14909467b48Spatrick if (!isa<GlobalValue>(U.get()))
15009467b48Spatrick orderValue(U.get(), OM);
15109467b48Spatrick
15209467b48Spatrick orderValue(&F, OM);
15309467b48Spatrick
15409467b48Spatrick if (F.isDeclaration())
15509467b48Spatrick continue;
15609467b48Spatrick
15709467b48Spatrick for (const Argument &A : F.args())
15809467b48Spatrick orderValue(&A, OM);
15909467b48Spatrick for (const BasicBlock &BB : F) {
16009467b48Spatrick orderValue(&BB, OM);
16109467b48Spatrick for (const Instruction &I : BB) {
16273471bf0Spatrick for (const Value *Op : I.operands()) {
16373471bf0Spatrick Op = skipMetadataWrapper(Op);
16409467b48Spatrick if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
16509467b48Spatrick isa<InlineAsm>(*Op))
16609467b48Spatrick orderValue(Op, OM);
16773471bf0Spatrick }
16809467b48Spatrick orderValue(&I, OM);
16909467b48Spatrick }
17009467b48Spatrick }
17109467b48Spatrick }
17209467b48Spatrick return OM;
17309467b48Spatrick }
17409467b48Spatrick
17573471bf0Spatrick static std::vector<unsigned>
predictValueUseListOrder(const Value * V,unsigned ID,const OrderMap & OM)17673471bf0Spatrick predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
17709467b48Spatrick // Predict use-list order for this one.
17809467b48Spatrick using Entry = std::pair<const Use *, unsigned>;
17909467b48Spatrick SmallVector<Entry, 64> List;
18009467b48Spatrick for (const Use &U : V->uses())
18109467b48Spatrick // Check if this user will be serialized.
18273471bf0Spatrick if (OM.lookup(U.getUser()))
18309467b48Spatrick List.push_back(std::make_pair(&U, List.size()));
18409467b48Spatrick
18509467b48Spatrick if (List.size() < 2)
18609467b48Spatrick // We may have lost some users.
18773471bf0Spatrick return {};
18809467b48Spatrick
18973471bf0Spatrick // When referencing a value before its declaration, a temporary value is
19073471bf0Spatrick // created, which will later be RAUWed with the actual value. This reverses
19173471bf0Spatrick // the use list. This happens for all values apart from basic blocks.
19273471bf0Spatrick bool GetsReversed = !isa<BasicBlock>(V);
19309467b48Spatrick if (auto *BA = dyn_cast<BlockAddress>(V))
19473471bf0Spatrick ID = OM.lookup(BA->getBasicBlock());
19509467b48Spatrick llvm::sort(List, [&](const Entry &L, const Entry &R) {
19609467b48Spatrick const Use *LU = L.first;
19709467b48Spatrick const Use *RU = R.first;
19809467b48Spatrick if (LU == RU)
19909467b48Spatrick return false;
20009467b48Spatrick
20173471bf0Spatrick auto LID = OM.lookup(LU->getUser());
20273471bf0Spatrick auto RID = OM.lookup(RU->getUser());
20309467b48Spatrick
20409467b48Spatrick // If ID is 4, then expect: 7 6 5 1 2 3.
20509467b48Spatrick if (LID < RID) {
20609467b48Spatrick if (GetsReversed)
20709467b48Spatrick if (RID <= ID)
20809467b48Spatrick return true;
20909467b48Spatrick return false;
21009467b48Spatrick }
21109467b48Spatrick if (RID < LID) {
21209467b48Spatrick if (GetsReversed)
21309467b48Spatrick if (LID <= ID)
21409467b48Spatrick return false;
21509467b48Spatrick return true;
21609467b48Spatrick }
21709467b48Spatrick
21809467b48Spatrick // LID and RID are equal, so we have different operands of the same user.
21909467b48Spatrick // Assume operands are added in order for all instructions.
22009467b48Spatrick if (GetsReversed)
22109467b48Spatrick if (LID <= ID)
22209467b48Spatrick return LU->getOperandNo() < RU->getOperandNo();
22309467b48Spatrick return LU->getOperandNo() > RU->getOperandNo();
22409467b48Spatrick });
22509467b48Spatrick
226*d415bd75Srobert if (llvm::is_sorted(List, llvm::less_second()))
22709467b48Spatrick // Order is already correct.
22873471bf0Spatrick return {};
22909467b48Spatrick
23009467b48Spatrick // Store the shuffle.
23173471bf0Spatrick std::vector<unsigned> Shuffle(List.size());
23209467b48Spatrick for (size_t I = 0, E = List.size(); I != E; ++I)
23373471bf0Spatrick Shuffle[I] = List[I].second;
23473471bf0Spatrick return Shuffle;
23509467b48Spatrick }
23609467b48Spatrick
predictUseListOrder(const Module * M)23773471bf0Spatrick static UseListOrderMap predictUseListOrder(const Module *M) {
23809467b48Spatrick OrderMap OM = orderModule(M);
23973471bf0Spatrick UseListOrderMap ULOM;
24073471bf0Spatrick for (const auto &Pair : OM) {
24173471bf0Spatrick const Value *V = Pair.first;
24273471bf0Spatrick if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
24309467b48Spatrick continue;
24473471bf0Spatrick
24573471bf0Spatrick std::vector<unsigned> Shuffle =
24673471bf0Spatrick predictValueUseListOrder(V, Pair.second, OM);
24773471bf0Spatrick if (Shuffle.empty())
24873471bf0Spatrick continue;
24973471bf0Spatrick
25073471bf0Spatrick const Function *F = nullptr;
25173471bf0Spatrick if (auto *I = dyn_cast<Instruction>(V))
25273471bf0Spatrick F = I->getFunction();
25373471bf0Spatrick if (auto *A = dyn_cast<Argument>(V))
25473471bf0Spatrick F = A->getParent();
25573471bf0Spatrick if (auto *BB = dyn_cast<BasicBlock>(V))
25673471bf0Spatrick F = BB->getParent();
25773471bf0Spatrick ULOM[F][V] = std::move(Shuffle);
25809467b48Spatrick }
25973471bf0Spatrick return ULOM;
26009467b48Spatrick }
26109467b48Spatrick
getModuleFromVal(const Value * V)26209467b48Spatrick static const Module *getModuleFromVal(const Value *V) {
26309467b48Spatrick if (const Argument *MA = dyn_cast<Argument>(V))
26409467b48Spatrick return MA->getParent() ? MA->getParent()->getParent() : nullptr;
26509467b48Spatrick
26609467b48Spatrick if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
26709467b48Spatrick return BB->getParent() ? BB->getParent()->getParent() : nullptr;
26809467b48Spatrick
26909467b48Spatrick if (const Instruction *I = dyn_cast<Instruction>(V)) {
27009467b48Spatrick const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
27109467b48Spatrick return M ? M->getParent() : nullptr;
27209467b48Spatrick }
27309467b48Spatrick
27409467b48Spatrick if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
27509467b48Spatrick return GV->getParent();
27609467b48Spatrick
27709467b48Spatrick if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
27809467b48Spatrick for (const User *U : MAV->users())
27909467b48Spatrick if (isa<Instruction>(U))
28009467b48Spatrick if (const Module *M = getModuleFromVal(U))
28109467b48Spatrick return M;
28209467b48Spatrick return nullptr;
28309467b48Spatrick }
28409467b48Spatrick
28509467b48Spatrick return nullptr;
28609467b48Spatrick }
28709467b48Spatrick
PrintCallingConv(unsigned cc,raw_ostream & Out)28809467b48Spatrick static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
28909467b48Spatrick switch (cc) {
29009467b48Spatrick default: Out << "cc" << cc; break;
29109467b48Spatrick case CallingConv::Fast: Out << "fastcc"; break;
29209467b48Spatrick case CallingConv::Cold: Out << "coldcc"; break;
29309467b48Spatrick case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
29409467b48Spatrick case CallingConv::AnyReg: Out << "anyregcc"; break;
29509467b48Spatrick case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
29609467b48Spatrick case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
29709467b48Spatrick case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
29809467b48Spatrick case CallingConv::GHC: Out << "ghccc"; break;
29909467b48Spatrick case CallingConv::Tail: Out << "tailcc"; break;
30009467b48Spatrick case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
30109467b48Spatrick case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
30209467b48Spatrick case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
30309467b48Spatrick case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
30409467b48Spatrick case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break;
30509467b48Spatrick case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
30609467b48Spatrick case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
30709467b48Spatrick case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
30809467b48Spatrick case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
30909467b48Spatrick case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
31009467b48Spatrick case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
31109467b48Spatrick case CallingConv::AArch64_SVE_VectorCall:
31209467b48Spatrick Out << "aarch64_sve_vector_pcs";
31309467b48Spatrick break;
314*d415bd75Srobert case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
315*d415bd75Srobert Out << "aarch64_sme_preservemost_from_x0";
316*d415bd75Srobert break;
317*d415bd75Srobert case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
318*d415bd75Srobert Out << "aarch64_sme_preservemost_from_x2";
319*d415bd75Srobert break;
32009467b48Spatrick case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
32109467b48Spatrick case CallingConv::AVR_INTR: Out << "avr_intrcc "; break;
32209467b48Spatrick case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break;
32309467b48Spatrick case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
32409467b48Spatrick case CallingConv::PTX_Device: Out << "ptx_device"; break;
32509467b48Spatrick case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
32609467b48Spatrick case CallingConv::Win64: Out << "win64cc"; break;
32709467b48Spatrick case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
32809467b48Spatrick case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
32909467b48Spatrick case CallingConv::Swift: Out << "swiftcc"; break;
33073471bf0Spatrick case CallingConv::SwiftTail: Out << "swifttailcc"; break;
33109467b48Spatrick case CallingConv::X86_INTR: Out << "x86_intrcc"; break;
33209467b48Spatrick case CallingConv::HHVM: Out << "hhvmcc"; break;
33309467b48Spatrick case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
33409467b48Spatrick case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break;
33509467b48Spatrick case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break;
33609467b48Spatrick case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break;
33709467b48Spatrick case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break;
33809467b48Spatrick case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break;
33909467b48Spatrick case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break;
34009467b48Spatrick case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break;
34109467b48Spatrick case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
34273471bf0Spatrick case CallingConv::AMDGPU_Gfx: Out << "amdgpu_gfx"; break;
34309467b48Spatrick }
34409467b48Spatrick }
34509467b48Spatrick
34609467b48Spatrick enum PrefixType {
34709467b48Spatrick GlobalPrefix,
34809467b48Spatrick ComdatPrefix,
34909467b48Spatrick LabelPrefix,
35009467b48Spatrick LocalPrefix,
35109467b48Spatrick NoPrefix
35209467b48Spatrick };
35309467b48Spatrick
printLLVMNameWithoutPrefix(raw_ostream & OS,StringRef Name)35409467b48Spatrick void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
35509467b48Spatrick assert(!Name.empty() && "Cannot get empty name!");
35609467b48Spatrick
35709467b48Spatrick // Scan the name to see if it needs quotes first.
35809467b48Spatrick bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
35909467b48Spatrick if (!NeedsQuotes) {
360*d415bd75Srobert for (unsigned char C : Name) {
36109467b48Spatrick // By making this unsigned, the value passed in to isalnum will always be
36209467b48Spatrick // in the range 0-255. This is important when building with MSVC because
36309467b48Spatrick // its implementation will assert. This situation can arise when dealing
36409467b48Spatrick // with UTF-8 multibyte characters.
36509467b48Spatrick if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
36609467b48Spatrick C != '_') {
36709467b48Spatrick NeedsQuotes = true;
36809467b48Spatrick break;
36909467b48Spatrick }
37009467b48Spatrick }
37109467b48Spatrick }
37209467b48Spatrick
37309467b48Spatrick // If we didn't need any quotes, just write out the name in one blast.
37409467b48Spatrick if (!NeedsQuotes) {
37509467b48Spatrick OS << Name;
37609467b48Spatrick return;
37709467b48Spatrick }
37809467b48Spatrick
37909467b48Spatrick // Okay, we need quotes. Output the quotes and escape any scary characters as
38009467b48Spatrick // needed.
38109467b48Spatrick OS << '"';
38209467b48Spatrick printEscapedString(Name, OS);
38309467b48Spatrick OS << '"';
38409467b48Spatrick }
38509467b48Spatrick
38609467b48Spatrick /// Turn the specified name into an 'LLVM name', which is either prefixed with %
38709467b48Spatrick /// (if the string only contains simple characters) or is surrounded with ""'s
38809467b48Spatrick /// (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,StringRef Name,PrefixType Prefix)38909467b48Spatrick static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
39009467b48Spatrick switch (Prefix) {
39109467b48Spatrick case NoPrefix:
39209467b48Spatrick break;
39309467b48Spatrick case GlobalPrefix:
39409467b48Spatrick OS << '@';
39509467b48Spatrick break;
39609467b48Spatrick case ComdatPrefix:
39709467b48Spatrick OS << '$';
39809467b48Spatrick break;
39909467b48Spatrick case LabelPrefix:
40009467b48Spatrick break;
40109467b48Spatrick case LocalPrefix:
40209467b48Spatrick OS << '%';
40309467b48Spatrick break;
40409467b48Spatrick }
40509467b48Spatrick printLLVMNameWithoutPrefix(OS, Name);
40609467b48Spatrick }
40709467b48Spatrick
40809467b48Spatrick /// Turn the specified name into an 'LLVM name', which is either prefixed with %
40909467b48Spatrick /// (if the string only contains simple characters) or is surrounded with ""'s
41009467b48Spatrick /// (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,const Value * V)41109467b48Spatrick static void PrintLLVMName(raw_ostream &OS, const Value *V) {
41209467b48Spatrick PrintLLVMName(OS, V->getName(),
41309467b48Spatrick isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
41409467b48Spatrick }
41509467b48Spatrick
PrintShuffleMask(raw_ostream & Out,Type * Ty,ArrayRef<int> Mask)416097a140dSpatrick static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
417097a140dSpatrick Out << ", <";
418097a140dSpatrick if (isa<ScalableVectorType>(Ty))
419097a140dSpatrick Out << "vscale x ";
420097a140dSpatrick Out << Mask.size() << " x i32> ";
421097a140dSpatrick bool FirstElt = true;
422097a140dSpatrick if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
423097a140dSpatrick Out << "zeroinitializer";
424097a140dSpatrick } else if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
425097a140dSpatrick Out << "undef";
426097a140dSpatrick } else {
427097a140dSpatrick Out << "<";
428097a140dSpatrick for (int Elt : Mask) {
429097a140dSpatrick if (FirstElt)
430097a140dSpatrick FirstElt = false;
431097a140dSpatrick else
432097a140dSpatrick Out << ", ";
433097a140dSpatrick Out << "i32 ";
434097a140dSpatrick if (Elt == UndefMaskElem)
435097a140dSpatrick Out << "undef";
436097a140dSpatrick else
437097a140dSpatrick Out << Elt;
438097a140dSpatrick }
439097a140dSpatrick Out << ">";
440097a140dSpatrick }
441097a140dSpatrick }
442097a140dSpatrick
44309467b48Spatrick namespace {
44409467b48Spatrick
44509467b48Spatrick class TypePrinting {
44609467b48Spatrick public:
TypePrinting(const Module * M=nullptr)44709467b48Spatrick TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
44809467b48Spatrick
44909467b48Spatrick TypePrinting(const TypePrinting &) = delete;
45009467b48Spatrick TypePrinting &operator=(const TypePrinting &) = delete;
45109467b48Spatrick
45209467b48Spatrick /// The named types that are used by the current module.
45309467b48Spatrick TypeFinder &getNamedTypes();
45409467b48Spatrick
45509467b48Spatrick /// The numbered types, number to type mapping.
45609467b48Spatrick std::vector<StructType *> &getNumberedTypes();
45709467b48Spatrick
45809467b48Spatrick bool empty();
45909467b48Spatrick
46009467b48Spatrick void print(Type *Ty, raw_ostream &OS);
46109467b48Spatrick
46209467b48Spatrick void printStructBody(StructType *Ty, raw_ostream &OS);
46309467b48Spatrick
46409467b48Spatrick private:
46509467b48Spatrick void incorporateTypes();
46609467b48Spatrick
46709467b48Spatrick /// A module to process lazily when needed. Set to nullptr as soon as used.
46809467b48Spatrick const Module *DeferredM;
46909467b48Spatrick
47009467b48Spatrick TypeFinder NamedTypes;
47109467b48Spatrick
47209467b48Spatrick // The numbered types, along with their value.
47309467b48Spatrick DenseMap<StructType *, unsigned> Type2Number;
47409467b48Spatrick
47509467b48Spatrick std::vector<StructType *> NumberedTypes;
47609467b48Spatrick };
47709467b48Spatrick
47809467b48Spatrick } // end anonymous namespace
47909467b48Spatrick
getNamedTypes()48009467b48Spatrick TypeFinder &TypePrinting::getNamedTypes() {
48109467b48Spatrick incorporateTypes();
48209467b48Spatrick return NamedTypes;
48309467b48Spatrick }
48409467b48Spatrick
getNumberedTypes()48509467b48Spatrick std::vector<StructType *> &TypePrinting::getNumberedTypes() {
48609467b48Spatrick incorporateTypes();
48709467b48Spatrick
48809467b48Spatrick // We know all the numbers that each type is used and we know that it is a
48909467b48Spatrick // dense assignment. Convert the map to an index table, if it's not done
49009467b48Spatrick // already (judging from the sizes):
49109467b48Spatrick if (NumberedTypes.size() == Type2Number.size())
49209467b48Spatrick return NumberedTypes;
49309467b48Spatrick
49409467b48Spatrick NumberedTypes.resize(Type2Number.size());
49509467b48Spatrick for (const auto &P : Type2Number) {
49609467b48Spatrick assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
49709467b48Spatrick assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
49809467b48Spatrick NumberedTypes[P.second] = P.first;
49909467b48Spatrick }
50009467b48Spatrick return NumberedTypes;
50109467b48Spatrick }
50209467b48Spatrick
empty()50309467b48Spatrick bool TypePrinting::empty() {
50409467b48Spatrick incorporateTypes();
50509467b48Spatrick return NamedTypes.empty() && Type2Number.empty();
50609467b48Spatrick }
50709467b48Spatrick
incorporateTypes()50809467b48Spatrick void TypePrinting::incorporateTypes() {
50909467b48Spatrick if (!DeferredM)
51009467b48Spatrick return;
51109467b48Spatrick
51209467b48Spatrick NamedTypes.run(*DeferredM, false);
51309467b48Spatrick DeferredM = nullptr;
51409467b48Spatrick
51509467b48Spatrick // The list of struct types we got back includes all the struct types, split
51609467b48Spatrick // the unnamed ones out to a numbering and remove the anonymous structs.
51709467b48Spatrick unsigned NextNumber = 0;
51809467b48Spatrick
519*d415bd75Srobert std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
520*d415bd75Srobert for (StructType *STy : NamedTypes) {
52109467b48Spatrick // Ignore anonymous types.
52209467b48Spatrick if (STy->isLiteral())
52309467b48Spatrick continue;
52409467b48Spatrick
52509467b48Spatrick if (STy->getName().empty())
52609467b48Spatrick Type2Number[STy] = NextNumber++;
52709467b48Spatrick else
52809467b48Spatrick *NextToUse++ = STy;
52909467b48Spatrick }
53009467b48Spatrick
53109467b48Spatrick NamedTypes.erase(NextToUse, NamedTypes.end());
53209467b48Spatrick }
53309467b48Spatrick
53409467b48Spatrick /// Write the specified type to the specified raw_ostream, making use of type
53509467b48Spatrick /// names or up references to shorten the type name where possible.
print(Type * Ty,raw_ostream & OS)53609467b48Spatrick void TypePrinting::print(Type *Ty, raw_ostream &OS) {
53709467b48Spatrick switch (Ty->getTypeID()) {
53809467b48Spatrick case Type::VoidTyID: OS << "void"; return;
53909467b48Spatrick case Type::HalfTyID: OS << "half"; return;
540097a140dSpatrick case Type::BFloatTyID: OS << "bfloat"; return;
54109467b48Spatrick case Type::FloatTyID: OS << "float"; return;
54209467b48Spatrick case Type::DoubleTyID: OS << "double"; return;
54309467b48Spatrick case Type::X86_FP80TyID: OS << "x86_fp80"; return;
54409467b48Spatrick case Type::FP128TyID: OS << "fp128"; return;
54509467b48Spatrick case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
54609467b48Spatrick case Type::LabelTyID: OS << "label"; return;
54709467b48Spatrick case Type::MetadataTyID: OS << "metadata"; return;
54809467b48Spatrick case Type::X86_MMXTyID: OS << "x86_mmx"; return;
54973471bf0Spatrick case Type::X86_AMXTyID: OS << "x86_amx"; return;
55009467b48Spatrick case Type::TokenTyID: OS << "token"; return;
55109467b48Spatrick case Type::IntegerTyID:
55209467b48Spatrick OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
55309467b48Spatrick return;
55409467b48Spatrick
55509467b48Spatrick case Type::FunctionTyID: {
55609467b48Spatrick FunctionType *FTy = cast<FunctionType>(Ty);
55709467b48Spatrick print(FTy->getReturnType(), OS);
55809467b48Spatrick OS << " (";
559*d415bd75Srobert ListSeparator LS;
560*d415bd75Srobert for (Type *Ty : FTy->params()) {
561*d415bd75Srobert OS << LS;
562*d415bd75Srobert print(Ty, OS);
56309467b48Spatrick }
564*d415bd75Srobert if (FTy->isVarArg())
565*d415bd75Srobert OS << LS << "...";
56609467b48Spatrick OS << ')';
56709467b48Spatrick return;
56809467b48Spatrick }
56909467b48Spatrick case Type::StructTyID: {
57009467b48Spatrick StructType *STy = cast<StructType>(Ty);
57109467b48Spatrick
57209467b48Spatrick if (STy->isLiteral())
57309467b48Spatrick return printStructBody(STy, OS);
57409467b48Spatrick
57509467b48Spatrick if (!STy->getName().empty())
57609467b48Spatrick return PrintLLVMName(OS, STy->getName(), LocalPrefix);
57709467b48Spatrick
57809467b48Spatrick incorporateTypes();
57909467b48Spatrick const auto I = Type2Number.find(STy);
58009467b48Spatrick if (I != Type2Number.end())
58109467b48Spatrick OS << '%' << I->second;
58209467b48Spatrick else // Not enumerated, print the hex address.
58309467b48Spatrick OS << "%\"type " << STy << '\"';
58409467b48Spatrick return;
58509467b48Spatrick }
58609467b48Spatrick case Type::PointerTyID: {
58709467b48Spatrick PointerType *PTy = cast<PointerType>(Ty);
58873471bf0Spatrick if (PTy->isOpaque()) {
58973471bf0Spatrick OS << "ptr";
59073471bf0Spatrick if (unsigned AddressSpace = PTy->getAddressSpace())
59173471bf0Spatrick OS << " addrspace(" << AddressSpace << ')';
59273471bf0Spatrick return;
59373471bf0Spatrick }
594*d415bd75Srobert print(PTy->getNonOpaquePointerElementType(), OS);
59509467b48Spatrick if (unsigned AddressSpace = PTy->getAddressSpace())
59609467b48Spatrick OS << " addrspace(" << AddressSpace << ')';
59709467b48Spatrick OS << '*';
59809467b48Spatrick return;
59909467b48Spatrick }
60009467b48Spatrick case Type::ArrayTyID: {
60109467b48Spatrick ArrayType *ATy = cast<ArrayType>(Ty);
60209467b48Spatrick OS << '[' << ATy->getNumElements() << " x ";
60309467b48Spatrick print(ATy->getElementType(), OS);
60409467b48Spatrick OS << ']';
60509467b48Spatrick return;
60609467b48Spatrick }
607097a140dSpatrick case Type::FixedVectorTyID:
608097a140dSpatrick case Type::ScalableVectorTyID: {
60909467b48Spatrick VectorType *PTy = cast<VectorType>(Ty);
610097a140dSpatrick ElementCount EC = PTy->getElementCount();
61109467b48Spatrick OS << "<";
61273471bf0Spatrick if (EC.isScalable())
61309467b48Spatrick OS << "vscale x ";
61473471bf0Spatrick OS << EC.getKnownMinValue() << " x ";
61509467b48Spatrick print(PTy->getElementType(), OS);
61609467b48Spatrick OS << '>';
61709467b48Spatrick return;
61809467b48Spatrick }
619*d415bd75Srobert case Type::TypedPointerTyID: {
620*d415bd75Srobert TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
621*d415bd75Srobert OS << "typedptr(" << *TPTy->getElementType() << ", "
622*d415bd75Srobert << TPTy->getAddressSpace() << ")";
623*d415bd75Srobert return;
624*d415bd75Srobert }
625*d415bd75Srobert case Type::TargetExtTyID:
626*d415bd75Srobert TargetExtType *TETy = cast<TargetExtType>(Ty);
627*d415bd75Srobert OS << "target(\"";
628*d415bd75Srobert printEscapedString(Ty->getTargetExtName(), OS);
629*d415bd75Srobert OS << "\"";
630*d415bd75Srobert for (Type *Inner : TETy->type_params())
631*d415bd75Srobert OS << ", " << *Inner;
632*d415bd75Srobert for (unsigned IntParam : TETy->int_params())
633*d415bd75Srobert OS << ", " << IntParam;
634*d415bd75Srobert OS << ")";
635*d415bd75Srobert return;
63609467b48Spatrick }
63709467b48Spatrick llvm_unreachable("Invalid TypeID");
63809467b48Spatrick }
63909467b48Spatrick
printStructBody(StructType * STy,raw_ostream & OS)64009467b48Spatrick void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
64109467b48Spatrick if (STy->isOpaque()) {
64209467b48Spatrick OS << "opaque";
64309467b48Spatrick return;
64409467b48Spatrick }
64509467b48Spatrick
64609467b48Spatrick if (STy->isPacked())
64709467b48Spatrick OS << '<';
64809467b48Spatrick
64909467b48Spatrick if (STy->getNumElements() == 0) {
65009467b48Spatrick OS << "{}";
65109467b48Spatrick } else {
65209467b48Spatrick OS << "{ ";
653*d415bd75Srobert ListSeparator LS;
654*d415bd75Srobert for (Type *Ty : STy->elements()) {
655*d415bd75Srobert OS << LS;
656*d415bd75Srobert print(Ty, OS);
65709467b48Spatrick }
65809467b48Spatrick
65909467b48Spatrick OS << " }";
66009467b48Spatrick }
66109467b48Spatrick if (STy->isPacked())
66209467b48Spatrick OS << '>';
66309467b48Spatrick }
66409467b48Spatrick
665*d415bd75Srobert AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
66673471bf0Spatrick
66709467b48Spatrick namespace llvm {
66809467b48Spatrick
66909467b48Spatrick //===----------------------------------------------------------------------===//
67009467b48Spatrick // SlotTracker Class: Enumerate slot numbers for unnamed values
67109467b48Spatrick //===----------------------------------------------------------------------===//
67209467b48Spatrick /// This class provides computation of slot numbers for LLVM Assembly writing.
67309467b48Spatrick ///
67473471bf0Spatrick class SlotTracker : public AbstractSlotTrackerStorage {
67509467b48Spatrick public:
67609467b48Spatrick /// ValueMap - A mapping of Values to slot numbers.
67709467b48Spatrick using ValueMap = DenseMap<const Value *, unsigned>;
67809467b48Spatrick
67909467b48Spatrick private:
68009467b48Spatrick /// TheModule - The module for which we are holding slot numbers.
68109467b48Spatrick const Module* TheModule;
68209467b48Spatrick
68309467b48Spatrick /// TheFunction - The function for which we are holding slot numbers.
68409467b48Spatrick const Function* TheFunction = nullptr;
68509467b48Spatrick bool FunctionProcessed = false;
68609467b48Spatrick bool ShouldInitializeAllMetadata;
68709467b48Spatrick
68873471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
68973471bf0Spatrick ProcessModuleHookFn;
69073471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
69173471bf0Spatrick ProcessFunctionHookFn;
69273471bf0Spatrick
69309467b48Spatrick /// The summary index for which we are holding slot numbers.
69409467b48Spatrick const ModuleSummaryIndex *TheIndex = nullptr;
69509467b48Spatrick
69609467b48Spatrick /// mMap - The slot map for the module level data.
69709467b48Spatrick ValueMap mMap;
69809467b48Spatrick unsigned mNext = 0;
69909467b48Spatrick
70009467b48Spatrick /// fMap - The slot map for the function level data.
70109467b48Spatrick ValueMap fMap;
70209467b48Spatrick unsigned fNext = 0;
70309467b48Spatrick
70409467b48Spatrick /// mdnMap - Map for MDNodes.
70509467b48Spatrick DenseMap<const MDNode*, unsigned> mdnMap;
70609467b48Spatrick unsigned mdnNext = 0;
70709467b48Spatrick
70809467b48Spatrick /// asMap - The slot map for attribute sets.
70909467b48Spatrick DenseMap<AttributeSet, unsigned> asMap;
71009467b48Spatrick unsigned asNext = 0;
71109467b48Spatrick
71209467b48Spatrick /// ModulePathMap - The slot map for Module paths used in the summary index.
71309467b48Spatrick StringMap<unsigned> ModulePathMap;
71409467b48Spatrick unsigned ModulePathNext = 0;
71509467b48Spatrick
71609467b48Spatrick /// GUIDMap - The slot map for GUIDs used in the summary index.
71709467b48Spatrick DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
71809467b48Spatrick unsigned GUIDNext = 0;
71909467b48Spatrick
72009467b48Spatrick /// TypeIdMap - The slot map for type ids used in the summary index.
72109467b48Spatrick StringMap<unsigned> TypeIdMap;
72209467b48Spatrick unsigned TypeIdNext = 0;
72309467b48Spatrick
72409467b48Spatrick public:
72509467b48Spatrick /// Construct from a module.
72609467b48Spatrick ///
72709467b48Spatrick /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
72809467b48Spatrick /// functions, giving correct numbering for metadata referenced only from
72909467b48Spatrick /// within a function (even if no functions have been initialized).
73009467b48Spatrick explicit SlotTracker(const Module *M,
73109467b48Spatrick bool ShouldInitializeAllMetadata = false);
73209467b48Spatrick
73309467b48Spatrick /// Construct from a function, starting out in incorp state.
73409467b48Spatrick ///
73509467b48Spatrick /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
73609467b48Spatrick /// functions, giving correct numbering for metadata referenced only from
73709467b48Spatrick /// within a function (even if no functions have been initialized).
73809467b48Spatrick explicit SlotTracker(const Function *F,
73909467b48Spatrick bool ShouldInitializeAllMetadata = false);
74009467b48Spatrick
74109467b48Spatrick /// Construct from a module summary index.
74209467b48Spatrick explicit SlotTracker(const ModuleSummaryIndex *Index);
74309467b48Spatrick
74409467b48Spatrick SlotTracker(const SlotTracker &) = delete;
74509467b48Spatrick SlotTracker &operator=(const SlotTracker &) = delete;
74609467b48Spatrick
74773471bf0Spatrick ~SlotTracker() = default;
74873471bf0Spatrick
74973471bf0Spatrick void setProcessHook(
75073471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
75173471bf0Spatrick void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
75273471bf0Spatrick const Function *, bool)>);
75373471bf0Spatrick
getNextMetadataSlot()75473471bf0Spatrick unsigned getNextMetadataSlot() override { return mdnNext; }
75573471bf0Spatrick
75673471bf0Spatrick void createMetadataSlot(const MDNode *N) override;
75773471bf0Spatrick
75809467b48Spatrick /// Return the slot number of the specified value in it's type
75909467b48Spatrick /// plane. If something is not in the SlotTracker, return -1.
76009467b48Spatrick int getLocalSlot(const Value *V);
76109467b48Spatrick int getGlobalSlot(const GlobalValue *V);
76273471bf0Spatrick int getMetadataSlot(const MDNode *N) override;
76309467b48Spatrick int getAttributeGroupSlot(AttributeSet AS);
76409467b48Spatrick int getModulePathSlot(StringRef Path);
76509467b48Spatrick int getGUIDSlot(GlobalValue::GUID GUID);
76609467b48Spatrick int getTypeIdSlot(StringRef Id);
76709467b48Spatrick
76809467b48Spatrick /// If you'd like to deal with a function instead of just a module, use
76909467b48Spatrick /// this method to get its data into the SlotTracker.
incorporateFunction(const Function * F)77009467b48Spatrick void incorporateFunction(const Function *F) {
77109467b48Spatrick TheFunction = F;
77209467b48Spatrick FunctionProcessed = false;
77309467b48Spatrick }
77409467b48Spatrick
getFunction() const77509467b48Spatrick const Function *getFunction() const { return TheFunction; }
77609467b48Spatrick
77709467b48Spatrick /// After calling incorporateFunction, use this method to remove the
77809467b48Spatrick /// most recently incorporated function from the SlotTracker. This
77909467b48Spatrick /// will reset the state of the machine back to just the module contents.
78009467b48Spatrick void purgeFunction();
78109467b48Spatrick
78209467b48Spatrick /// MDNode map iterators.
78309467b48Spatrick using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
78409467b48Spatrick
mdn_begin()78509467b48Spatrick mdn_iterator mdn_begin() { return mdnMap.begin(); }
mdn_end()78609467b48Spatrick mdn_iterator mdn_end() { return mdnMap.end(); }
mdn_size() const78709467b48Spatrick unsigned mdn_size() const { return mdnMap.size(); }
mdn_empty() const78809467b48Spatrick bool mdn_empty() const { return mdnMap.empty(); }
78909467b48Spatrick
79009467b48Spatrick /// AttributeSet map iterators.
79109467b48Spatrick using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
79209467b48Spatrick
as_begin()79309467b48Spatrick as_iterator as_begin() { return asMap.begin(); }
as_end()79409467b48Spatrick as_iterator as_end() { return asMap.end(); }
as_size() const79509467b48Spatrick unsigned as_size() const { return asMap.size(); }
as_empty() const79609467b48Spatrick bool as_empty() const { return asMap.empty(); }
79709467b48Spatrick
79809467b48Spatrick /// GUID map iterators.
79909467b48Spatrick using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
80009467b48Spatrick
80109467b48Spatrick /// These functions do the actual initialization.
80209467b48Spatrick inline void initializeIfNeeded();
803097a140dSpatrick int initializeIndexIfNeeded();
80409467b48Spatrick
80509467b48Spatrick // Implementation Details
80609467b48Spatrick private:
80709467b48Spatrick /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
80809467b48Spatrick void CreateModuleSlot(const GlobalValue *V);
80909467b48Spatrick
81009467b48Spatrick /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
81109467b48Spatrick void CreateMetadataSlot(const MDNode *N);
81209467b48Spatrick
81309467b48Spatrick /// CreateFunctionSlot - Insert the specified Value* into the slot table.
81409467b48Spatrick void CreateFunctionSlot(const Value *V);
81509467b48Spatrick
81609467b48Spatrick /// Insert the specified AttributeSet into the slot table.
81709467b48Spatrick void CreateAttributeSetSlot(AttributeSet AS);
81809467b48Spatrick
81909467b48Spatrick inline void CreateModulePathSlot(StringRef Path);
82009467b48Spatrick void CreateGUIDSlot(GlobalValue::GUID GUID);
82109467b48Spatrick void CreateTypeIdSlot(StringRef Id);
82209467b48Spatrick
82309467b48Spatrick /// Add all of the module level global variables (and their initializers)
82409467b48Spatrick /// and function declarations, but not the contents of those functions.
82509467b48Spatrick void processModule();
826097a140dSpatrick // Returns number of allocated slots
827097a140dSpatrick int processIndex();
82809467b48Spatrick
82909467b48Spatrick /// Add all of the functions arguments, basic blocks, and instructions.
83009467b48Spatrick void processFunction();
83109467b48Spatrick
83209467b48Spatrick /// Add the metadata directly attached to a GlobalObject.
83309467b48Spatrick void processGlobalObjectMetadata(const GlobalObject &GO);
83409467b48Spatrick
83509467b48Spatrick /// Add all of the metadata from a function.
83609467b48Spatrick void processFunctionMetadata(const Function &F);
83709467b48Spatrick
83809467b48Spatrick /// Add all of the metadata from an instruction.
83909467b48Spatrick void processInstructionMetadata(const Instruction &I);
84009467b48Spatrick };
84109467b48Spatrick
84209467b48Spatrick } // end namespace llvm
84309467b48Spatrick
ModuleSlotTracker(SlotTracker & Machine,const Module * M,const Function * F)84409467b48Spatrick ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
84509467b48Spatrick const Function *F)
84609467b48Spatrick : M(M), F(F), Machine(&Machine) {}
84709467b48Spatrick
ModuleSlotTracker(const Module * M,bool ShouldInitializeAllMetadata)84809467b48Spatrick ModuleSlotTracker::ModuleSlotTracker(const Module *M,
84909467b48Spatrick bool ShouldInitializeAllMetadata)
85009467b48Spatrick : ShouldCreateStorage(M),
85109467b48Spatrick ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
85209467b48Spatrick
85309467b48Spatrick ModuleSlotTracker::~ModuleSlotTracker() = default;
85409467b48Spatrick
getMachine()85509467b48Spatrick SlotTracker *ModuleSlotTracker::getMachine() {
85609467b48Spatrick if (!ShouldCreateStorage)
85709467b48Spatrick return Machine;
85809467b48Spatrick
85909467b48Spatrick ShouldCreateStorage = false;
86009467b48Spatrick MachineStorage =
86109467b48Spatrick std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
86209467b48Spatrick Machine = MachineStorage.get();
86373471bf0Spatrick if (ProcessModuleHookFn)
86473471bf0Spatrick Machine->setProcessHook(ProcessModuleHookFn);
86573471bf0Spatrick if (ProcessFunctionHookFn)
86673471bf0Spatrick Machine->setProcessHook(ProcessFunctionHookFn);
86709467b48Spatrick return Machine;
86809467b48Spatrick }
86909467b48Spatrick
incorporateFunction(const Function & F)87009467b48Spatrick void ModuleSlotTracker::incorporateFunction(const Function &F) {
87109467b48Spatrick // Using getMachine() may lazily create the slot tracker.
87209467b48Spatrick if (!getMachine())
87309467b48Spatrick return;
87409467b48Spatrick
87509467b48Spatrick // Nothing to do if this is the right function already.
87609467b48Spatrick if (this->F == &F)
87709467b48Spatrick return;
87809467b48Spatrick if (this->F)
87909467b48Spatrick Machine->purgeFunction();
88009467b48Spatrick Machine->incorporateFunction(&F);
88109467b48Spatrick this->F = &F;
88209467b48Spatrick }
88309467b48Spatrick
getLocalSlot(const Value * V)88409467b48Spatrick int ModuleSlotTracker::getLocalSlot(const Value *V) {
88509467b48Spatrick assert(F && "No function incorporated");
88609467b48Spatrick return Machine->getLocalSlot(V);
88709467b48Spatrick }
88809467b48Spatrick
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Module *,bool)> Fn)88973471bf0Spatrick void ModuleSlotTracker::setProcessHook(
89073471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
89173471bf0Spatrick Fn) {
89273471bf0Spatrick ProcessModuleHookFn = Fn;
89373471bf0Spatrick }
89473471bf0Spatrick
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Function *,bool)> Fn)89573471bf0Spatrick void ModuleSlotTracker::setProcessHook(
89673471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
89773471bf0Spatrick Fn) {
89873471bf0Spatrick ProcessFunctionHookFn = Fn;
89973471bf0Spatrick }
90073471bf0Spatrick
createSlotTracker(const Value * V)90109467b48Spatrick static SlotTracker *createSlotTracker(const Value *V) {
90209467b48Spatrick if (const Argument *FA = dyn_cast<Argument>(V))
90309467b48Spatrick return new SlotTracker(FA->getParent());
90409467b48Spatrick
90509467b48Spatrick if (const Instruction *I = dyn_cast<Instruction>(V))
90609467b48Spatrick if (I->getParent())
90709467b48Spatrick return new SlotTracker(I->getParent()->getParent());
90809467b48Spatrick
90909467b48Spatrick if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
91009467b48Spatrick return new SlotTracker(BB->getParent());
91109467b48Spatrick
91209467b48Spatrick if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
91309467b48Spatrick return new SlotTracker(GV->getParent());
91409467b48Spatrick
91509467b48Spatrick if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
91609467b48Spatrick return new SlotTracker(GA->getParent());
91709467b48Spatrick
91809467b48Spatrick if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
91909467b48Spatrick return new SlotTracker(GIF->getParent());
92009467b48Spatrick
92109467b48Spatrick if (const Function *Func = dyn_cast<Function>(V))
92209467b48Spatrick return new SlotTracker(Func);
92309467b48Spatrick
92409467b48Spatrick return nullptr;
92509467b48Spatrick }
92609467b48Spatrick
92709467b48Spatrick #if 0
92809467b48Spatrick #define ST_DEBUG(X) dbgs() << X
92909467b48Spatrick #else
93009467b48Spatrick #define ST_DEBUG(X)
93109467b48Spatrick #endif
93209467b48Spatrick
93309467b48Spatrick // Module level constructor. Causes the contents of the Module (sans functions)
93409467b48Spatrick // to be added to the slot table.
SlotTracker(const Module * M,bool ShouldInitializeAllMetadata)93509467b48Spatrick SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
93609467b48Spatrick : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
93709467b48Spatrick
93809467b48Spatrick // Function level constructor. Causes the contents of the Module and the one
93909467b48Spatrick // function provided to be added to the slot table.
SlotTracker(const Function * F,bool ShouldInitializeAllMetadata)94009467b48Spatrick SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
94109467b48Spatrick : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
94209467b48Spatrick ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
94309467b48Spatrick
SlotTracker(const ModuleSummaryIndex * Index)94409467b48Spatrick SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
94509467b48Spatrick : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
94609467b48Spatrick
initializeIfNeeded()94709467b48Spatrick inline void SlotTracker::initializeIfNeeded() {
94809467b48Spatrick if (TheModule) {
94909467b48Spatrick processModule();
95009467b48Spatrick TheModule = nullptr; ///< Prevent re-processing next time we're called.
95109467b48Spatrick }
95209467b48Spatrick
95309467b48Spatrick if (TheFunction && !FunctionProcessed)
95409467b48Spatrick processFunction();
95509467b48Spatrick }
95609467b48Spatrick
initializeIndexIfNeeded()957097a140dSpatrick int SlotTracker::initializeIndexIfNeeded() {
95809467b48Spatrick if (!TheIndex)
959097a140dSpatrick return 0;
960097a140dSpatrick int NumSlots = processIndex();
96109467b48Spatrick TheIndex = nullptr; ///< Prevent re-processing next time we're called.
962097a140dSpatrick return NumSlots;
96309467b48Spatrick }
96409467b48Spatrick
96509467b48Spatrick // Iterate through all the global variables, functions, and global
96609467b48Spatrick // variable initializers and create slots for them.
processModule()96709467b48Spatrick void SlotTracker::processModule() {
96809467b48Spatrick ST_DEBUG("begin processModule!\n");
96909467b48Spatrick
97009467b48Spatrick // Add all of the unnamed global variables to the value table.
97109467b48Spatrick for (const GlobalVariable &Var : TheModule->globals()) {
97209467b48Spatrick if (!Var.hasName())
97309467b48Spatrick CreateModuleSlot(&Var);
97409467b48Spatrick processGlobalObjectMetadata(Var);
97509467b48Spatrick auto Attrs = Var.getAttributes();
97609467b48Spatrick if (Attrs.hasAttributes())
97709467b48Spatrick CreateAttributeSetSlot(Attrs);
97809467b48Spatrick }
97909467b48Spatrick
98009467b48Spatrick for (const GlobalAlias &A : TheModule->aliases()) {
98109467b48Spatrick if (!A.hasName())
98209467b48Spatrick CreateModuleSlot(&A);
98309467b48Spatrick }
98409467b48Spatrick
98509467b48Spatrick for (const GlobalIFunc &I : TheModule->ifuncs()) {
98609467b48Spatrick if (!I.hasName())
98709467b48Spatrick CreateModuleSlot(&I);
98809467b48Spatrick }
98909467b48Spatrick
99009467b48Spatrick // Add metadata used by named metadata.
99109467b48Spatrick for (const NamedMDNode &NMD : TheModule->named_metadata()) {
99209467b48Spatrick for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
99309467b48Spatrick CreateMetadataSlot(NMD.getOperand(i));
99409467b48Spatrick }
99509467b48Spatrick
99609467b48Spatrick for (const Function &F : *TheModule) {
99709467b48Spatrick if (!F.hasName())
99809467b48Spatrick // Add all the unnamed functions to the table.
99909467b48Spatrick CreateModuleSlot(&F);
100009467b48Spatrick
100109467b48Spatrick if (ShouldInitializeAllMetadata)
100209467b48Spatrick processFunctionMetadata(F);
100309467b48Spatrick
100409467b48Spatrick // Add all the function attributes to the table.
100509467b48Spatrick // FIXME: Add attributes of other objects?
1006*d415bd75Srobert AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
100709467b48Spatrick if (FnAttrs.hasAttributes())
100809467b48Spatrick CreateAttributeSetSlot(FnAttrs);
100909467b48Spatrick }
101009467b48Spatrick
101173471bf0Spatrick if (ProcessModuleHookFn)
101273471bf0Spatrick ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
101373471bf0Spatrick
101409467b48Spatrick ST_DEBUG("end processModule!\n");
101509467b48Spatrick }
101609467b48Spatrick
101709467b48Spatrick // Process the arguments, basic blocks, and instructions of a function.
processFunction()101809467b48Spatrick void SlotTracker::processFunction() {
101909467b48Spatrick ST_DEBUG("begin processFunction!\n");
102009467b48Spatrick fNext = 0;
102109467b48Spatrick
102209467b48Spatrick // Process function metadata if it wasn't hit at the module-level.
102309467b48Spatrick if (!ShouldInitializeAllMetadata)
102409467b48Spatrick processFunctionMetadata(*TheFunction);
102509467b48Spatrick
102609467b48Spatrick // Add all the function arguments with no names.
102709467b48Spatrick for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
102809467b48Spatrick AE = TheFunction->arg_end(); AI != AE; ++AI)
102909467b48Spatrick if (!AI->hasName())
103009467b48Spatrick CreateFunctionSlot(&*AI);
103109467b48Spatrick
103209467b48Spatrick ST_DEBUG("Inserting Instructions:\n");
103309467b48Spatrick
103409467b48Spatrick // Add all of the basic blocks and instructions with no names.
103509467b48Spatrick for (auto &BB : *TheFunction) {
103609467b48Spatrick if (!BB.hasName())
103709467b48Spatrick CreateFunctionSlot(&BB);
103809467b48Spatrick
103909467b48Spatrick for (auto &I : BB) {
104009467b48Spatrick if (!I.getType()->isVoidTy() && !I.hasName())
104109467b48Spatrick CreateFunctionSlot(&I);
104209467b48Spatrick
104309467b48Spatrick // We allow direct calls to any llvm.foo function here, because the
104409467b48Spatrick // target may not be linked into the optimizer.
104509467b48Spatrick if (const auto *Call = dyn_cast<CallBase>(&I)) {
104609467b48Spatrick // Add all the call attributes to the table.
1047*d415bd75Srobert AttributeSet Attrs = Call->getAttributes().getFnAttrs();
104809467b48Spatrick if (Attrs.hasAttributes())
104909467b48Spatrick CreateAttributeSetSlot(Attrs);
105009467b48Spatrick }
105109467b48Spatrick }
105209467b48Spatrick }
105309467b48Spatrick
105473471bf0Spatrick if (ProcessFunctionHookFn)
105573471bf0Spatrick ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
105673471bf0Spatrick
105709467b48Spatrick FunctionProcessed = true;
105809467b48Spatrick
105909467b48Spatrick ST_DEBUG("end processFunction!\n");
106009467b48Spatrick }
106109467b48Spatrick
106209467b48Spatrick // Iterate through all the GUID in the index and create slots for them.
processIndex()1063097a140dSpatrick int SlotTracker::processIndex() {
106409467b48Spatrick ST_DEBUG("begin processIndex!\n");
106509467b48Spatrick assert(TheIndex);
106609467b48Spatrick
106709467b48Spatrick // The first block of slots are just the module ids, which start at 0 and are
106809467b48Spatrick // assigned consecutively. Since the StringMap iteration order isn't
106909467b48Spatrick // guaranteed, use a std::map to order by module ID before assigning slots.
107009467b48Spatrick std::map<uint64_t, StringRef> ModuleIdToPathMap;
1071*d415bd75Srobert for (auto &[ModPath, ModId] : TheIndex->modulePaths())
1072*d415bd75Srobert ModuleIdToPathMap[ModId.first] = ModPath;
107309467b48Spatrick for (auto &ModPair : ModuleIdToPathMap)
107409467b48Spatrick CreateModulePathSlot(ModPair.second);
107509467b48Spatrick
107609467b48Spatrick // Start numbering the GUIDs after the module ids.
107709467b48Spatrick GUIDNext = ModulePathNext;
107809467b48Spatrick
107909467b48Spatrick for (auto &GlobalList : *TheIndex)
108009467b48Spatrick CreateGUIDSlot(GlobalList.first);
108109467b48Spatrick
1082097a140dSpatrick for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1083097a140dSpatrick CreateGUIDSlot(GlobalValue::getGUID(TId.first));
1084097a140dSpatrick
108509467b48Spatrick // Start numbering the TypeIds after the GUIDs.
108609467b48Spatrick TypeIdNext = GUIDNext;
108773471bf0Spatrick for (const auto &TID : TheIndex->typeIds())
108873471bf0Spatrick CreateTypeIdSlot(TID.second.first);
108909467b48Spatrick
109009467b48Spatrick ST_DEBUG("end processIndex!\n");
1091097a140dSpatrick return TypeIdNext;
109209467b48Spatrick }
109309467b48Spatrick
processGlobalObjectMetadata(const GlobalObject & GO)109409467b48Spatrick void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
109509467b48Spatrick SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
109609467b48Spatrick GO.getAllMetadata(MDs);
109709467b48Spatrick for (auto &MD : MDs)
109809467b48Spatrick CreateMetadataSlot(MD.second);
109909467b48Spatrick }
110009467b48Spatrick
processFunctionMetadata(const Function & F)110109467b48Spatrick void SlotTracker::processFunctionMetadata(const Function &F) {
110209467b48Spatrick processGlobalObjectMetadata(F);
110309467b48Spatrick for (auto &BB : F) {
110409467b48Spatrick for (auto &I : BB)
110509467b48Spatrick processInstructionMetadata(I);
110609467b48Spatrick }
110709467b48Spatrick }
110809467b48Spatrick
processInstructionMetadata(const Instruction & I)110909467b48Spatrick void SlotTracker::processInstructionMetadata(const Instruction &I) {
111009467b48Spatrick // Process metadata used directly by intrinsics.
111109467b48Spatrick if (const CallInst *CI = dyn_cast<CallInst>(&I))
111209467b48Spatrick if (Function *F = CI->getCalledFunction())
111309467b48Spatrick if (F->isIntrinsic())
111409467b48Spatrick for (auto &Op : I.operands())
111509467b48Spatrick if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
111609467b48Spatrick if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
111709467b48Spatrick CreateMetadataSlot(N);
111809467b48Spatrick
111909467b48Spatrick // Process metadata attached to this instruction.
112009467b48Spatrick SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
112109467b48Spatrick I.getAllMetadata(MDs);
112209467b48Spatrick for (auto &MD : MDs)
112309467b48Spatrick CreateMetadataSlot(MD.second);
112409467b48Spatrick }
112509467b48Spatrick
112609467b48Spatrick /// Clean up after incorporating a function. This is the only way to get out of
112709467b48Spatrick /// the function incorporation state that affects get*Slot/Create*Slot. Function
112809467b48Spatrick /// incorporation state is indicated by TheFunction != 0.
purgeFunction()112909467b48Spatrick void SlotTracker::purgeFunction() {
113009467b48Spatrick ST_DEBUG("begin purgeFunction!\n");
113109467b48Spatrick fMap.clear(); // Simply discard the function level map
113209467b48Spatrick TheFunction = nullptr;
113309467b48Spatrick FunctionProcessed = false;
113409467b48Spatrick ST_DEBUG("end purgeFunction!\n");
113509467b48Spatrick }
113609467b48Spatrick
113709467b48Spatrick /// getGlobalSlot - Get the slot number of a global value.
getGlobalSlot(const GlobalValue * V)113809467b48Spatrick int SlotTracker::getGlobalSlot(const GlobalValue *V) {
113909467b48Spatrick // Check for uninitialized state and do lazy initialization.
114009467b48Spatrick initializeIfNeeded();
114109467b48Spatrick
114209467b48Spatrick // Find the value in the module map
114309467b48Spatrick ValueMap::iterator MI = mMap.find(V);
114409467b48Spatrick return MI == mMap.end() ? -1 : (int)MI->second;
114509467b48Spatrick }
114609467b48Spatrick
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Module *,bool)> Fn)114773471bf0Spatrick void SlotTracker::setProcessHook(
114873471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
114973471bf0Spatrick Fn) {
115073471bf0Spatrick ProcessModuleHookFn = Fn;
115173471bf0Spatrick }
115273471bf0Spatrick
setProcessHook(std::function<void (AbstractSlotTrackerStorage *,const Function *,bool)> Fn)115373471bf0Spatrick void SlotTracker::setProcessHook(
115473471bf0Spatrick std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
115573471bf0Spatrick Fn) {
115673471bf0Spatrick ProcessFunctionHookFn = Fn;
115773471bf0Spatrick }
115873471bf0Spatrick
115973471bf0Spatrick /// getMetadataSlot - Get the slot number of a MDNode.
createMetadataSlot(const MDNode * N)116073471bf0Spatrick void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
116173471bf0Spatrick
116209467b48Spatrick /// getMetadataSlot - Get the slot number of a MDNode.
getMetadataSlot(const MDNode * N)116309467b48Spatrick int SlotTracker::getMetadataSlot(const MDNode *N) {
116409467b48Spatrick // Check for uninitialized state and do lazy initialization.
116509467b48Spatrick initializeIfNeeded();
116609467b48Spatrick
116709467b48Spatrick // Find the MDNode in the module map
116809467b48Spatrick mdn_iterator MI = mdnMap.find(N);
116909467b48Spatrick return MI == mdnMap.end() ? -1 : (int)MI->second;
117009467b48Spatrick }
117109467b48Spatrick
117209467b48Spatrick /// getLocalSlot - Get the slot number for a value that is local to a function.
getLocalSlot(const Value * V)117309467b48Spatrick int SlotTracker::getLocalSlot(const Value *V) {
117409467b48Spatrick assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
117509467b48Spatrick
117609467b48Spatrick // Check for uninitialized state and do lazy initialization.
117709467b48Spatrick initializeIfNeeded();
117809467b48Spatrick
117909467b48Spatrick ValueMap::iterator FI = fMap.find(V);
118009467b48Spatrick return FI == fMap.end() ? -1 : (int)FI->second;
118109467b48Spatrick }
118209467b48Spatrick
getAttributeGroupSlot(AttributeSet AS)118309467b48Spatrick int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
118409467b48Spatrick // Check for uninitialized state and do lazy initialization.
118509467b48Spatrick initializeIfNeeded();
118609467b48Spatrick
118709467b48Spatrick // Find the AttributeSet in the module map.
118809467b48Spatrick as_iterator AI = asMap.find(AS);
118909467b48Spatrick return AI == asMap.end() ? -1 : (int)AI->second;
119009467b48Spatrick }
119109467b48Spatrick
getModulePathSlot(StringRef Path)119209467b48Spatrick int SlotTracker::getModulePathSlot(StringRef Path) {
119309467b48Spatrick // Check for uninitialized state and do lazy initialization.
119409467b48Spatrick initializeIndexIfNeeded();
119509467b48Spatrick
119609467b48Spatrick // Find the Module path in the map
119709467b48Spatrick auto I = ModulePathMap.find(Path);
119809467b48Spatrick return I == ModulePathMap.end() ? -1 : (int)I->second;
119909467b48Spatrick }
120009467b48Spatrick
getGUIDSlot(GlobalValue::GUID GUID)120109467b48Spatrick int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
120209467b48Spatrick // Check for uninitialized state and do lazy initialization.
120309467b48Spatrick initializeIndexIfNeeded();
120409467b48Spatrick
120509467b48Spatrick // Find the GUID in the map
120609467b48Spatrick guid_iterator I = GUIDMap.find(GUID);
120709467b48Spatrick return I == GUIDMap.end() ? -1 : (int)I->second;
120809467b48Spatrick }
120909467b48Spatrick
getTypeIdSlot(StringRef Id)121009467b48Spatrick int SlotTracker::getTypeIdSlot(StringRef Id) {
121109467b48Spatrick // Check for uninitialized state and do lazy initialization.
121209467b48Spatrick initializeIndexIfNeeded();
121309467b48Spatrick
121409467b48Spatrick // Find the TypeId string in the map
121509467b48Spatrick auto I = TypeIdMap.find(Id);
121609467b48Spatrick return I == TypeIdMap.end() ? -1 : (int)I->second;
121709467b48Spatrick }
121809467b48Spatrick
121909467b48Spatrick /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
CreateModuleSlot(const GlobalValue * V)122009467b48Spatrick void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
122109467b48Spatrick assert(V && "Can't insert a null Value into SlotTracker!");
122209467b48Spatrick assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
122309467b48Spatrick assert(!V->hasName() && "Doesn't need a slot!");
122409467b48Spatrick
122509467b48Spatrick unsigned DestSlot = mNext++;
122609467b48Spatrick mMap[V] = DestSlot;
122709467b48Spatrick
122809467b48Spatrick ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
122909467b48Spatrick DestSlot << " [");
123009467b48Spatrick // G = Global, F = Function, A = Alias, I = IFunc, o = other
123109467b48Spatrick ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
123209467b48Spatrick (isa<Function>(V) ? 'F' :
123309467b48Spatrick (isa<GlobalAlias>(V) ? 'A' :
123409467b48Spatrick (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
123509467b48Spatrick }
123609467b48Spatrick
123709467b48Spatrick /// CreateSlot - Create a new slot for the specified value if it has no name.
CreateFunctionSlot(const Value * V)123809467b48Spatrick void SlotTracker::CreateFunctionSlot(const Value *V) {
123909467b48Spatrick assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
124009467b48Spatrick
124109467b48Spatrick unsigned DestSlot = fNext++;
124209467b48Spatrick fMap[V] = DestSlot;
124309467b48Spatrick
124409467b48Spatrick // G = Global, F = Function, o = other
124509467b48Spatrick ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
124609467b48Spatrick DestSlot << " [o]\n");
124709467b48Spatrick }
124809467b48Spatrick
124909467b48Spatrick /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
CreateMetadataSlot(const MDNode * N)125009467b48Spatrick void SlotTracker::CreateMetadataSlot(const MDNode *N) {
125109467b48Spatrick assert(N && "Can't insert a null Value into SlotTracker!");
125209467b48Spatrick
125373471bf0Spatrick // Don't make slots for DIExpressions or DIArgLists. We just print them inline
125473471bf0Spatrick // everywhere.
125573471bf0Spatrick if (isa<DIExpression>(N) || isa<DIArgList>(N))
125609467b48Spatrick return;
125709467b48Spatrick
125809467b48Spatrick unsigned DestSlot = mdnNext;
125909467b48Spatrick if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
126009467b48Spatrick return;
126109467b48Spatrick ++mdnNext;
126209467b48Spatrick
126309467b48Spatrick // Recursively add any MDNodes referenced by operands.
126409467b48Spatrick for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
126509467b48Spatrick if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
126609467b48Spatrick CreateMetadataSlot(Op);
126709467b48Spatrick }
126809467b48Spatrick
CreateAttributeSetSlot(AttributeSet AS)126909467b48Spatrick void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
127009467b48Spatrick assert(AS.hasAttributes() && "Doesn't need a slot!");
127109467b48Spatrick
127209467b48Spatrick as_iterator I = asMap.find(AS);
127309467b48Spatrick if (I != asMap.end())
127409467b48Spatrick return;
127509467b48Spatrick
127609467b48Spatrick unsigned DestSlot = asNext++;
127709467b48Spatrick asMap[AS] = DestSlot;
127809467b48Spatrick }
127909467b48Spatrick
128009467b48Spatrick /// Create a new slot for the specified Module
CreateModulePathSlot(StringRef Path)128109467b48Spatrick void SlotTracker::CreateModulePathSlot(StringRef Path) {
128209467b48Spatrick ModulePathMap[Path] = ModulePathNext++;
128309467b48Spatrick }
128409467b48Spatrick
128509467b48Spatrick /// Create a new slot for the specified GUID
CreateGUIDSlot(GlobalValue::GUID GUID)128609467b48Spatrick void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
128709467b48Spatrick GUIDMap[GUID] = GUIDNext++;
128809467b48Spatrick }
128909467b48Spatrick
129009467b48Spatrick /// Create a new slot for the specified Id
CreateTypeIdSlot(StringRef Id)129109467b48Spatrick void SlotTracker::CreateTypeIdSlot(StringRef Id) {
129209467b48Spatrick TypeIdMap[Id] = TypeIdNext++;
129309467b48Spatrick }
129409467b48Spatrick
1295*d415bd75Srobert namespace {
1296*d415bd75Srobert /// Common instances used by most of the printer functions.
1297*d415bd75Srobert struct AsmWriterContext {
1298*d415bd75Srobert TypePrinting *TypePrinter = nullptr;
1299*d415bd75Srobert SlotTracker *Machine = nullptr;
1300*d415bd75Srobert const Module *Context = nullptr;
1301*d415bd75Srobert
AsmWriterContext__anon4f18fdef0511::AsmWriterContext1302*d415bd75Srobert AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1303*d415bd75Srobert : TypePrinter(TP), Machine(ST), Context(M) {}
1304*d415bd75Srobert
getEmpty__anon4f18fdef0511::AsmWriterContext1305*d415bd75Srobert static AsmWriterContext &getEmpty() {
1306*d415bd75Srobert static AsmWriterContext EmptyCtx(nullptr, nullptr);
1307*d415bd75Srobert return EmptyCtx;
1308*d415bd75Srobert }
1309*d415bd75Srobert
1310*d415bd75Srobert /// A callback that will be triggered when the underlying printer
1311*d415bd75Srobert /// prints a Metadata as operand.
onWriteMetadataAsOperand__anon4f18fdef0511::AsmWriterContext1312*d415bd75Srobert virtual void onWriteMetadataAsOperand(const Metadata *) {}
1313*d415bd75Srobert
1314*d415bd75Srobert virtual ~AsmWriterContext() = default;
1315*d415bd75Srobert };
1316*d415bd75Srobert } // end anonymous namespace
1317*d415bd75Srobert
131809467b48Spatrick //===----------------------------------------------------------------------===//
131909467b48Spatrick // AsmWriter Implementation
132009467b48Spatrick //===----------------------------------------------------------------------===//
132109467b48Spatrick
132209467b48Spatrick static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1323*d415bd75Srobert AsmWriterContext &WriterCtx);
132409467b48Spatrick
132509467b48Spatrick static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1326*d415bd75Srobert AsmWriterContext &WriterCtx,
132709467b48Spatrick bool FromValue = false);
132809467b48Spatrick
WriteOptimizationInfo(raw_ostream & Out,const User * U)132909467b48Spatrick static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1330*d415bd75Srobert if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1331*d415bd75Srobert Out << FPO->getFastMathFlags();
133209467b48Spatrick
133309467b48Spatrick if (const OverflowingBinaryOperator *OBO =
133409467b48Spatrick dyn_cast<OverflowingBinaryOperator>(U)) {
133509467b48Spatrick if (OBO->hasNoUnsignedWrap())
133609467b48Spatrick Out << " nuw";
133709467b48Spatrick if (OBO->hasNoSignedWrap())
133809467b48Spatrick Out << " nsw";
133909467b48Spatrick } else if (const PossiblyExactOperator *Div =
134009467b48Spatrick dyn_cast<PossiblyExactOperator>(U)) {
134109467b48Spatrick if (Div->isExact())
134209467b48Spatrick Out << " exact";
134309467b48Spatrick } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
134409467b48Spatrick if (GEP->isInBounds())
134509467b48Spatrick Out << " inbounds";
134609467b48Spatrick }
134709467b48Spatrick }
134809467b48Spatrick
WriteConstantInternal(raw_ostream & Out,const Constant * CV,AsmWriterContext & WriterCtx)134909467b48Spatrick static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1350*d415bd75Srobert AsmWriterContext &WriterCtx) {
135109467b48Spatrick if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
135209467b48Spatrick if (CI->getType()->isIntegerTy(1)) {
135309467b48Spatrick Out << (CI->getZExtValue() ? "true" : "false");
135409467b48Spatrick return;
135509467b48Spatrick }
135609467b48Spatrick Out << CI->getValue();
135709467b48Spatrick return;
135809467b48Spatrick }
135909467b48Spatrick
136009467b48Spatrick if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
136109467b48Spatrick const APFloat &APF = CFP->getValueAPF();
136209467b48Spatrick if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
136309467b48Spatrick &APF.getSemantics() == &APFloat::IEEEdouble()) {
136409467b48Spatrick // We would like to output the FP constant value in exponential notation,
136509467b48Spatrick // but we cannot do this if doing so will lose precision. Check here to
136609467b48Spatrick // make sure that we only output it in exponential format if we can parse
136709467b48Spatrick // the value back and get the same value.
136809467b48Spatrick //
136909467b48Spatrick bool ignored;
137009467b48Spatrick bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
137109467b48Spatrick bool isInf = APF.isInfinity();
137209467b48Spatrick bool isNaN = APF.isNaN();
137309467b48Spatrick if (!isInf && !isNaN) {
137473471bf0Spatrick double Val = APF.convertToDouble();
137509467b48Spatrick SmallString<128> StrVal;
137609467b48Spatrick APF.toString(StrVal, 6, 0, false);
137709467b48Spatrick // Check to make sure that the stringized number is not some string like
137809467b48Spatrick // "Inf" or NaN, that atof will accept, but the lexer will not. Check
137909467b48Spatrick // that the string matches the "[-+]?[0-9]" regex.
138009467b48Spatrick //
138173471bf0Spatrick assert((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') &&
138273471bf0Spatrick isDigit(StrVal[1]))) &&
138309467b48Spatrick "[-+]?[0-9] regex does not match!");
138409467b48Spatrick // Reparse stringized version!
138509467b48Spatrick if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
138609467b48Spatrick Out << StrVal;
138709467b48Spatrick return;
138809467b48Spatrick }
138909467b48Spatrick }
139009467b48Spatrick // Otherwise we could not reparse it to exactly the same value, so we must
139109467b48Spatrick // output the string in hexadecimal format! Note that loading and storing
139209467b48Spatrick // floating point types changes the bits of NaNs on some hosts, notably
139309467b48Spatrick // x86, so we must not use these types.
139409467b48Spatrick static_assert(sizeof(double) == sizeof(uint64_t),
139509467b48Spatrick "assuming that double is 64 bits!");
139609467b48Spatrick APFloat apf = APF;
139709467b48Spatrick // Floats are represented in ASCII IR as double, convert.
139873471bf0Spatrick // FIXME: We should allow 32-bit hex float and remove this.
139973471bf0Spatrick if (!isDouble) {
140073471bf0Spatrick // A signaling NaN is quieted on conversion, so we need to recreate the
140173471bf0Spatrick // expected value after convert (quiet bit of the payload is clear).
140273471bf0Spatrick bool IsSNAN = apf.isSignaling();
140309467b48Spatrick apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
140409467b48Spatrick &ignored);
140573471bf0Spatrick if (IsSNAN) {
140673471bf0Spatrick APInt Payload = apf.bitcastToAPInt();
140773471bf0Spatrick apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(),
140873471bf0Spatrick &Payload);
140973471bf0Spatrick }
141073471bf0Spatrick }
141109467b48Spatrick Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
141209467b48Spatrick return;
141309467b48Spatrick }
141409467b48Spatrick
1415097a140dSpatrick // Either half, bfloat or some form of long double.
141609467b48Spatrick // These appear as a magic letter identifying the type, then a
141709467b48Spatrick // fixed number of hex digits.
141809467b48Spatrick Out << "0x";
141909467b48Spatrick APInt API = APF.bitcastToAPInt();
142009467b48Spatrick if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
142109467b48Spatrick Out << 'K';
142209467b48Spatrick Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
142309467b48Spatrick /*Upper=*/true);
142409467b48Spatrick Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
142509467b48Spatrick /*Upper=*/true);
142609467b48Spatrick return;
142709467b48Spatrick } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
142809467b48Spatrick Out << 'L';
142909467b48Spatrick Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
143009467b48Spatrick /*Upper=*/true);
143109467b48Spatrick Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
143209467b48Spatrick /*Upper=*/true);
143309467b48Spatrick } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
143409467b48Spatrick Out << 'M';
143509467b48Spatrick Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
143609467b48Spatrick /*Upper=*/true);
143709467b48Spatrick Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
143809467b48Spatrick /*Upper=*/true);
143909467b48Spatrick } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
144009467b48Spatrick Out << 'H';
144109467b48Spatrick Out << format_hex_no_prefix(API.getZExtValue(), 4,
144209467b48Spatrick /*Upper=*/true);
1443097a140dSpatrick } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1444097a140dSpatrick Out << 'R';
1445097a140dSpatrick Out << format_hex_no_prefix(API.getZExtValue(), 4,
1446097a140dSpatrick /*Upper=*/true);
144709467b48Spatrick } else
144809467b48Spatrick llvm_unreachable("Unsupported floating point type");
144909467b48Spatrick return;
145009467b48Spatrick }
145109467b48Spatrick
1452*d415bd75Srobert if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
145309467b48Spatrick Out << "zeroinitializer";
145409467b48Spatrick return;
145509467b48Spatrick }
145609467b48Spatrick
145709467b48Spatrick if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
145809467b48Spatrick Out << "blockaddress(";
1459*d415bd75Srobert WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
146009467b48Spatrick Out << ", ";
1461*d415bd75Srobert WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
146209467b48Spatrick Out << ")";
146309467b48Spatrick return;
146409467b48Spatrick }
146509467b48Spatrick
146673471bf0Spatrick if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
146773471bf0Spatrick Out << "dso_local_equivalent ";
1468*d415bd75Srobert WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1469*d415bd75Srobert return;
1470*d415bd75Srobert }
1471*d415bd75Srobert
1472*d415bd75Srobert if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
1473*d415bd75Srobert Out << "no_cfi ";
1474*d415bd75Srobert WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
147573471bf0Spatrick return;
147673471bf0Spatrick }
147773471bf0Spatrick
147809467b48Spatrick if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
147909467b48Spatrick Type *ETy = CA->getType()->getElementType();
148009467b48Spatrick Out << '[';
1481*d415bd75Srobert WriterCtx.TypePrinter->print(ETy, Out);
148209467b48Spatrick Out << ' ';
1483*d415bd75Srobert WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
148409467b48Spatrick for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
148509467b48Spatrick Out << ", ";
1486*d415bd75Srobert WriterCtx.TypePrinter->print(ETy, Out);
148709467b48Spatrick Out << ' ';
1488*d415bd75Srobert WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
148909467b48Spatrick }
149009467b48Spatrick Out << ']';
149109467b48Spatrick return;
149209467b48Spatrick }
149309467b48Spatrick
149409467b48Spatrick if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
149509467b48Spatrick // As a special case, print the array as a string if it is an array of
149609467b48Spatrick // i8 with ConstantInt values.
149709467b48Spatrick if (CA->isString()) {
149809467b48Spatrick Out << "c\"";
149909467b48Spatrick printEscapedString(CA->getAsString(), Out);
150009467b48Spatrick Out << '"';
150109467b48Spatrick return;
150209467b48Spatrick }
150309467b48Spatrick
150409467b48Spatrick Type *ETy = CA->getType()->getElementType();
150509467b48Spatrick Out << '[';
1506*d415bd75Srobert WriterCtx.TypePrinter->print(ETy, Out);
150709467b48Spatrick Out << ' ';
1508*d415bd75Srobert WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
150909467b48Spatrick for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
151009467b48Spatrick Out << ", ";
1511*d415bd75Srobert WriterCtx.TypePrinter->print(ETy, Out);
151209467b48Spatrick Out << ' ';
1513*d415bd75Srobert WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
151409467b48Spatrick }
151509467b48Spatrick Out << ']';
151609467b48Spatrick return;
151709467b48Spatrick }
151809467b48Spatrick
151909467b48Spatrick if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
152009467b48Spatrick if (CS->getType()->isPacked())
152109467b48Spatrick Out << '<';
152209467b48Spatrick Out << '{';
152309467b48Spatrick unsigned N = CS->getNumOperands();
152409467b48Spatrick if (N) {
152509467b48Spatrick Out << ' ';
1526*d415bd75Srobert WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
152709467b48Spatrick Out << ' ';
152809467b48Spatrick
1529*d415bd75Srobert WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
153009467b48Spatrick
153109467b48Spatrick for (unsigned i = 1; i < N; i++) {
153209467b48Spatrick Out << ", ";
1533*d415bd75Srobert WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
153409467b48Spatrick Out << ' ';
153509467b48Spatrick
1536*d415bd75Srobert WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
153709467b48Spatrick }
153809467b48Spatrick Out << ' ';
153909467b48Spatrick }
154009467b48Spatrick
154109467b48Spatrick Out << '}';
154209467b48Spatrick if (CS->getType()->isPacked())
154309467b48Spatrick Out << '>';
154409467b48Spatrick return;
154509467b48Spatrick }
154609467b48Spatrick
154709467b48Spatrick if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
154873471bf0Spatrick auto *CVVTy = cast<FixedVectorType>(CV->getType());
1549097a140dSpatrick Type *ETy = CVVTy->getElementType();
155009467b48Spatrick Out << '<';
1551*d415bd75Srobert WriterCtx.TypePrinter->print(ETy, Out);
155209467b48Spatrick Out << ' ';
1553*d415bd75Srobert WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1554097a140dSpatrick for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
155509467b48Spatrick Out << ", ";
1556*d415bd75Srobert WriterCtx.TypePrinter->print(ETy, Out);
155709467b48Spatrick Out << ' ';
1558*d415bd75Srobert WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
155909467b48Spatrick }
156009467b48Spatrick Out << '>';
156109467b48Spatrick return;
156209467b48Spatrick }
156309467b48Spatrick
156409467b48Spatrick if (isa<ConstantPointerNull>(CV)) {
156509467b48Spatrick Out << "null";
156609467b48Spatrick return;
156709467b48Spatrick }
156809467b48Spatrick
156909467b48Spatrick if (isa<ConstantTokenNone>(CV)) {
157009467b48Spatrick Out << "none";
157109467b48Spatrick return;
157209467b48Spatrick }
157309467b48Spatrick
157473471bf0Spatrick if (isa<PoisonValue>(CV)) {
157573471bf0Spatrick Out << "poison";
157673471bf0Spatrick return;
157773471bf0Spatrick }
157873471bf0Spatrick
157909467b48Spatrick if (isa<UndefValue>(CV)) {
158009467b48Spatrick Out << "undef";
158109467b48Spatrick return;
158209467b48Spatrick }
158309467b48Spatrick
158409467b48Spatrick if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
158509467b48Spatrick Out << CE->getOpcodeName();
158609467b48Spatrick WriteOptimizationInfo(Out, CE);
158709467b48Spatrick if (CE->isCompare())
158809467b48Spatrick Out << ' ' << CmpInst::getPredicateName(
158909467b48Spatrick static_cast<CmpInst::Predicate>(CE->getPredicate()));
159009467b48Spatrick Out << " (";
159109467b48Spatrick
1592*d415bd75Srobert std::optional<unsigned> InRangeOp;
159309467b48Spatrick if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1594*d415bd75Srobert WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
159509467b48Spatrick Out << ", ";
159609467b48Spatrick InRangeOp = GEP->getInRangeIndex();
159709467b48Spatrick if (InRangeOp)
159809467b48Spatrick ++*InRangeOp;
159909467b48Spatrick }
160009467b48Spatrick
160109467b48Spatrick for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
160209467b48Spatrick if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
160309467b48Spatrick Out << "inrange ";
1604*d415bd75Srobert WriterCtx.TypePrinter->print((*OI)->getType(), Out);
160509467b48Spatrick Out << ' ';
1606*d415bd75Srobert WriteAsOperandInternal(Out, *OI, WriterCtx);
160709467b48Spatrick if (OI+1 != CE->op_end())
160809467b48Spatrick Out << ", ";
160909467b48Spatrick }
161009467b48Spatrick
161109467b48Spatrick if (CE->isCast()) {
161209467b48Spatrick Out << " to ";
1613*d415bd75Srobert WriterCtx.TypePrinter->print(CE->getType(), Out);
161409467b48Spatrick }
161509467b48Spatrick
1616097a140dSpatrick if (CE->getOpcode() == Instruction::ShuffleVector)
1617097a140dSpatrick PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1618097a140dSpatrick
161909467b48Spatrick Out << ')';
162009467b48Spatrick return;
162109467b48Spatrick }
162209467b48Spatrick
162309467b48Spatrick Out << "<placeholder or erroneous Constant>";
162409467b48Spatrick }
162509467b48Spatrick
writeMDTuple(raw_ostream & Out,const MDTuple * Node,AsmWriterContext & WriterCtx)162609467b48Spatrick static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1627*d415bd75Srobert AsmWriterContext &WriterCtx) {
162809467b48Spatrick Out << "!{";
162909467b48Spatrick for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
163009467b48Spatrick const Metadata *MD = Node->getOperand(mi);
163109467b48Spatrick if (!MD)
163209467b48Spatrick Out << "null";
163309467b48Spatrick else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
163409467b48Spatrick Value *V = MDV->getValue();
1635*d415bd75Srobert WriterCtx.TypePrinter->print(V->getType(), Out);
163609467b48Spatrick Out << ' ';
1637*d415bd75Srobert WriteAsOperandInternal(Out, V, WriterCtx);
163809467b48Spatrick } else {
1639*d415bd75Srobert WriteAsOperandInternal(Out, MD, WriterCtx);
1640*d415bd75Srobert WriterCtx.onWriteMetadataAsOperand(MD);
164109467b48Spatrick }
164209467b48Spatrick if (mi + 1 != me)
164309467b48Spatrick Out << ", ";
164409467b48Spatrick }
164509467b48Spatrick
164609467b48Spatrick Out << "}";
164709467b48Spatrick }
164809467b48Spatrick
164909467b48Spatrick namespace {
165009467b48Spatrick
165109467b48Spatrick struct FieldSeparator {
165209467b48Spatrick bool Skip = true;
165309467b48Spatrick const char *Sep;
165409467b48Spatrick
FieldSeparator__anon4f18fdef0611::FieldSeparator165509467b48Spatrick FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
165609467b48Spatrick };
165709467b48Spatrick
operator <<(raw_ostream & OS,FieldSeparator & FS)165809467b48Spatrick raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
165909467b48Spatrick if (FS.Skip) {
166009467b48Spatrick FS.Skip = false;
166109467b48Spatrick return OS;
166209467b48Spatrick }
166309467b48Spatrick return OS << FS.Sep;
166409467b48Spatrick }
166509467b48Spatrick
166609467b48Spatrick struct MDFieldPrinter {
166709467b48Spatrick raw_ostream &Out;
166809467b48Spatrick FieldSeparator FS;
1669*d415bd75Srobert AsmWriterContext &WriterCtx;
167009467b48Spatrick
MDFieldPrinter__anon4f18fdef0611::MDFieldPrinter1671*d415bd75Srobert explicit MDFieldPrinter(raw_ostream &Out)
1672*d415bd75Srobert : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
MDFieldPrinter__anon4f18fdef0611::MDFieldPrinter1673*d415bd75Srobert MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1674*d415bd75Srobert : Out(Out), WriterCtx(Ctx) {}
167509467b48Spatrick
167609467b48Spatrick void printTag(const DINode *N);
167709467b48Spatrick void printMacinfoType(const DIMacroNode *N);
167809467b48Spatrick void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
167909467b48Spatrick void printString(StringRef Name, StringRef Value,
168009467b48Spatrick bool ShouldSkipEmpty = true);
168109467b48Spatrick void printMetadata(StringRef Name, const Metadata *MD,
168209467b48Spatrick bool ShouldSkipNull = true);
168309467b48Spatrick template <class IntTy>
168409467b48Spatrick void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1685097a140dSpatrick void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1686097a140dSpatrick bool ShouldSkipZero);
1687*d415bd75Srobert void printBool(StringRef Name, bool Value,
1688*d415bd75Srobert std::optional<bool> Default = std::nullopt);
168909467b48Spatrick void printDIFlags(StringRef Name, DINode::DIFlags Flags);
169009467b48Spatrick void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
169109467b48Spatrick template <class IntTy, class Stringifier>
169209467b48Spatrick void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
169309467b48Spatrick bool ShouldSkipZero = true);
169409467b48Spatrick void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
169509467b48Spatrick void printNameTableKind(StringRef Name,
169609467b48Spatrick DICompileUnit::DebugNameTableKind NTK);
169709467b48Spatrick };
169809467b48Spatrick
169909467b48Spatrick } // end anonymous namespace
170009467b48Spatrick
printTag(const DINode * N)170109467b48Spatrick void MDFieldPrinter::printTag(const DINode *N) {
170209467b48Spatrick Out << FS << "tag: ";
170309467b48Spatrick auto Tag = dwarf::TagString(N->getTag());
170409467b48Spatrick if (!Tag.empty())
170509467b48Spatrick Out << Tag;
170609467b48Spatrick else
170709467b48Spatrick Out << N->getTag();
170809467b48Spatrick }
170909467b48Spatrick
printMacinfoType(const DIMacroNode * N)171009467b48Spatrick void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
171109467b48Spatrick Out << FS << "type: ";
171209467b48Spatrick auto Type = dwarf::MacinfoString(N->getMacinfoType());
171309467b48Spatrick if (!Type.empty())
171409467b48Spatrick Out << Type;
171509467b48Spatrick else
171609467b48Spatrick Out << N->getMacinfoType();
171709467b48Spatrick }
171809467b48Spatrick
printChecksum(const DIFile::ChecksumInfo<StringRef> & Checksum)171909467b48Spatrick void MDFieldPrinter::printChecksum(
172009467b48Spatrick const DIFile::ChecksumInfo<StringRef> &Checksum) {
172109467b48Spatrick Out << FS << "checksumkind: " << Checksum.getKindAsString();
172209467b48Spatrick printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
172309467b48Spatrick }
172409467b48Spatrick
printString(StringRef Name,StringRef Value,bool ShouldSkipEmpty)172509467b48Spatrick void MDFieldPrinter::printString(StringRef Name, StringRef Value,
172609467b48Spatrick bool ShouldSkipEmpty) {
172709467b48Spatrick if (ShouldSkipEmpty && Value.empty())
172809467b48Spatrick return;
172909467b48Spatrick
173009467b48Spatrick Out << FS << Name << ": \"";
173109467b48Spatrick printEscapedString(Value, Out);
173209467b48Spatrick Out << "\"";
173309467b48Spatrick }
173409467b48Spatrick
writeMetadataAsOperand(raw_ostream & Out,const Metadata * MD,AsmWriterContext & WriterCtx)173509467b48Spatrick static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1736*d415bd75Srobert AsmWriterContext &WriterCtx) {
173709467b48Spatrick if (!MD) {
173809467b48Spatrick Out << "null";
173909467b48Spatrick return;
174009467b48Spatrick }
1741*d415bd75Srobert WriteAsOperandInternal(Out, MD, WriterCtx);
1742*d415bd75Srobert WriterCtx.onWriteMetadataAsOperand(MD);
174309467b48Spatrick }
174409467b48Spatrick
printMetadata(StringRef Name,const Metadata * MD,bool ShouldSkipNull)174509467b48Spatrick void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
174609467b48Spatrick bool ShouldSkipNull) {
174709467b48Spatrick if (ShouldSkipNull && !MD)
174809467b48Spatrick return;
174909467b48Spatrick
175009467b48Spatrick Out << FS << Name << ": ";
1751*d415bd75Srobert writeMetadataAsOperand(Out, MD, WriterCtx);
175209467b48Spatrick }
175309467b48Spatrick
175409467b48Spatrick template <class IntTy>
printInt(StringRef Name,IntTy Int,bool ShouldSkipZero)175509467b48Spatrick void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
175609467b48Spatrick if (ShouldSkipZero && !Int)
175709467b48Spatrick return;
175809467b48Spatrick
175909467b48Spatrick Out << FS << Name << ": " << Int;
176009467b48Spatrick }
176109467b48Spatrick
printAPInt(StringRef Name,const APInt & Int,bool IsUnsigned,bool ShouldSkipZero)1762097a140dSpatrick void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1763097a140dSpatrick bool IsUnsigned, bool ShouldSkipZero) {
1764*d415bd75Srobert if (ShouldSkipZero && Int.isZero())
1765097a140dSpatrick return;
1766097a140dSpatrick
1767097a140dSpatrick Out << FS << Name << ": ";
1768097a140dSpatrick Int.print(Out, !IsUnsigned);
1769097a140dSpatrick }
1770097a140dSpatrick
printBool(StringRef Name,bool Value,std::optional<bool> Default)177109467b48Spatrick void MDFieldPrinter::printBool(StringRef Name, bool Value,
1772*d415bd75Srobert std::optional<bool> Default) {
177309467b48Spatrick if (Default && Value == *Default)
177409467b48Spatrick return;
177509467b48Spatrick Out << FS << Name << ": " << (Value ? "true" : "false");
177609467b48Spatrick }
177709467b48Spatrick
printDIFlags(StringRef Name,DINode::DIFlags Flags)177809467b48Spatrick void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
177909467b48Spatrick if (!Flags)
178009467b48Spatrick return;
178109467b48Spatrick
178209467b48Spatrick Out << FS << Name << ": ";
178309467b48Spatrick
178409467b48Spatrick SmallVector<DINode::DIFlags, 8> SplitFlags;
178509467b48Spatrick auto Extra = DINode::splitFlags(Flags, SplitFlags);
178609467b48Spatrick
178709467b48Spatrick FieldSeparator FlagsFS(" | ");
178809467b48Spatrick for (auto F : SplitFlags) {
178909467b48Spatrick auto StringF = DINode::getFlagString(F);
179009467b48Spatrick assert(!StringF.empty() && "Expected valid flag");
179109467b48Spatrick Out << FlagsFS << StringF;
179209467b48Spatrick }
179309467b48Spatrick if (Extra || SplitFlags.empty())
179409467b48Spatrick Out << FlagsFS << Extra;
179509467b48Spatrick }
179609467b48Spatrick
printDISPFlags(StringRef Name,DISubprogram::DISPFlags Flags)179709467b48Spatrick void MDFieldPrinter::printDISPFlags(StringRef Name,
179809467b48Spatrick DISubprogram::DISPFlags Flags) {
179909467b48Spatrick // Always print this field, because no flags in the IR at all will be
180009467b48Spatrick // interpreted as old-style isDefinition: true.
180109467b48Spatrick Out << FS << Name << ": ";
180209467b48Spatrick
180309467b48Spatrick if (!Flags) {
180409467b48Spatrick Out << 0;
180509467b48Spatrick return;
180609467b48Spatrick }
180709467b48Spatrick
180809467b48Spatrick SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
180909467b48Spatrick auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
181009467b48Spatrick
181109467b48Spatrick FieldSeparator FlagsFS(" | ");
181209467b48Spatrick for (auto F : SplitFlags) {
181309467b48Spatrick auto StringF = DISubprogram::getFlagString(F);
181409467b48Spatrick assert(!StringF.empty() && "Expected valid flag");
181509467b48Spatrick Out << FlagsFS << StringF;
181609467b48Spatrick }
181709467b48Spatrick if (Extra || SplitFlags.empty())
181809467b48Spatrick Out << FlagsFS << Extra;
181909467b48Spatrick }
182009467b48Spatrick
printEmissionKind(StringRef Name,DICompileUnit::DebugEmissionKind EK)182109467b48Spatrick void MDFieldPrinter::printEmissionKind(StringRef Name,
182209467b48Spatrick DICompileUnit::DebugEmissionKind EK) {
182309467b48Spatrick Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
182409467b48Spatrick }
182509467b48Spatrick
printNameTableKind(StringRef Name,DICompileUnit::DebugNameTableKind NTK)182609467b48Spatrick void MDFieldPrinter::printNameTableKind(StringRef Name,
182709467b48Spatrick DICompileUnit::DebugNameTableKind NTK) {
182809467b48Spatrick if (NTK == DICompileUnit::DebugNameTableKind::Default)
182909467b48Spatrick return;
183009467b48Spatrick Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
183109467b48Spatrick }
183209467b48Spatrick
183309467b48Spatrick template <class IntTy, class Stringifier>
printDwarfEnum(StringRef Name,IntTy Value,Stringifier toString,bool ShouldSkipZero)183409467b48Spatrick void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
183509467b48Spatrick Stringifier toString, bool ShouldSkipZero) {
183609467b48Spatrick if (!Value)
183709467b48Spatrick return;
183809467b48Spatrick
183909467b48Spatrick Out << FS << Name << ": ";
184009467b48Spatrick auto S = toString(Value);
184109467b48Spatrick if (!S.empty())
184209467b48Spatrick Out << S;
184309467b48Spatrick else
184409467b48Spatrick Out << Value;
184509467b48Spatrick }
184609467b48Spatrick
writeGenericDINode(raw_ostream & Out,const GenericDINode * N,AsmWriterContext & WriterCtx)184709467b48Spatrick static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1848*d415bd75Srobert AsmWriterContext &WriterCtx) {
184909467b48Spatrick Out << "!GenericDINode(";
1850*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
185109467b48Spatrick Printer.printTag(N);
185209467b48Spatrick Printer.printString("header", N->getHeader());
185309467b48Spatrick if (N->getNumDwarfOperands()) {
185409467b48Spatrick Out << Printer.FS << "operands: {";
185509467b48Spatrick FieldSeparator IFS;
185609467b48Spatrick for (auto &I : N->dwarf_operands()) {
185709467b48Spatrick Out << IFS;
1858*d415bd75Srobert writeMetadataAsOperand(Out, I, WriterCtx);
185909467b48Spatrick }
186009467b48Spatrick Out << "}";
186109467b48Spatrick }
186209467b48Spatrick Out << ")";
186309467b48Spatrick }
186409467b48Spatrick
writeDILocation(raw_ostream & Out,const DILocation * DL,AsmWriterContext & WriterCtx)186509467b48Spatrick static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1866*d415bd75Srobert AsmWriterContext &WriterCtx) {
186709467b48Spatrick Out << "!DILocation(";
1868*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
186909467b48Spatrick // Always output the line, since 0 is a relevant and important value for it.
187009467b48Spatrick Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
187109467b48Spatrick Printer.printInt("column", DL->getColumn());
187209467b48Spatrick Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
187309467b48Spatrick Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
187409467b48Spatrick Printer.printBool("isImplicitCode", DL->isImplicitCode(),
187509467b48Spatrick /* Default */ false);
187609467b48Spatrick Out << ")";
187709467b48Spatrick }
187809467b48Spatrick
writeDIAssignID(raw_ostream & Out,const DIAssignID * DL,AsmWriterContext & WriterCtx)1879*d415bd75Srobert static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
1880*d415bd75Srobert AsmWriterContext &WriterCtx) {
1881*d415bd75Srobert Out << "!DIAssignID()";
1882*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
1883*d415bd75Srobert }
1884*d415bd75Srobert
writeDISubrange(raw_ostream & Out,const DISubrange * N,AsmWriterContext & WriterCtx)188509467b48Spatrick static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1886*d415bd75Srobert AsmWriterContext &WriterCtx) {
188709467b48Spatrick Out << "!DISubrange(";
1888*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
188973471bf0Spatrick
189073471bf0Spatrick auto *Count = N->getRawCountNode();
189173471bf0Spatrick if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
189273471bf0Spatrick auto *CV = cast<ConstantInt>(CE->getValue());
189373471bf0Spatrick Printer.printInt("count", CV->getSExtValue(),
189473471bf0Spatrick /* ShouldSkipZero */ false);
189573471bf0Spatrick } else
189673471bf0Spatrick Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1897097a140dSpatrick
1898097a140dSpatrick // A lowerBound of constant 0 should not be skipped, since it is different
1899097a140dSpatrick // from an unspecified lower bound (= nullptr).
1900097a140dSpatrick auto *LBound = N->getRawLowerBound();
1901097a140dSpatrick if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1902097a140dSpatrick auto *LV = cast<ConstantInt>(LE->getValue());
1903097a140dSpatrick Printer.printInt("lowerBound", LV->getSExtValue(),
1904097a140dSpatrick /* ShouldSkipZero */ false);
1905097a140dSpatrick } else
1906097a140dSpatrick Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1907097a140dSpatrick
1908097a140dSpatrick auto *UBound = N->getRawUpperBound();
1909097a140dSpatrick if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1910097a140dSpatrick auto *UV = cast<ConstantInt>(UE->getValue());
1911097a140dSpatrick Printer.printInt("upperBound", UV->getSExtValue(),
1912097a140dSpatrick /* ShouldSkipZero */ false);
1913097a140dSpatrick } else
1914097a140dSpatrick Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1915097a140dSpatrick
1916097a140dSpatrick auto *Stride = N->getRawStride();
1917097a140dSpatrick if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1918097a140dSpatrick auto *SV = cast<ConstantInt>(SE->getValue());
1919097a140dSpatrick Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1920097a140dSpatrick } else
1921097a140dSpatrick Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1922097a140dSpatrick
192309467b48Spatrick Out << ")";
192409467b48Spatrick }
192509467b48Spatrick
writeDIGenericSubrange(raw_ostream & Out,const DIGenericSubrange * N,AsmWriterContext & WriterCtx)192673471bf0Spatrick static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1927*d415bd75Srobert AsmWriterContext &WriterCtx) {
192873471bf0Spatrick Out << "!DIGenericSubrange(";
1929*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
193073471bf0Spatrick
193173471bf0Spatrick auto IsConstant = [&](Metadata *Bound) -> bool {
193273471bf0Spatrick if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1933*d415bd75Srobert return BE->isConstant() &&
1934*d415bd75Srobert DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1935*d415bd75Srobert *BE->isConstant();
193673471bf0Spatrick }
193773471bf0Spatrick return false;
193873471bf0Spatrick };
193973471bf0Spatrick
194073471bf0Spatrick auto GetConstant = [&](Metadata *Bound) -> int64_t {
194173471bf0Spatrick assert(IsConstant(Bound) && "Expected constant");
194273471bf0Spatrick auto *BE = dyn_cast_or_null<DIExpression>(Bound);
194373471bf0Spatrick return static_cast<int64_t>(BE->getElement(1));
194473471bf0Spatrick };
194573471bf0Spatrick
194673471bf0Spatrick auto *Count = N->getRawCountNode();
194773471bf0Spatrick if (IsConstant(Count))
194873471bf0Spatrick Printer.printInt("count", GetConstant(Count),
194973471bf0Spatrick /* ShouldSkipZero */ false);
195073471bf0Spatrick else
195173471bf0Spatrick Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
195273471bf0Spatrick
195373471bf0Spatrick auto *LBound = N->getRawLowerBound();
195473471bf0Spatrick if (IsConstant(LBound))
195573471bf0Spatrick Printer.printInt("lowerBound", GetConstant(LBound),
195673471bf0Spatrick /* ShouldSkipZero */ false);
195773471bf0Spatrick else
195873471bf0Spatrick Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
195973471bf0Spatrick
196073471bf0Spatrick auto *UBound = N->getRawUpperBound();
196173471bf0Spatrick if (IsConstant(UBound))
196273471bf0Spatrick Printer.printInt("upperBound", GetConstant(UBound),
196373471bf0Spatrick /* ShouldSkipZero */ false);
196473471bf0Spatrick else
196573471bf0Spatrick Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
196673471bf0Spatrick
196773471bf0Spatrick auto *Stride = N->getRawStride();
196873471bf0Spatrick if (IsConstant(Stride))
196973471bf0Spatrick Printer.printInt("stride", GetConstant(Stride),
197073471bf0Spatrick /* ShouldSkipZero */ false);
197173471bf0Spatrick else
197273471bf0Spatrick Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
197373471bf0Spatrick
197473471bf0Spatrick Out << ")";
197573471bf0Spatrick }
197673471bf0Spatrick
writeDIEnumerator(raw_ostream & Out,const DIEnumerator * N,AsmWriterContext &)197709467b48Spatrick static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1978*d415bd75Srobert AsmWriterContext &) {
197909467b48Spatrick Out << "!DIEnumerator(";
198009467b48Spatrick MDFieldPrinter Printer(Out);
198109467b48Spatrick Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1982097a140dSpatrick Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1983097a140dSpatrick /*ShouldSkipZero=*/false);
1984097a140dSpatrick if (N->isUnsigned())
198509467b48Spatrick Printer.printBool("isUnsigned", true);
198609467b48Spatrick Out << ")";
198709467b48Spatrick }
198809467b48Spatrick
writeDIBasicType(raw_ostream & Out,const DIBasicType * N,AsmWriterContext &)198909467b48Spatrick static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1990*d415bd75Srobert AsmWriterContext &) {
199109467b48Spatrick Out << "!DIBasicType(";
199209467b48Spatrick MDFieldPrinter Printer(Out);
199309467b48Spatrick if (N->getTag() != dwarf::DW_TAG_base_type)
199409467b48Spatrick Printer.printTag(N);
199509467b48Spatrick Printer.printString("name", N->getName());
199609467b48Spatrick Printer.printInt("size", N->getSizeInBits());
199709467b48Spatrick Printer.printInt("align", N->getAlignInBits());
199809467b48Spatrick Printer.printDwarfEnum("encoding", N->getEncoding(),
199909467b48Spatrick dwarf::AttributeEncodingString);
200009467b48Spatrick Printer.printDIFlags("flags", N->getFlags());
200109467b48Spatrick Out << ")";
200209467b48Spatrick }
200309467b48Spatrick
writeDIStringType(raw_ostream & Out,const DIStringType * N,AsmWriterContext & WriterCtx)200473471bf0Spatrick static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2005*d415bd75Srobert AsmWriterContext &WriterCtx) {
200673471bf0Spatrick Out << "!DIStringType(";
2007*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
200873471bf0Spatrick if (N->getTag() != dwarf::DW_TAG_string_type)
200973471bf0Spatrick Printer.printTag(N);
201073471bf0Spatrick Printer.printString("name", N->getName());
201173471bf0Spatrick Printer.printMetadata("stringLength", N->getRawStringLength());
201273471bf0Spatrick Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2013*d415bd75Srobert Printer.printMetadata("stringLocationExpression",
2014*d415bd75Srobert N->getRawStringLocationExp());
201573471bf0Spatrick Printer.printInt("size", N->getSizeInBits());
201673471bf0Spatrick Printer.printInt("align", N->getAlignInBits());
201773471bf0Spatrick Printer.printDwarfEnum("encoding", N->getEncoding(),
201873471bf0Spatrick dwarf::AttributeEncodingString);
201973471bf0Spatrick Out << ")";
202073471bf0Spatrick }
202173471bf0Spatrick
writeDIDerivedType(raw_ostream & Out,const DIDerivedType * N,AsmWriterContext & WriterCtx)202209467b48Spatrick static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2023*d415bd75Srobert AsmWriterContext &WriterCtx) {
202409467b48Spatrick Out << "!DIDerivedType(";
2025*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
202609467b48Spatrick Printer.printTag(N);
202709467b48Spatrick Printer.printString("name", N->getName());
202809467b48Spatrick Printer.printMetadata("scope", N->getRawScope());
202909467b48Spatrick Printer.printMetadata("file", N->getRawFile());
203009467b48Spatrick Printer.printInt("line", N->getLine());
203109467b48Spatrick Printer.printMetadata("baseType", N->getRawBaseType(),
203209467b48Spatrick /* ShouldSkipNull */ false);
203309467b48Spatrick Printer.printInt("size", N->getSizeInBits());
203409467b48Spatrick Printer.printInt("align", N->getAlignInBits());
203509467b48Spatrick Printer.printInt("offset", N->getOffsetInBits());
203609467b48Spatrick Printer.printDIFlags("flags", N->getFlags());
203709467b48Spatrick Printer.printMetadata("extraData", N->getRawExtraData());
203809467b48Spatrick if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
203909467b48Spatrick Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
204009467b48Spatrick /* ShouldSkipZero */ false);
2041*d415bd75Srobert Printer.printMetadata("annotations", N->getRawAnnotations());
204209467b48Spatrick Out << ")";
204309467b48Spatrick }
204409467b48Spatrick
writeDICompositeType(raw_ostream & Out,const DICompositeType * N,AsmWriterContext & WriterCtx)204509467b48Spatrick static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2046*d415bd75Srobert AsmWriterContext &WriterCtx) {
204709467b48Spatrick Out << "!DICompositeType(";
2048*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
204909467b48Spatrick Printer.printTag(N);
205009467b48Spatrick Printer.printString("name", N->getName());
205109467b48Spatrick Printer.printMetadata("scope", N->getRawScope());
205209467b48Spatrick Printer.printMetadata("file", N->getRawFile());
205309467b48Spatrick Printer.printInt("line", N->getLine());
205409467b48Spatrick Printer.printMetadata("baseType", N->getRawBaseType());
205509467b48Spatrick Printer.printInt("size", N->getSizeInBits());
205609467b48Spatrick Printer.printInt("align", N->getAlignInBits());
205709467b48Spatrick Printer.printInt("offset", N->getOffsetInBits());
205809467b48Spatrick Printer.printDIFlags("flags", N->getFlags());
205909467b48Spatrick Printer.printMetadata("elements", N->getRawElements());
206009467b48Spatrick Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
206109467b48Spatrick dwarf::LanguageString);
206209467b48Spatrick Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
206309467b48Spatrick Printer.printMetadata("templateParams", N->getRawTemplateParams());
206409467b48Spatrick Printer.printString("identifier", N->getIdentifier());
206509467b48Spatrick Printer.printMetadata("discriminator", N->getRawDiscriminator());
2066097a140dSpatrick Printer.printMetadata("dataLocation", N->getRawDataLocation());
206773471bf0Spatrick Printer.printMetadata("associated", N->getRawAssociated());
206873471bf0Spatrick Printer.printMetadata("allocated", N->getRawAllocated());
206973471bf0Spatrick if (auto *RankConst = N->getRankConst())
207073471bf0Spatrick Printer.printInt("rank", RankConst->getSExtValue(),
207173471bf0Spatrick /* ShouldSkipZero */ false);
207273471bf0Spatrick else
207373471bf0Spatrick Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2074*d415bd75Srobert Printer.printMetadata("annotations", N->getRawAnnotations());
207509467b48Spatrick Out << ")";
207609467b48Spatrick }
207709467b48Spatrick
writeDISubroutineType(raw_ostream & Out,const DISubroutineType * N,AsmWriterContext & WriterCtx)207809467b48Spatrick static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2079*d415bd75Srobert AsmWriterContext &WriterCtx) {
208009467b48Spatrick Out << "!DISubroutineType(";
2081*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
208209467b48Spatrick Printer.printDIFlags("flags", N->getFlags());
208309467b48Spatrick Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
208409467b48Spatrick Printer.printMetadata("types", N->getRawTypeArray(),
208509467b48Spatrick /* ShouldSkipNull */ false);
208609467b48Spatrick Out << ")";
208709467b48Spatrick }
208809467b48Spatrick
writeDIFile(raw_ostream & Out,const DIFile * N,AsmWriterContext &)2089*d415bd75Srobert static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
209009467b48Spatrick Out << "!DIFile(";
209109467b48Spatrick MDFieldPrinter Printer(Out);
209209467b48Spatrick Printer.printString("filename", N->getFilename(),
209309467b48Spatrick /* ShouldSkipEmpty */ false);
209409467b48Spatrick Printer.printString("directory", N->getDirectory(),
209509467b48Spatrick /* ShouldSkipEmpty */ false);
209609467b48Spatrick // Print all values for checksum together, or not at all.
209709467b48Spatrick if (N->getChecksum())
209809467b48Spatrick Printer.printChecksum(*N->getChecksum());
2099*d415bd75Srobert Printer.printString("source", N->getSource().value_or(StringRef()),
210009467b48Spatrick /* ShouldSkipEmpty */ true);
210109467b48Spatrick Out << ")";
210209467b48Spatrick }
210309467b48Spatrick
writeDICompileUnit(raw_ostream & Out,const DICompileUnit * N,AsmWriterContext & WriterCtx)210409467b48Spatrick static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2105*d415bd75Srobert AsmWriterContext &WriterCtx) {
210609467b48Spatrick Out << "!DICompileUnit(";
2107*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
210809467b48Spatrick Printer.printDwarfEnum("language", N->getSourceLanguage(),
210909467b48Spatrick dwarf::LanguageString, /* ShouldSkipZero */ false);
211009467b48Spatrick Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
211109467b48Spatrick Printer.printString("producer", N->getProducer());
211209467b48Spatrick Printer.printBool("isOptimized", N->isOptimized());
211309467b48Spatrick Printer.printString("flags", N->getFlags());
211409467b48Spatrick Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
211509467b48Spatrick /* ShouldSkipZero */ false);
211609467b48Spatrick Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
211709467b48Spatrick Printer.printEmissionKind("emissionKind", N->getEmissionKind());
211809467b48Spatrick Printer.printMetadata("enums", N->getRawEnumTypes());
211909467b48Spatrick Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
212009467b48Spatrick Printer.printMetadata("globals", N->getRawGlobalVariables());
212109467b48Spatrick Printer.printMetadata("imports", N->getRawImportedEntities());
212209467b48Spatrick Printer.printMetadata("macros", N->getRawMacros());
212309467b48Spatrick Printer.printInt("dwoId", N->getDWOId());
212409467b48Spatrick Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
212509467b48Spatrick Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
212609467b48Spatrick false);
212709467b48Spatrick Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
212809467b48Spatrick Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2129097a140dSpatrick Printer.printString("sysroot", N->getSysRoot());
2130097a140dSpatrick Printer.printString("sdk", N->getSDK());
213109467b48Spatrick Out << ")";
213209467b48Spatrick }
213309467b48Spatrick
writeDISubprogram(raw_ostream & Out,const DISubprogram * N,AsmWriterContext & WriterCtx)213409467b48Spatrick static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2135*d415bd75Srobert AsmWriterContext &WriterCtx) {
213609467b48Spatrick Out << "!DISubprogram(";
2137*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
213809467b48Spatrick Printer.printString("name", N->getName());
213909467b48Spatrick Printer.printString("linkageName", N->getLinkageName());
214009467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
214109467b48Spatrick Printer.printMetadata("file", N->getRawFile());
214209467b48Spatrick Printer.printInt("line", N->getLine());
214309467b48Spatrick Printer.printMetadata("type", N->getRawType());
214409467b48Spatrick Printer.printInt("scopeLine", N->getScopeLine());
214509467b48Spatrick Printer.printMetadata("containingType", N->getRawContainingType());
214609467b48Spatrick if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
214709467b48Spatrick N->getVirtualIndex() != 0)
214809467b48Spatrick Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
214909467b48Spatrick Printer.printInt("thisAdjustment", N->getThisAdjustment());
215009467b48Spatrick Printer.printDIFlags("flags", N->getFlags());
215109467b48Spatrick Printer.printDISPFlags("spFlags", N->getSPFlags());
215209467b48Spatrick Printer.printMetadata("unit", N->getRawUnit());
215309467b48Spatrick Printer.printMetadata("templateParams", N->getRawTemplateParams());
215409467b48Spatrick Printer.printMetadata("declaration", N->getRawDeclaration());
215509467b48Spatrick Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
215609467b48Spatrick Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2157*d415bd75Srobert Printer.printMetadata("annotations", N->getRawAnnotations());
2158*d415bd75Srobert Printer.printString("targetFuncName", N->getTargetFuncName());
215909467b48Spatrick Out << ")";
216009467b48Spatrick }
216109467b48Spatrick
writeDILexicalBlock(raw_ostream & Out,const DILexicalBlock * N,AsmWriterContext & WriterCtx)216209467b48Spatrick static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2163*d415bd75Srobert AsmWriterContext &WriterCtx) {
216409467b48Spatrick Out << "!DILexicalBlock(";
2165*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
216609467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
216709467b48Spatrick Printer.printMetadata("file", N->getRawFile());
216809467b48Spatrick Printer.printInt("line", N->getLine());
216909467b48Spatrick Printer.printInt("column", N->getColumn());
217009467b48Spatrick Out << ")";
217109467b48Spatrick }
217209467b48Spatrick
writeDILexicalBlockFile(raw_ostream & Out,const DILexicalBlockFile * N,AsmWriterContext & WriterCtx)217309467b48Spatrick static void writeDILexicalBlockFile(raw_ostream &Out,
217409467b48Spatrick const DILexicalBlockFile *N,
2175*d415bd75Srobert AsmWriterContext &WriterCtx) {
217609467b48Spatrick Out << "!DILexicalBlockFile(";
2177*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
217809467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
217909467b48Spatrick Printer.printMetadata("file", N->getRawFile());
218009467b48Spatrick Printer.printInt("discriminator", N->getDiscriminator(),
218109467b48Spatrick /* ShouldSkipZero */ false);
218209467b48Spatrick Out << ")";
218309467b48Spatrick }
218409467b48Spatrick
writeDINamespace(raw_ostream & Out,const DINamespace * N,AsmWriterContext & WriterCtx)218509467b48Spatrick static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2186*d415bd75Srobert AsmWriterContext &WriterCtx) {
218709467b48Spatrick Out << "!DINamespace(";
2188*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
218909467b48Spatrick Printer.printString("name", N->getName());
219009467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
219109467b48Spatrick Printer.printBool("exportSymbols", N->getExportSymbols(), false);
219209467b48Spatrick Out << ")";
219309467b48Spatrick }
219409467b48Spatrick
writeDICommonBlock(raw_ostream & Out,const DICommonBlock * N,AsmWriterContext & WriterCtx)219509467b48Spatrick static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2196*d415bd75Srobert AsmWriterContext &WriterCtx) {
219709467b48Spatrick Out << "!DICommonBlock(";
2198*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
219909467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), false);
220009467b48Spatrick Printer.printMetadata("declaration", N->getRawDecl(), false);
220109467b48Spatrick Printer.printString("name", N->getName());
220209467b48Spatrick Printer.printMetadata("file", N->getRawFile());
220309467b48Spatrick Printer.printInt("line", N->getLineNo());
220409467b48Spatrick Out << ")";
220509467b48Spatrick }
220609467b48Spatrick
writeDIMacro(raw_ostream & Out,const DIMacro * N,AsmWriterContext & WriterCtx)220709467b48Spatrick static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2208*d415bd75Srobert AsmWriterContext &WriterCtx) {
220909467b48Spatrick Out << "!DIMacro(";
2210*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
221109467b48Spatrick Printer.printMacinfoType(N);
221209467b48Spatrick Printer.printInt("line", N->getLine());
221309467b48Spatrick Printer.printString("name", N->getName());
221409467b48Spatrick Printer.printString("value", N->getValue());
221509467b48Spatrick Out << ")";
221609467b48Spatrick }
221709467b48Spatrick
writeDIMacroFile(raw_ostream & Out,const DIMacroFile * N,AsmWriterContext & WriterCtx)221809467b48Spatrick static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2219*d415bd75Srobert AsmWriterContext &WriterCtx) {
222009467b48Spatrick Out << "!DIMacroFile(";
2221*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
222209467b48Spatrick Printer.printInt("line", N->getLine());
222309467b48Spatrick Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
222409467b48Spatrick Printer.printMetadata("nodes", N->getRawElements());
222509467b48Spatrick Out << ")";
222609467b48Spatrick }
222709467b48Spatrick
writeDIModule(raw_ostream & Out,const DIModule * N,AsmWriterContext & WriterCtx)222809467b48Spatrick static void writeDIModule(raw_ostream &Out, const DIModule *N,
2229*d415bd75Srobert AsmWriterContext &WriterCtx) {
223009467b48Spatrick Out << "!DIModule(";
2231*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
223209467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
223309467b48Spatrick Printer.printString("name", N->getName());
223409467b48Spatrick Printer.printString("configMacros", N->getConfigurationMacros());
223509467b48Spatrick Printer.printString("includePath", N->getIncludePath());
2236097a140dSpatrick Printer.printString("apinotes", N->getAPINotesFile());
2237097a140dSpatrick Printer.printMetadata("file", N->getRawFile());
2238097a140dSpatrick Printer.printInt("line", N->getLineNo());
223973471bf0Spatrick Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
224009467b48Spatrick Out << ")";
224109467b48Spatrick }
224209467b48Spatrick
writeDITemplateTypeParameter(raw_ostream & Out,const DITemplateTypeParameter * N,AsmWriterContext & WriterCtx)224309467b48Spatrick static void writeDITemplateTypeParameter(raw_ostream &Out,
224409467b48Spatrick const DITemplateTypeParameter *N,
2245*d415bd75Srobert AsmWriterContext &WriterCtx) {
224609467b48Spatrick Out << "!DITemplateTypeParameter(";
2247*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
224809467b48Spatrick Printer.printString("name", N->getName());
224909467b48Spatrick Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2250097a140dSpatrick Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
225109467b48Spatrick Out << ")";
225209467b48Spatrick }
225309467b48Spatrick
writeDITemplateValueParameter(raw_ostream & Out,const DITemplateValueParameter * N,AsmWriterContext & WriterCtx)225409467b48Spatrick static void writeDITemplateValueParameter(raw_ostream &Out,
225509467b48Spatrick const DITemplateValueParameter *N,
2256*d415bd75Srobert AsmWriterContext &WriterCtx) {
225709467b48Spatrick Out << "!DITemplateValueParameter(";
2258*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
225909467b48Spatrick if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
226009467b48Spatrick Printer.printTag(N);
226109467b48Spatrick Printer.printString("name", N->getName());
226209467b48Spatrick Printer.printMetadata("type", N->getRawType());
2263097a140dSpatrick Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
226409467b48Spatrick Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
226509467b48Spatrick Out << ")";
226609467b48Spatrick }
226709467b48Spatrick
writeDIGlobalVariable(raw_ostream & Out,const DIGlobalVariable * N,AsmWriterContext & WriterCtx)226809467b48Spatrick static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2269*d415bd75Srobert AsmWriterContext &WriterCtx) {
227009467b48Spatrick Out << "!DIGlobalVariable(";
2271*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
227209467b48Spatrick Printer.printString("name", N->getName());
227309467b48Spatrick Printer.printString("linkageName", N->getLinkageName());
227409467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
227509467b48Spatrick Printer.printMetadata("file", N->getRawFile());
227609467b48Spatrick Printer.printInt("line", N->getLine());
227709467b48Spatrick Printer.printMetadata("type", N->getRawType());
227809467b48Spatrick Printer.printBool("isLocal", N->isLocalToUnit());
227909467b48Spatrick Printer.printBool("isDefinition", N->isDefinition());
228009467b48Spatrick Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
228109467b48Spatrick Printer.printMetadata("templateParams", N->getRawTemplateParams());
228209467b48Spatrick Printer.printInt("align", N->getAlignInBits());
2283*d415bd75Srobert Printer.printMetadata("annotations", N->getRawAnnotations());
228409467b48Spatrick Out << ")";
228509467b48Spatrick }
228609467b48Spatrick
writeDILocalVariable(raw_ostream & Out,const DILocalVariable * N,AsmWriterContext & WriterCtx)228709467b48Spatrick static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2288*d415bd75Srobert AsmWriterContext &WriterCtx) {
228909467b48Spatrick Out << "!DILocalVariable(";
2290*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
229109467b48Spatrick Printer.printString("name", N->getName());
229209467b48Spatrick Printer.printInt("arg", N->getArg());
229309467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
229409467b48Spatrick Printer.printMetadata("file", N->getRawFile());
229509467b48Spatrick Printer.printInt("line", N->getLine());
229609467b48Spatrick Printer.printMetadata("type", N->getRawType());
229709467b48Spatrick Printer.printDIFlags("flags", N->getFlags());
229809467b48Spatrick Printer.printInt("align", N->getAlignInBits());
2299*d415bd75Srobert Printer.printMetadata("annotations", N->getRawAnnotations());
230009467b48Spatrick Out << ")";
230109467b48Spatrick }
230209467b48Spatrick
writeDILabel(raw_ostream & Out,const DILabel * N,AsmWriterContext & WriterCtx)230309467b48Spatrick static void writeDILabel(raw_ostream &Out, const DILabel *N,
2304*d415bd75Srobert AsmWriterContext &WriterCtx) {
230509467b48Spatrick Out << "!DILabel(";
2306*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
230709467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
230809467b48Spatrick Printer.printString("name", N->getName());
230909467b48Spatrick Printer.printMetadata("file", N->getRawFile());
231009467b48Spatrick Printer.printInt("line", N->getLine());
231109467b48Spatrick Out << ")";
231209467b48Spatrick }
231309467b48Spatrick
writeDIExpression(raw_ostream & Out,const DIExpression * N,AsmWriterContext & WriterCtx)231409467b48Spatrick static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2315*d415bd75Srobert AsmWriterContext &WriterCtx) {
231609467b48Spatrick Out << "!DIExpression(";
231709467b48Spatrick FieldSeparator FS;
231809467b48Spatrick if (N->isValid()) {
231973471bf0Spatrick for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
232073471bf0Spatrick auto OpStr = dwarf::OperationEncodingString(Op.getOp());
232109467b48Spatrick assert(!OpStr.empty() && "Expected valid opcode");
232209467b48Spatrick
232309467b48Spatrick Out << FS << OpStr;
232473471bf0Spatrick if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
232573471bf0Spatrick Out << FS << Op.getArg(0);
232673471bf0Spatrick Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
232709467b48Spatrick } else {
232873471bf0Spatrick for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
232973471bf0Spatrick Out << FS << Op.getArg(A);
233009467b48Spatrick }
233109467b48Spatrick }
233209467b48Spatrick } else {
233309467b48Spatrick for (const auto &I : N->getElements())
233409467b48Spatrick Out << FS << I;
233509467b48Spatrick }
233609467b48Spatrick Out << ")";
233709467b48Spatrick }
233809467b48Spatrick
writeDIArgList(raw_ostream & Out,const DIArgList * N,AsmWriterContext & WriterCtx,bool FromValue=false)233973471bf0Spatrick static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2340*d415bd75Srobert AsmWriterContext &WriterCtx,
2341*d415bd75Srobert bool FromValue = false) {
234273471bf0Spatrick assert(FromValue &&
234373471bf0Spatrick "Unexpected DIArgList metadata outside of value argument");
234473471bf0Spatrick Out << "!DIArgList(";
234573471bf0Spatrick FieldSeparator FS;
2346*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
234773471bf0Spatrick for (Metadata *Arg : N->getArgs()) {
234873471bf0Spatrick Out << FS;
2349*d415bd75Srobert WriteAsOperandInternal(Out, Arg, WriterCtx, true);
235073471bf0Spatrick }
235173471bf0Spatrick Out << ")";
235273471bf0Spatrick }
235373471bf0Spatrick
writeDIGlobalVariableExpression(raw_ostream & Out,const DIGlobalVariableExpression * N,AsmWriterContext & WriterCtx)235409467b48Spatrick static void writeDIGlobalVariableExpression(raw_ostream &Out,
235509467b48Spatrick const DIGlobalVariableExpression *N,
2356*d415bd75Srobert AsmWriterContext &WriterCtx) {
235709467b48Spatrick Out << "!DIGlobalVariableExpression(";
2358*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
235909467b48Spatrick Printer.printMetadata("var", N->getVariable());
236009467b48Spatrick Printer.printMetadata("expr", N->getExpression());
236109467b48Spatrick Out << ")";
236209467b48Spatrick }
236309467b48Spatrick
writeDIObjCProperty(raw_ostream & Out,const DIObjCProperty * N,AsmWriterContext & WriterCtx)236409467b48Spatrick static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2365*d415bd75Srobert AsmWriterContext &WriterCtx) {
236609467b48Spatrick Out << "!DIObjCProperty(";
2367*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
236809467b48Spatrick Printer.printString("name", N->getName());
236909467b48Spatrick Printer.printMetadata("file", N->getRawFile());
237009467b48Spatrick Printer.printInt("line", N->getLine());
237109467b48Spatrick Printer.printString("setter", N->getSetterName());
237209467b48Spatrick Printer.printString("getter", N->getGetterName());
237309467b48Spatrick Printer.printInt("attributes", N->getAttributes());
237409467b48Spatrick Printer.printMetadata("type", N->getRawType());
237509467b48Spatrick Out << ")";
237609467b48Spatrick }
237709467b48Spatrick
writeDIImportedEntity(raw_ostream & Out,const DIImportedEntity * N,AsmWriterContext & WriterCtx)237809467b48Spatrick static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2379*d415bd75Srobert AsmWriterContext &WriterCtx) {
238009467b48Spatrick Out << "!DIImportedEntity(";
2381*d415bd75Srobert MDFieldPrinter Printer(Out, WriterCtx);
238209467b48Spatrick Printer.printTag(N);
238309467b48Spatrick Printer.printString("name", N->getName());
238409467b48Spatrick Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
238509467b48Spatrick Printer.printMetadata("entity", N->getRawEntity());
238609467b48Spatrick Printer.printMetadata("file", N->getRawFile());
238709467b48Spatrick Printer.printInt("line", N->getLine());
2388*d415bd75Srobert Printer.printMetadata("elements", N->getRawElements());
238909467b48Spatrick Out << ")";
239009467b48Spatrick }
239109467b48Spatrick
WriteMDNodeBodyInternal(raw_ostream & Out,const MDNode * Node,AsmWriterContext & Ctx)239209467b48Spatrick static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2393*d415bd75Srobert AsmWriterContext &Ctx) {
239409467b48Spatrick if (Node->isDistinct())
239509467b48Spatrick Out << "distinct ";
239609467b48Spatrick else if (Node->isTemporary())
239709467b48Spatrick Out << "<temporary!> "; // Handle broken code.
239809467b48Spatrick
239909467b48Spatrick switch (Node->getMetadataID()) {
240009467b48Spatrick default:
240109467b48Spatrick llvm_unreachable("Expected uniquable MDNode");
240209467b48Spatrick #define HANDLE_MDNODE_LEAF(CLASS) \
240309467b48Spatrick case Metadata::CLASS##Kind: \
2404*d415bd75Srobert write##CLASS(Out, cast<CLASS>(Node), Ctx); \
240509467b48Spatrick break;
240609467b48Spatrick #include "llvm/IR/Metadata.def"
240709467b48Spatrick }
240809467b48Spatrick }
240909467b48Spatrick
241009467b48Spatrick // Full implementation of printing a Value as an operand with support for
241109467b48Spatrick // TypePrinting, etc.
WriteAsOperandInternal(raw_ostream & Out,const Value * V,AsmWriterContext & WriterCtx)241209467b48Spatrick static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2413*d415bd75Srobert AsmWriterContext &WriterCtx) {
241409467b48Spatrick if (V->hasName()) {
241509467b48Spatrick PrintLLVMName(Out, V);
241609467b48Spatrick return;
241709467b48Spatrick }
241809467b48Spatrick
241909467b48Spatrick const Constant *CV = dyn_cast<Constant>(V);
242009467b48Spatrick if (CV && !isa<GlobalValue>(CV)) {
2421*d415bd75Srobert assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2422*d415bd75Srobert WriteConstantInternal(Out, CV, WriterCtx);
242309467b48Spatrick return;
242409467b48Spatrick }
242509467b48Spatrick
242609467b48Spatrick if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
242709467b48Spatrick Out << "asm ";
242809467b48Spatrick if (IA->hasSideEffects())
242909467b48Spatrick Out << "sideeffect ";
243009467b48Spatrick if (IA->isAlignStack())
243109467b48Spatrick Out << "alignstack ";
243209467b48Spatrick // We don't emit the AD_ATT dialect as it's the assumed default.
243309467b48Spatrick if (IA->getDialect() == InlineAsm::AD_Intel)
243409467b48Spatrick Out << "inteldialect ";
243573471bf0Spatrick if (IA->canThrow())
243673471bf0Spatrick Out << "unwind ";
243709467b48Spatrick Out << '"';
243809467b48Spatrick printEscapedString(IA->getAsmString(), Out);
243909467b48Spatrick Out << "\", \"";
244009467b48Spatrick printEscapedString(IA->getConstraintString(), Out);
244109467b48Spatrick Out << '"';
244209467b48Spatrick return;
244309467b48Spatrick }
244409467b48Spatrick
244509467b48Spatrick if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2446*d415bd75Srobert WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2447*d415bd75Srobert /* FromValue */ true);
244809467b48Spatrick return;
244909467b48Spatrick }
245009467b48Spatrick
245109467b48Spatrick char Prefix = '%';
245209467b48Spatrick int Slot;
2453*d415bd75Srobert auto *Machine = WriterCtx.Machine;
245409467b48Spatrick // If we have a SlotTracker, use it.
245509467b48Spatrick if (Machine) {
245609467b48Spatrick if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
245709467b48Spatrick Slot = Machine->getGlobalSlot(GV);
245809467b48Spatrick Prefix = '@';
245909467b48Spatrick } else {
246009467b48Spatrick Slot = Machine->getLocalSlot(V);
246109467b48Spatrick
246209467b48Spatrick // If the local value didn't succeed, then we may be referring to a value
246309467b48Spatrick // from a different function. Translate it, as this can happen when using
246409467b48Spatrick // address of blocks.
246509467b48Spatrick if (Slot == -1)
246609467b48Spatrick if ((Machine = createSlotTracker(V))) {
246709467b48Spatrick Slot = Machine->getLocalSlot(V);
246809467b48Spatrick delete Machine;
246909467b48Spatrick }
247009467b48Spatrick }
247109467b48Spatrick } else if ((Machine = createSlotTracker(V))) {
247209467b48Spatrick // Otherwise, create one to get the # and then destroy it.
247309467b48Spatrick if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
247409467b48Spatrick Slot = Machine->getGlobalSlot(GV);
247509467b48Spatrick Prefix = '@';
247609467b48Spatrick } else {
247709467b48Spatrick Slot = Machine->getLocalSlot(V);
247809467b48Spatrick }
247909467b48Spatrick delete Machine;
248009467b48Spatrick Machine = nullptr;
248109467b48Spatrick } else {
248209467b48Spatrick Slot = -1;
248309467b48Spatrick }
248409467b48Spatrick
248509467b48Spatrick if (Slot != -1)
248609467b48Spatrick Out << Prefix << Slot;
248709467b48Spatrick else
248809467b48Spatrick Out << "<badref>";
248909467b48Spatrick }
249009467b48Spatrick
WriteAsOperandInternal(raw_ostream & Out,const Metadata * MD,AsmWriterContext & WriterCtx,bool FromValue)249109467b48Spatrick static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2492*d415bd75Srobert AsmWriterContext &WriterCtx,
249309467b48Spatrick bool FromValue) {
249473471bf0Spatrick // Write DIExpressions and DIArgLists inline when used as a value. Improves
249573471bf0Spatrick // readability of debug info intrinsics.
249609467b48Spatrick if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2497*d415bd75Srobert writeDIExpression(Out, Expr, WriterCtx);
249809467b48Spatrick return;
249909467b48Spatrick }
250073471bf0Spatrick if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2501*d415bd75Srobert writeDIArgList(Out, ArgList, WriterCtx, FromValue);
250273471bf0Spatrick return;
250373471bf0Spatrick }
250409467b48Spatrick
250509467b48Spatrick if (const MDNode *N = dyn_cast<MDNode>(MD)) {
250609467b48Spatrick std::unique_ptr<SlotTracker> MachineStorage;
2507*d415bd75Srobert SaveAndRestore SARMachine(WriterCtx.Machine);
2508*d415bd75Srobert if (!WriterCtx.Machine) {
2509*d415bd75Srobert MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2510*d415bd75Srobert WriterCtx.Machine = MachineStorage.get();
251109467b48Spatrick }
2512*d415bd75Srobert int Slot = WriterCtx.Machine->getMetadataSlot(N);
251309467b48Spatrick if (Slot == -1) {
251409467b48Spatrick if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2515*d415bd75Srobert writeDILocation(Out, Loc, WriterCtx);
251609467b48Spatrick return;
251709467b48Spatrick }
251809467b48Spatrick // Give the pointer value instead of "badref", since this comes up all
251909467b48Spatrick // the time when debugging.
252009467b48Spatrick Out << "<" << N << ">";
252109467b48Spatrick } else
252209467b48Spatrick Out << '!' << Slot;
252309467b48Spatrick return;
252409467b48Spatrick }
252509467b48Spatrick
252609467b48Spatrick if (const MDString *MDS = dyn_cast<MDString>(MD)) {
252709467b48Spatrick Out << "!\"";
252809467b48Spatrick printEscapedString(MDS->getString(), Out);
252909467b48Spatrick Out << '"';
253009467b48Spatrick return;
253109467b48Spatrick }
253209467b48Spatrick
253309467b48Spatrick auto *V = cast<ValueAsMetadata>(MD);
2534*d415bd75Srobert assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
253509467b48Spatrick assert((FromValue || !isa<LocalAsMetadata>(V)) &&
253609467b48Spatrick "Unexpected function-local metadata outside of value argument");
253709467b48Spatrick
2538*d415bd75Srobert WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
253909467b48Spatrick Out << ' ';
2540*d415bd75Srobert WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
254109467b48Spatrick }
254209467b48Spatrick
254309467b48Spatrick namespace {
254409467b48Spatrick
254509467b48Spatrick class AssemblyWriter {
254609467b48Spatrick formatted_raw_ostream &Out;
254709467b48Spatrick const Module *TheModule = nullptr;
254809467b48Spatrick const ModuleSummaryIndex *TheIndex = nullptr;
254909467b48Spatrick std::unique_ptr<SlotTracker> SlotTrackerStorage;
255009467b48Spatrick SlotTracker &Machine;
255109467b48Spatrick TypePrinting TypePrinter;
255209467b48Spatrick AssemblyAnnotationWriter *AnnotationWriter = nullptr;
255309467b48Spatrick SetVector<const Comdat *> Comdats;
255409467b48Spatrick bool IsForDebug;
255509467b48Spatrick bool ShouldPreserveUseListOrder;
255673471bf0Spatrick UseListOrderMap UseListOrders;
255709467b48Spatrick SmallVector<StringRef, 8> MDNames;
255809467b48Spatrick /// Synchronization scope names registered with LLVMContext.
255909467b48Spatrick SmallVector<StringRef, 8> SSNs;
256009467b48Spatrick DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
256109467b48Spatrick
256209467b48Spatrick public:
256309467b48Spatrick /// Construct an AssemblyWriter with an external SlotTracker
256409467b48Spatrick AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
256509467b48Spatrick AssemblyAnnotationWriter *AAW, bool IsForDebug,
256609467b48Spatrick bool ShouldPreserveUseListOrder = false);
256709467b48Spatrick
256809467b48Spatrick AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
256909467b48Spatrick const ModuleSummaryIndex *Index, bool IsForDebug);
257009467b48Spatrick
getContext()2571*d415bd75Srobert AsmWriterContext getContext() {
2572*d415bd75Srobert return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2573*d415bd75Srobert }
2574*d415bd75Srobert
257509467b48Spatrick void printMDNodeBody(const MDNode *MD);
257609467b48Spatrick void printNamedMDNode(const NamedMDNode *NMD);
257709467b48Spatrick
257809467b48Spatrick void printModule(const Module *M);
257909467b48Spatrick
258009467b48Spatrick void writeOperand(const Value *Op, bool PrintType);
258109467b48Spatrick void writeParamOperand(const Value *Operand, AttributeSet Attrs);
258209467b48Spatrick void writeOperandBundles(const CallBase *Call);
258309467b48Spatrick void writeSyncScope(const LLVMContext &Context,
258409467b48Spatrick SyncScope::ID SSID);
258509467b48Spatrick void writeAtomic(const LLVMContext &Context,
258609467b48Spatrick AtomicOrdering Ordering,
258709467b48Spatrick SyncScope::ID SSID);
258809467b48Spatrick void writeAtomicCmpXchg(const LLVMContext &Context,
258909467b48Spatrick AtomicOrdering SuccessOrdering,
259009467b48Spatrick AtomicOrdering FailureOrdering,
259109467b48Spatrick SyncScope::ID SSID);
259209467b48Spatrick
259309467b48Spatrick void writeAllMDNodes();
259409467b48Spatrick void writeMDNode(unsigned Slot, const MDNode *Node);
259509467b48Spatrick void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
259609467b48Spatrick void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
259709467b48Spatrick void writeAllAttributeGroups();
259809467b48Spatrick
259909467b48Spatrick void printTypeIdentities();
260009467b48Spatrick void printGlobal(const GlobalVariable *GV);
2601*d415bd75Srobert void printAlias(const GlobalAlias *GA);
2602*d415bd75Srobert void printIFunc(const GlobalIFunc *GI);
260309467b48Spatrick void printComdat(const Comdat *C);
260409467b48Spatrick void printFunction(const Function *F);
260509467b48Spatrick void printArgument(const Argument *FA, AttributeSet Attrs);
260609467b48Spatrick void printBasicBlock(const BasicBlock *BB);
260709467b48Spatrick void printInstructionLine(const Instruction &I);
260809467b48Spatrick void printInstruction(const Instruction &I);
260909467b48Spatrick
261073471bf0Spatrick void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
261109467b48Spatrick void printUseLists(const Function *F);
261209467b48Spatrick
261309467b48Spatrick void printModuleSummaryIndex();
261409467b48Spatrick void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
261509467b48Spatrick void printSummary(const GlobalValueSummary &Summary);
261609467b48Spatrick void printAliasSummary(const AliasSummary *AS);
261709467b48Spatrick void printGlobalVarSummary(const GlobalVarSummary *GS);
261809467b48Spatrick void printFunctionSummary(const FunctionSummary *FS);
261909467b48Spatrick void printTypeIdSummary(const TypeIdSummary &TIS);
262009467b48Spatrick void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
262109467b48Spatrick void printTypeTestResolution(const TypeTestResolution &TTRes);
262209467b48Spatrick void printArgs(const std::vector<uint64_t> &Args);
262309467b48Spatrick void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
262409467b48Spatrick void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
262509467b48Spatrick void printVFuncId(const FunctionSummary::VFuncId VFId);
262609467b48Spatrick void
2627097a140dSpatrick printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
262809467b48Spatrick const char *Tag);
262909467b48Spatrick void
2630097a140dSpatrick printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
263109467b48Spatrick const char *Tag);
263209467b48Spatrick
263309467b48Spatrick private:
263409467b48Spatrick /// Print out metadata attachments.
263509467b48Spatrick void printMetadataAttachments(
263609467b48Spatrick const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
263709467b48Spatrick StringRef Separator);
263809467b48Spatrick
263909467b48Spatrick // printInfoComment - Print a little comment after the instruction indicating
264009467b48Spatrick // which slot it occupies.
264109467b48Spatrick void printInfoComment(const Value &V);
264209467b48Spatrick
264309467b48Spatrick // printGCRelocateComment - print comment after call to the gc.relocate
264409467b48Spatrick // intrinsic indicating base and derived pointer names.
264509467b48Spatrick void printGCRelocateComment(const GCRelocateInst &Relocate);
264609467b48Spatrick };
264709467b48Spatrick
264809467b48Spatrick } // end anonymous namespace
264909467b48Spatrick
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const Module * M,AssemblyAnnotationWriter * AAW,bool IsForDebug,bool ShouldPreserveUseListOrder)265009467b48Spatrick AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
265109467b48Spatrick const Module *M, AssemblyAnnotationWriter *AAW,
265209467b48Spatrick bool IsForDebug, bool ShouldPreserveUseListOrder)
265309467b48Spatrick : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
265409467b48Spatrick IsForDebug(IsForDebug),
265509467b48Spatrick ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
265609467b48Spatrick if (!TheModule)
265709467b48Spatrick return;
265809467b48Spatrick for (const GlobalObject &GO : TheModule->global_objects())
265909467b48Spatrick if (const Comdat *C = GO.getComdat())
266009467b48Spatrick Comdats.insert(C);
266109467b48Spatrick }
266209467b48Spatrick
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const ModuleSummaryIndex * Index,bool IsForDebug)266309467b48Spatrick AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
266409467b48Spatrick const ModuleSummaryIndex *Index, bool IsForDebug)
266509467b48Spatrick : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
266609467b48Spatrick IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
266709467b48Spatrick
writeOperand(const Value * Operand,bool PrintType)266809467b48Spatrick void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
266909467b48Spatrick if (!Operand) {
267009467b48Spatrick Out << "<null operand!>";
267109467b48Spatrick return;
267209467b48Spatrick }
267309467b48Spatrick if (PrintType) {
267409467b48Spatrick TypePrinter.print(Operand->getType(), Out);
267509467b48Spatrick Out << ' ';
267609467b48Spatrick }
2677*d415bd75Srobert auto WriterCtx = getContext();
2678*d415bd75Srobert WriteAsOperandInternal(Out, Operand, WriterCtx);
267909467b48Spatrick }
268009467b48Spatrick
writeSyncScope(const LLVMContext & Context,SyncScope::ID SSID)268109467b48Spatrick void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
268209467b48Spatrick SyncScope::ID SSID) {
268309467b48Spatrick switch (SSID) {
268409467b48Spatrick case SyncScope::System: {
268509467b48Spatrick break;
268609467b48Spatrick }
268709467b48Spatrick default: {
268809467b48Spatrick if (SSNs.empty())
268909467b48Spatrick Context.getSyncScopeNames(SSNs);
269009467b48Spatrick
269109467b48Spatrick Out << " syncscope(\"";
269209467b48Spatrick printEscapedString(SSNs[SSID], Out);
269309467b48Spatrick Out << "\")";
269409467b48Spatrick break;
269509467b48Spatrick }
269609467b48Spatrick }
269709467b48Spatrick }
269809467b48Spatrick
writeAtomic(const LLVMContext & Context,AtomicOrdering Ordering,SyncScope::ID SSID)269909467b48Spatrick void AssemblyWriter::writeAtomic(const LLVMContext &Context,
270009467b48Spatrick AtomicOrdering Ordering,
270109467b48Spatrick SyncScope::ID SSID) {
270209467b48Spatrick if (Ordering == AtomicOrdering::NotAtomic)
270309467b48Spatrick return;
270409467b48Spatrick
270509467b48Spatrick writeSyncScope(Context, SSID);
270609467b48Spatrick Out << " " << toIRString(Ordering);
270709467b48Spatrick }
270809467b48Spatrick
writeAtomicCmpXchg(const LLVMContext & Context,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID)270909467b48Spatrick void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
271009467b48Spatrick AtomicOrdering SuccessOrdering,
271109467b48Spatrick AtomicOrdering FailureOrdering,
271209467b48Spatrick SyncScope::ID SSID) {
271309467b48Spatrick assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
271409467b48Spatrick FailureOrdering != AtomicOrdering::NotAtomic);
271509467b48Spatrick
271609467b48Spatrick writeSyncScope(Context, SSID);
271709467b48Spatrick Out << " " << toIRString(SuccessOrdering);
271809467b48Spatrick Out << " " << toIRString(FailureOrdering);
271909467b48Spatrick }
272009467b48Spatrick
writeParamOperand(const Value * Operand,AttributeSet Attrs)272109467b48Spatrick void AssemblyWriter::writeParamOperand(const Value *Operand,
272209467b48Spatrick AttributeSet Attrs) {
272309467b48Spatrick if (!Operand) {
272409467b48Spatrick Out << "<null operand!>";
272509467b48Spatrick return;
272609467b48Spatrick }
272709467b48Spatrick
272809467b48Spatrick // Print the type
272909467b48Spatrick TypePrinter.print(Operand->getType(), Out);
273009467b48Spatrick // Print parameter attributes list
273109467b48Spatrick if (Attrs.hasAttributes()) {
273209467b48Spatrick Out << ' ';
273309467b48Spatrick writeAttributeSet(Attrs);
273409467b48Spatrick }
273509467b48Spatrick Out << ' ';
273609467b48Spatrick // Print the operand
2737*d415bd75Srobert auto WriterCtx = getContext();
2738*d415bd75Srobert WriteAsOperandInternal(Out, Operand, WriterCtx);
273909467b48Spatrick }
274009467b48Spatrick
writeOperandBundles(const CallBase * Call)274109467b48Spatrick void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
274209467b48Spatrick if (!Call->hasOperandBundles())
274309467b48Spatrick return;
274409467b48Spatrick
274509467b48Spatrick Out << " [ ";
274609467b48Spatrick
274709467b48Spatrick bool FirstBundle = true;
274809467b48Spatrick for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
274909467b48Spatrick OperandBundleUse BU = Call->getOperandBundleAt(i);
275009467b48Spatrick
275109467b48Spatrick if (!FirstBundle)
275209467b48Spatrick Out << ", ";
275309467b48Spatrick FirstBundle = false;
275409467b48Spatrick
275509467b48Spatrick Out << '"';
275609467b48Spatrick printEscapedString(BU.getTagName(), Out);
275709467b48Spatrick Out << '"';
275809467b48Spatrick
275909467b48Spatrick Out << '(';
276009467b48Spatrick
276109467b48Spatrick bool FirstInput = true;
2762*d415bd75Srobert auto WriterCtx = getContext();
276309467b48Spatrick for (const auto &Input : BU.Inputs) {
276409467b48Spatrick if (!FirstInput)
276509467b48Spatrick Out << ", ";
276609467b48Spatrick FirstInput = false;
276709467b48Spatrick
2768*d415bd75Srobert if (Input == nullptr)
2769*d415bd75Srobert Out << "<null operand bundle!>";
2770*d415bd75Srobert else {
277109467b48Spatrick TypePrinter.print(Input->getType(), Out);
277209467b48Spatrick Out << " ";
2773*d415bd75Srobert WriteAsOperandInternal(Out, Input, WriterCtx);
2774*d415bd75Srobert }
277509467b48Spatrick }
277609467b48Spatrick
277709467b48Spatrick Out << ')';
277809467b48Spatrick }
277909467b48Spatrick
278009467b48Spatrick Out << " ]";
278109467b48Spatrick }
278209467b48Spatrick
printModule(const Module * M)278309467b48Spatrick void AssemblyWriter::printModule(const Module *M) {
278409467b48Spatrick Machine.initializeIfNeeded();
278509467b48Spatrick
278609467b48Spatrick if (ShouldPreserveUseListOrder)
278709467b48Spatrick UseListOrders = predictUseListOrder(M);
278809467b48Spatrick
278909467b48Spatrick if (!M->getModuleIdentifier().empty() &&
279009467b48Spatrick // Don't print the ID if it will start a new line (which would
279109467b48Spatrick // require a comment char before it).
279209467b48Spatrick M->getModuleIdentifier().find('\n') == std::string::npos)
279309467b48Spatrick Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
279409467b48Spatrick
279509467b48Spatrick if (!M->getSourceFileName().empty()) {
279609467b48Spatrick Out << "source_filename = \"";
279709467b48Spatrick printEscapedString(M->getSourceFileName(), Out);
279809467b48Spatrick Out << "\"\n";
279909467b48Spatrick }
280009467b48Spatrick
280109467b48Spatrick const std::string &DL = M->getDataLayoutStr();
280209467b48Spatrick if (!DL.empty())
280309467b48Spatrick Out << "target datalayout = \"" << DL << "\"\n";
280409467b48Spatrick if (!M->getTargetTriple().empty())
280509467b48Spatrick Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
280609467b48Spatrick
280709467b48Spatrick if (!M->getModuleInlineAsm().empty()) {
280809467b48Spatrick Out << '\n';
280909467b48Spatrick
281009467b48Spatrick // Split the string into lines, to make it easier to read the .ll file.
281109467b48Spatrick StringRef Asm = M->getModuleInlineAsm();
281209467b48Spatrick do {
281309467b48Spatrick StringRef Front;
281409467b48Spatrick std::tie(Front, Asm) = Asm.split('\n');
281509467b48Spatrick
281609467b48Spatrick // We found a newline, print the portion of the asm string from the
281709467b48Spatrick // last newline up to this newline.
281809467b48Spatrick Out << "module asm \"";
281909467b48Spatrick printEscapedString(Front, Out);
282009467b48Spatrick Out << "\"\n";
282109467b48Spatrick } while (!Asm.empty());
282209467b48Spatrick }
282309467b48Spatrick
282409467b48Spatrick printTypeIdentities();
282509467b48Spatrick
282609467b48Spatrick // Output all comdats.
282709467b48Spatrick if (!Comdats.empty())
282809467b48Spatrick Out << '\n';
282909467b48Spatrick for (const Comdat *C : Comdats) {
283009467b48Spatrick printComdat(C);
283109467b48Spatrick if (C != Comdats.back())
283209467b48Spatrick Out << '\n';
283309467b48Spatrick }
283409467b48Spatrick
283509467b48Spatrick // Output all globals.
283609467b48Spatrick if (!M->global_empty()) Out << '\n';
283709467b48Spatrick for (const GlobalVariable &GV : M->globals()) {
283809467b48Spatrick printGlobal(&GV); Out << '\n';
283909467b48Spatrick }
284009467b48Spatrick
284109467b48Spatrick // Output all aliases.
284209467b48Spatrick if (!M->alias_empty()) Out << "\n";
284309467b48Spatrick for (const GlobalAlias &GA : M->aliases())
2844*d415bd75Srobert printAlias(&GA);
284509467b48Spatrick
284609467b48Spatrick // Output all ifuncs.
284709467b48Spatrick if (!M->ifunc_empty()) Out << "\n";
284809467b48Spatrick for (const GlobalIFunc &GI : M->ifuncs())
2849*d415bd75Srobert printIFunc(&GI);
285009467b48Spatrick
285109467b48Spatrick // Output all of the functions.
285209467b48Spatrick for (const Function &F : *M) {
285309467b48Spatrick Out << '\n';
285409467b48Spatrick printFunction(&F);
285509467b48Spatrick }
285673471bf0Spatrick
285773471bf0Spatrick // Output global use-lists.
285873471bf0Spatrick printUseLists(nullptr);
285909467b48Spatrick
286009467b48Spatrick // Output all attribute groups.
286109467b48Spatrick if (!Machine.as_empty()) {
286209467b48Spatrick Out << '\n';
286309467b48Spatrick writeAllAttributeGroups();
286409467b48Spatrick }
286509467b48Spatrick
286609467b48Spatrick // Output named metadata.
286709467b48Spatrick if (!M->named_metadata_empty()) Out << '\n';
286809467b48Spatrick
286909467b48Spatrick for (const NamedMDNode &Node : M->named_metadata())
287009467b48Spatrick printNamedMDNode(&Node);
287109467b48Spatrick
287209467b48Spatrick // Output metadata.
287309467b48Spatrick if (!Machine.mdn_empty()) {
287409467b48Spatrick Out << '\n';
287509467b48Spatrick writeAllMDNodes();
287609467b48Spatrick }
287709467b48Spatrick }
287809467b48Spatrick
printModuleSummaryIndex()287909467b48Spatrick void AssemblyWriter::printModuleSummaryIndex() {
288009467b48Spatrick assert(TheIndex);
2881097a140dSpatrick int NumSlots = Machine.initializeIndexIfNeeded();
288209467b48Spatrick
288309467b48Spatrick Out << "\n";
288409467b48Spatrick
288509467b48Spatrick // Print module path entries. To print in order, add paths to a vector
288609467b48Spatrick // indexed by module slot.
288709467b48Spatrick std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2888097a140dSpatrick std::string RegularLTOModuleName =
2889097a140dSpatrick ModuleSummaryIndex::getRegularLTOModuleName();
289009467b48Spatrick moduleVec.resize(TheIndex->modulePaths().size());
2891*d415bd75Srobert for (auto &[ModPath, ModId] : TheIndex->modulePaths())
2892*d415bd75Srobert moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
289309467b48Spatrick // A module id of -1 is a special entry for a regular LTO module created
289409467b48Spatrick // during the thin link.
2895*d415bd75Srobert ModId.first == -1u ? RegularLTOModuleName : std::string(ModPath),
2896*d415bd75Srobert ModId.second);
289709467b48Spatrick
289809467b48Spatrick unsigned i = 0;
289909467b48Spatrick for (auto &ModPair : moduleVec) {
290009467b48Spatrick Out << "^" << i++ << " = module: (";
290109467b48Spatrick Out << "path: \"";
290209467b48Spatrick printEscapedString(ModPair.first, Out);
290309467b48Spatrick Out << "\", hash: (";
290409467b48Spatrick FieldSeparator FS;
290509467b48Spatrick for (auto Hash : ModPair.second)
290609467b48Spatrick Out << FS << Hash;
290709467b48Spatrick Out << "))\n";
290809467b48Spatrick }
290909467b48Spatrick
291009467b48Spatrick // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
291109467b48Spatrick // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
291209467b48Spatrick for (auto &GlobalList : *TheIndex) {
291309467b48Spatrick auto GUID = GlobalList.first;
291409467b48Spatrick for (auto &Summary : GlobalList.second.SummaryList)
291509467b48Spatrick SummaryToGUIDMap[Summary.get()] = GUID;
291609467b48Spatrick }
291709467b48Spatrick
291809467b48Spatrick // Print the global value summary entries.
291909467b48Spatrick for (auto &GlobalList : *TheIndex) {
292009467b48Spatrick auto GUID = GlobalList.first;
292109467b48Spatrick auto VI = TheIndex->getValueInfo(GlobalList);
292209467b48Spatrick printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
292309467b48Spatrick }
292409467b48Spatrick
292509467b48Spatrick // Print the TypeIdMap entries.
292673471bf0Spatrick for (const auto &TID : TheIndex->typeIds()) {
292773471bf0Spatrick Out << "^" << Machine.getTypeIdSlot(TID.second.first)
292873471bf0Spatrick << " = typeid: (name: \"" << TID.second.first << "\"";
292973471bf0Spatrick printTypeIdSummary(TID.second.second);
293073471bf0Spatrick Out << ") ; guid = " << TID.first << "\n";
293109467b48Spatrick }
293209467b48Spatrick
293309467b48Spatrick // Print the TypeIdCompatibleVtableMap entries.
293409467b48Spatrick for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
293509467b48Spatrick auto GUID = GlobalValue::getGUID(TId.first);
293609467b48Spatrick Out << "^" << Machine.getGUIDSlot(GUID)
293709467b48Spatrick << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
293809467b48Spatrick printTypeIdCompatibleVtableSummary(TId.second);
293909467b48Spatrick Out << ") ; guid = " << GUID << "\n";
294009467b48Spatrick }
2941097a140dSpatrick
2942097a140dSpatrick // Don't emit flags when it's not really needed (value is zero by default).
2943097a140dSpatrick if (TheIndex->getFlags()) {
2944097a140dSpatrick Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
2945097a140dSpatrick ++NumSlots;
2946097a140dSpatrick }
2947097a140dSpatrick
2948097a140dSpatrick Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
2949097a140dSpatrick << "\n";
295009467b48Spatrick }
295109467b48Spatrick
295209467b48Spatrick static const char *
getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K)295309467b48Spatrick getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
295409467b48Spatrick switch (K) {
295509467b48Spatrick case WholeProgramDevirtResolution::Indir:
295609467b48Spatrick return "indir";
295709467b48Spatrick case WholeProgramDevirtResolution::SingleImpl:
295809467b48Spatrick return "singleImpl";
295909467b48Spatrick case WholeProgramDevirtResolution::BranchFunnel:
296009467b48Spatrick return "branchFunnel";
296109467b48Spatrick }
296209467b48Spatrick llvm_unreachable("invalid WholeProgramDevirtResolution kind");
296309467b48Spatrick }
296409467b48Spatrick
getWholeProgDevirtResByArgKindName(WholeProgramDevirtResolution::ByArg::Kind K)296509467b48Spatrick static const char *getWholeProgDevirtResByArgKindName(
296609467b48Spatrick WholeProgramDevirtResolution::ByArg::Kind K) {
296709467b48Spatrick switch (K) {
296809467b48Spatrick case WholeProgramDevirtResolution::ByArg::Indir:
296909467b48Spatrick return "indir";
297009467b48Spatrick case WholeProgramDevirtResolution::ByArg::UniformRetVal:
297109467b48Spatrick return "uniformRetVal";
297209467b48Spatrick case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
297309467b48Spatrick return "uniqueRetVal";
297409467b48Spatrick case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
297509467b48Spatrick return "virtualConstProp";
297609467b48Spatrick }
297709467b48Spatrick llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
297809467b48Spatrick }
297909467b48Spatrick
getTTResKindName(TypeTestResolution::Kind K)298009467b48Spatrick static const char *getTTResKindName(TypeTestResolution::Kind K) {
298109467b48Spatrick switch (K) {
2982097a140dSpatrick case TypeTestResolution::Unknown:
2983097a140dSpatrick return "unknown";
298409467b48Spatrick case TypeTestResolution::Unsat:
298509467b48Spatrick return "unsat";
298609467b48Spatrick case TypeTestResolution::ByteArray:
298709467b48Spatrick return "byteArray";
298809467b48Spatrick case TypeTestResolution::Inline:
298909467b48Spatrick return "inline";
299009467b48Spatrick case TypeTestResolution::Single:
299109467b48Spatrick return "single";
299209467b48Spatrick case TypeTestResolution::AllOnes:
299309467b48Spatrick return "allOnes";
299409467b48Spatrick }
299509467b48Spatrick llvm_unreachable("invalid TypeTestResolution kind");
299609467b48Spatrick }
299709467b48Spatrick
printTypeTestResolution(const TypeTestResolution & TTRes)299809467b48Spatrick void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
299909467b48Spatrick Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
300009467b48Spatrick << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
300109467b48Spatrick
300209467b48Spatrick // The following fields are only used if the target does not support the use
300309467b48Spatrick // of absolute symbols to store constants. Print only if non-zero.
300409467b48Spatrick if (TTRes.AlignLog2)
300509467b48Spatrick Out << ", alignLog2: " << TTRes.AlignLog2;
300609467b48Spatrick if (TTRes.SizeM1)
300709467b48Spatrick Out << ", sizeM1: " << TTRes.SizeM1;
300809467b48Spatrick if (TTRes.BitMask)
300909467b48Spatrick // BitMask is uint8_t which causes it to print the corresponding char.
301009467b48Spatrick Out << ", bitMask: " << (unsigned)TTRes.BitMask;
301109467b48Spatrick if (TTRes.InlineBits)
301209467b48Spatrick Out << ", inlineBits: " << TTRes.InlineBits;
301309467b48Spatrick
301409467b48Spatrick Out << ")";
301509467b48Spatrick }
301609467b48Spatrick
printTypeIdSummary(const TypeIdSummary & TIS)301709467b48Spatrick void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
301809467b48Spatrick Out << ", summary: (";
301909467b48Spatrick printTypeTestResolution(TIS.TTRes);
302009467b48Spatrick if (!TIS.WPDRes.empty()) {
302109467b48Spatrick Out << ", wpdResolutions: (";
302209467b48Spatrick FieldSeparator FS;
302309467b48Spatrick for (auto &WPDRes : TIS.WPDRes) {
302409467b48Spatrick Out << FS;
302509467b48Spatrick Out << "(offset: " << WPDRes.first << ", ";
302609467b48Spatrick printWPDRes(WPDRes.second);
302709467b48Spatrick Out << ")";
302809467b48Spatrick }
302909467b48Spatrick Out << ")";
303009467b48Spatrick }
303109467b48Spatrick Out << ")";
303209467b48Spatrick }
303309467b48Spatrick
printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo & TI)303409467b48Spatrick void AssemblyWriter::printTypeIdCompatibleVtableSummary(
303509467b48Spatrick const TypeIdCompatibleVtableInfo &TI) {
303609467b48Spatrick Out << ", summary: (";
303709467b48Spatrick FieldSeparator FS;
303809467b48Spatrick for (auto &P : TI) {
303909467b48Spatrick Out << FS;
304009467b48Spatrick Out << "(offset: " << P.AddressPointOffset << ", ";
304109467b48Spatrick Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
304209467b48Spatrick Out << ")";
304309467b48Spatrick }
304409467b48Spatrick Out << ")";
304509467b48Spatrick }
304609467b48Spatrick
printArgs(const std::vector<uint64_t> & Args)304709467b48Spatrick void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
304809467b48Spatrick Out << "args: (";
304909467b48Spatrick FieldSeparator FS;
305009467b48Spatrick for (auto arg : Args) {
305109467b48Spatrick Out << FS;
305209467b48Spatrick Out << arg;
305309467b48Spatrick }
305409467b48Spatrick Out << ")";
305509467b48Spatrick }
305609467b48Spatrick
printWPDRes(const WholeProgramDevirtResolution & WPDRes)305709467b48Spatrick void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
305809467b48Spatrick Out << "wpdRes: (kind: ";
305909467b48Spatrick Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
306009467b48Spatrick
306109467b48Spatrick if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
306209467b48Spatrick Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
306309467b48Spatrick
306409467b48Spatrick if (!WPDRes.ResByArg.empty()) {
306509467b48Spatrick Out << ", resByArg: (";
306609467b48Spatrick FieldSeparator FS;
306709467b48Spatrick for (auto &ResByArg : WPDRes.ResByArg) {
306809467b48Spatrick Out << FS;
306909467b48Spatrick printArgs(ResByArg.first);
307009467b48Spatrick Out << ", byArg: (kind: ";
307109467b48Spatrick Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
307209467b48Spatrick if (ResByArg.second.TheKind ==
307309467b48Spatrick WholeProgramDevirtResolution::ByArg::UniformRetVal ||
307409467b48Spatrick ResByArg.second.TheKind ==
307509467b48Spatrick WholeProgramDevirtResolution::ByArg::UniqueRetVal)
307609467b48Spatrick Out << ", info: " << ResByArg.second.Info;
307709467b48Spatrick
307809467b48Spatrick // The following fields are only used if the target does not support the
307909467b48Spatrick // use of absolute symbols to store constants. Print only if non-zero.
308009467b48Spatrick if (ResByArg.second.Byte || ResByArg.second.Bit)
308109467b48Spatrick Out << ", byte: " << ResByArg.second.Byte
308209467b48Spatrick << ", bit: " << ResByArg.second.Bit;
308309467b48Spatrick
308409467b48Spatrick Out << ")";
308509467b48Spatrick }
308609467b48Spatrick Out << ")";
308709467b48Spatrick }
308809467b48Spatrick Out << ")";
308909467b48Spatrick }
309009467b48Spatrick
getSummaryKindName(GlobalValueSummary::SummaryKind SK)309109467b48Spatrick static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
309209467b48Spatrick switch (SK) {
309309467b48Spatrick case GlobalValueSummary::AliasKind:
309409467b48Spatrick return "alias";
309509467b48Spatrick case GlobalValueSummary::FunctionKind:
309609467b48Spatrick return "function";
309709467b48Spatrick case GlobalValueSummary::GlobalVarKind:
309809467b48Spatrick return "variable";
309909467b48Spatrick }
310009467b48Spatrick llvm_unreachable("invalid summary kind");
310109467b48Spatrick }
310209467b48Spatrick
printAliasSummary(const AliasSummary * AS)310309467b48Spatrick void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
310409467b48Spatrick Out << ", aliasee: ";
310509467b48Spatrick // The indexes emitted for distributed backends may not include the
310609467b48Spatrick // aliasee summary (only if it is being imported directly). Handle
310709467b48Spatrick // that case by just emitting "null" as the aliasee.
310809467b48Spatrick if (AS->hasAliasee())
310909467b48Spatrick Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
311009467b48Spatrick else
311109467b48Spatrick Out << "null";
311209467b48Spatrick }
311309467b48Spatrick
printGlobalVarSummary(const GlobalVarSummary * GS)311409467b48Spatrick void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
311509467b48Spatrick auto VTableFuncs = GS->vTableFuncs();
3116097a140dSpatrick Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3117097a140dSpatrick << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3118097a140dSpatrick << "constant: " << GS->VarFlags.Constant;
3119097a140dSpatrick if (!VTableFuncs.empty())
3120097a140dSpatrick Out << ", "
3121097a140dSpatrick << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3122097a140dSpatrick Out << ")";
3123097a140dSpatrick
312409467b48Spatrick if (!VTableFuncs.empty()) {
312509467b48Spatrick Out << ", vTableFuncs: (";
312609467b48Spatrick FieldSeparator FS;
312709467b48Spatrick for (auto &P : VTableFuncs) {
312809467b48Spatrick Out << FS;
312909467b48Spatrick Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
313009467b48Spatrick << ", offset: " << P.VTableOffset;
313109467b48Spatrick Out << ")";
313209467b48Spatrick }
313309467b48Spatrick Out << ")";
313409467b48Spatrick }
313509467b48Spatrick }
313609467b48Spatrick
getLinkageName(GlobalValue::LinkageTypes LT)313709467b48Spatrick static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
313809467b48Spatrick switch (LT) {
313909467b48Spatrick case GlobalValue::ExternalLinkage:
314009467b48Spatrick return "external";
314109467b48Spatrick case GlobalValue::PrivateLinkage:
314209467b48Spatrick return "private";
314309467b48Spatrick case GlobalValue::InternalLinkage:
314409467b48Spatrick return "internal";
314509467b48Spatrick case GlobalValue::LinkOnceAnyLinkage:
314609467b48Spatrick return "linkonce";
314709467b48Spatrick case GlobalValue::LinkOnceODRLinkage:
314809467b48Spatrick return "linkonce_odr";
314909467b48Spatrick case GlobalValue::WeakAnyLinkage:
315009467b48Spatrick return "weak";
315109467b48Spatrick case GlobalValue::WeakODRLinkage:
315209467b48Spatrick return "weak_odr";
315309467b48Spatrick case GlobalValue::CommonLinkage:
315409467b48Spatrick return "common";
315509467b48Spatrick case GlobalValue::AppendingLinkage:
315609467b48Spatrick return "appending";
315709467b48Spatrick case GlobalValue::ExternalWeakLinkage:
315809467b48Spatrick return "extern_weak";
315909467b48Spatrick case GlobalValue::AvailableExternallyLinkage:
316009467b48Spatrick return "available_externally";
316109467b48Spatrick }
316209467b48Spatrick llvm_unreachable("invalid linkage");
316309467b48Spatrick }
316409467b48Spatrick
316509467b48Spatrick // When printing the linkage types in IR where the ExternalLinkage is
316609467b48Spatrick // not printed, and other linkage types are expected to be printed with
316709467b48Spatrick // a space after the name.
getLinkageNameWithSpace(GlobalValue::LinkageTypes LT)316809467b48Spatrick static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
316909467b48Spatrick if (LT == GlobalValue::ExternalLinkage)
317009467b48Spatrick return "";
317109467b48Spatrick return getLinkageName(LT) + " ";
317209467b48Spatrick }
317309467b48Spatrick
getVisibilityName(GlobalValue::VisibilityTypes Vis)317473471bf0Spatrick static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
317573471bf0Spatrick switch (Vis) {
317673471bf0Spatrick case GlobalValue::DefaultVisibility:
317773471bf0Spatrick return "default";
317873471bf0Spatrick case GlobalValue::HiddenVisibility:
317973471bf0Spatrick return "hidden";
318073471bf0Spatrick case GlobalValue::ProtectedVisibility:
318173471bf0Spatrick return "protected";
318273471bf0Spatrick }
318373471bf0Spatrick llvm_unreachable("invalid visibility");
318473471bf0Spatrick }
318573471bf0Spatrick
printFunctionSummary(const FunctionSummary * FS)318609467b48Spatrick void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
318709467b48Spatrick Out << ", insts: " << FS->instCount();
3188*d415bd75Srobert if (FS->fflags().anyFlagSet())
3189*d415bd75Srobert Out << ", " << FS->fflags();
319009467b48Spatrick
319109467b48Spatrick if (!FS->calls().empty()) {
319209467b48Spatrick Out << ", calls: (";
319309467b48Spatrick FieldSeparator IFS;
319409467b48Spatrick for (auto &Call : FS->calls()) {
319509467b48Spatrick Out << IFS;
319609467b48Spatrick Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
319709467b48Spatrick if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
319809467b48Spatrick Out << ", hotness: " << getHotnessName(Call.second.getHotness());
319909467b48Spatrick else if (Call.second.RelBlockFreq)
320009467b48Spatrick Out << ", relbf: " << Call.second.RelBlockFreq;
320109467b48Spatrick Out << ")";
320209467b48Spatrick }
320309467b48Spatrick Out << ")";
320409467b48Spatrick }
320509467b48Spatrick
320609467b48Spatrick if (const auto *TIdInfo = FS->getTypeIdInfo())
320709467b48Spatrick printTypeIdInfo(*TIdInfo);
3208097a140dSpatrick
3209*d415bd75Srobert // The AllocationType identifiers capture the profiled context behavior
3210*d415bd75Srobert // reaching a specific static allocation site (possibly cloned). Thus
3211*d415bd75Srobert // "notcoldandcold" implies there are multiple contexts which reach this site,
3212*d415bd75Srobert // some of which are cold and some of which are not, and that need to
3213*d415bd75Srobert // disambiguate via cloning or other context identification.
3214*d415bd75Srobert auto AllocTypeName = [](uint8_t Type) -> const char * {
3215*d415bd75Srobert switch (Type) {
3216*d415bd75Srobert case (uint8_t)AllocationType::None:
3217*d415bd75Srobert return "none";
3218*d415bd75Srobert case (uint8_t)AllocationType::NotCold:
3219*d415bd75Srobert return "notcold";
3220*d415bd75Srobert case (uint8_t)AllocationType::Cold:
3221*d415bd75Srobert return "cold";
3222*d415bd75Srobert case (uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold:
3223*d415bd75Srobert return "notcoldandcold";
3224*d415bd75Srobert }
3225*d415bd75Srobert llvm_unreachable("Unexpected alloc type");
3226*d415bd75Srobert };
3227*d415bd75Srobert
3228*d415bd75Srobert if (!FS->allocs().empty()) {
3229*d415bd75Srobert Out << ", allocs: (";
3230*d415bd75Srobert FieldSeparator AFS;
3231*d415bd75Srobert for (auto &AI : FS->allocs()) {
3232*d415bd75Srobert Out << AFS;
3233*d415bd75Srobert Out << "(versions: (";
3234*d415bd75Srobert FieldSeparator VFS;
3235*d415bd75Srobert for (auto V : AI.Versions) {
3236*d415bd75Srobert Out << VFS;
3237*d415bd75Srobert Out << AllocTypeName(V);
3238*d415bd75Srobert }
3239*d415bd75Srobert Out << "), memProf: (";
3240*d415bd75Srobert FieldSeparator MIBFS;
3241*d415bd75Srobert for (auto &MIB : AI.MIBs) {
3242*d415bd75Srobert Out << MIBFS;
3243*d415bd75Srobert Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3244*d415bd75Srobert Out << ", stackIds: (";
3245*d415bd75Srobert FieldSeparator SIDFS;
3246*d415bd75Srobert for (auto Id : MIB.StackIdIndices) {
3247*d415bd75Srobert Out << SIDFS;
3248*d415bd75Srobert Out << TheIndex->getStackIdAtIndex(Id);
3249*d415bd75Srobert }
3250*d415bd75Srobert Out << "))";
3251*d415bd75Srobert }
3252*d415bd75Srobert Out << "))";
3253*d415bd75Srobert }
3254*d415bd75Srobert Out << ")";
3255*d415bd75Srobert }
3256*d415bd75Srobert
3257*d415bd75Srobert if (!FS->callsites().empty()) {
3258*d415bd75Srobert Out << ", callsites: (";
3259*d415bd75Srobert FieldSeparator SNFS;
3260*d415bd75Srobert for (auto &CI : FS->callsites()) {
3261*d415bd75Srobert Out << SNFS;
3262*d415bd75Srobert if (CI.Callee)
3263*d415bd75Srobert Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3264*d415bd75Srobert else
3265*d415bd75Srobert Out << "(callee: null";
3266*d415bd75Srobert Out << ", clones: (";
3267*d415bd75Srobert FieldSeparator VFS;
3268*d415bd75Srobert for (auto V : CI.Clones) {
3269*d415bd75Srobert Out << VFS;
3270*d415bd75Srobert Out << V;
3271*d415bd75Srobert }
3272*d415bd75Srobert Out << "), stackIds: (";
3273*d415bd75Srobert FieldSeparator SIDFS;
3274*d415bd75Srobert for (auto Id : CI.StackIdIndices) {
3275*d415bd75Srobert Out << SIDFS;
3276*d415bd75Srobert Out << TheIndex->getStackIdAtIndex(Id);
3277*d415bd75Srobert }
3278*d415bd75Srobert Out << "))";
3279*d415bd75Srobert }
3280*d415bd75Srobert Out << ")";
3281*d415bd75Srobert }
3282*d415bd75Srobert
3283097a140dSpatrick auto PrintRange = [&](const ConstantRange &Range) {
328473471bf0Spatrick Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3285097a140dSpatrick };
3286097a140dSpatrick
3287097a140dSpatrick if (!FS->paramAccesses().empty()) {
3288097a140dSpatrick Out << ", params: (";
3289097a140dSpatrick FieldSeparator IFS;
3290097a140dSpatrick for (auto &PS : FS->paramAccesses()) {
3291097a140dSpatrick Out << IFS;
3292097a140dSpatrick Out << "(param: " << PS.ParamNo;
3293097a140dSpatrick Out << ", offset: ";
3294097a140dSpatrick PrintRange(PS.Use);
3295097a140dSpatrick if (!PS.Calls.empty()) {
3296097a140dSpatrick Out << ", calls: (";
3297097a140dSpatrick FieldSeparator IFS;
3298097a140dSpatrick for (auto &Call : PS.Calls) {
3299097a140dSpatrick Out << IFS;
330073471bf0Spatrick Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3301097a140dSpatrick Out << ", param: " << Call.ParamNo;
3302097a140dSpatrick Out << ", offset: ";
3303097a140dSpatrick PrintRange(Call.Offsets);
3304097a140dSpatrick Out << ")";
3305097a140dSpatrick }
3306097a140dSpatrick Out << ")";
3307097a140dSpatrick }
3308097a140dSpatrick Out << ")";
3309097a140dSpatrick }
3310097a140dSpatrick Out << ")";
3311097a140dSpatrick }
331209467b48Spatrick }
331309467b48Spatrick
printTypeIdInfo(const FunctionSummary::TypeIdInfo & TIDInfo)331409467b48Spatrick void AssemblyWriter::printTypeIdInfo(
331509467b48Spatrick const FunctionSummary::TypeIdInfo &TIDInfo) {
331609467b48Spatrick Out << ", typeIdInfo: (";
331709467b48Spatrick FieldSeparator TIDFS;
331809467b48Spatrick if (!TIDInfo.TypeTests.empty()) {
331909467b48Spatrick Out << TIDFS;
332009467b48Spatrick Out << "typeTests: (";
332109467b48Spatrick FieldSeparator FS;
332209467b48Spatrick for (auto &GUID : TIDInfo.TypeTests) {
332309467b48Spatrick auto TidIter = TheIndex->typeIds().equal_range(GUID);
332409467b48Spatrick if (TidIter.first == TidIter.second) {
332509467b48Spatrick Out << FS;
332609467b48Spatrick Out << GUID;
332709467b48Spatrick continue;
332809467b48Spatrick }
332909467b48Spatrick // Print all type id that correspond to this GUID.
333009467b48Spatrick for (auto It = TidIter.first; It != TidIter.second; ++It) {
333109467b48Spatrick Out << FS;
333209467b48Spatrick auto Slot = Machine.getTypeIdSlot(It->second.first);
333309467b48Spatrick assert(Slot != -1);
333409467b48Spatrick Out << "^" << Slot;
333509467b48Spatrick }
333609467b48Spatrick }
333709467b48Spatrick Out << ")";
333809467b48Spatrick }
333909467b48Spatrick if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
334009467b48Spatrick Out << TIDFS;
334109467b48Spatrick printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
334209467b48Spatrick }
334309467b48Spatrick if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
334409467b48Spatrick Out << TIDFS;
334509467b48Spatrick printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
334609467b48Spatrick }
334709467b48Spatrick if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
334809467b48Spatrick Out << TIDFS;
334909467b48Spatrick printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
335009467b48Spatrick "typeTestAssumeConstVCalls");
335109467b48Spatrick }
335209467b48Spatrick if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
335309467b48Spatrick Out << TIDFS;
335409467b48Spatrick printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
335509467b48Spatrick "typeCheckedLoadConstVCalls");
335609467b48Spatrick }
335709467b48Spatrick Out << ")";
335809467b48Spatrick }
335909467b48Spatrick
printVFuncId(const FunctionSummary::VFuncId VFId)336009467b48Spatrick void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
336109467b48Spatrick auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
336209467b48Spatrick if (TidIter.first == TidIter.second) {
336309467b48Spatrick Out << "vFuncId: (";
336409467b48Spatrick Out << "guid: " << VFId.GUID;
336509467b48Spatrick Out << ", offset: " << VFId.Offset;
336609467b48Spatrick Out << ")";
336709467b48Spatrick return;
336809467b48Spatrick }
336909467b48Spatrick // Print all type id that correspond to this GUID.
337009467b48Spatrick FieldSeparator FS;
337109467b48Spatrick for (auto It = TidIter.first; It != TidIter.second; ++It) {
337209467b48Spatrick Out << FS;
337309467b48Spatrick Out << "vFuncId: (";
337409467b48Spatrick auto Slot = Machine.getTypeIdSlot(It->second.first);
337509467b48Spatrick assert(Slot != -1);
337609467b48Spatrick Out << "^" << Slot;
337709467b48Spatrick Out << ", offset: " << VFId.Offset;
337809467b48Spatrick Out << ")";
337909467b48Spatrick }
338009467b48Spatrick }
338109467b48Spatrick
printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> & VCallList,const char * Tag)338209467b48Spatrick void AssemblyWriter::printNonConstVCalls(
3383097a140dSpatrick const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
338409467b48Spatrick Out << Tag << ": (";
338509467b48Spatrick FieldSeparator FS;
338609467b48Spatrick for (auto &VFuncId : VCallList) {
338709467b48Spatrick Out << FS;
338809467b48Spatrick printVFuncId(VFuncId);
338909467b48Spatrick }
339009467b48Spatrick Out << ")";
339109467b48Spatrick }
339209467b48Spatrick
printConstVCalls(const std::vector<FunctionSummary::ConstVCall> & VCallList,const char * Tag)339309467b48Spatrick void AssemblyWriter::printConstVCalls(
3394097a140dSpatrick const std::vector<FunctionSummary::ConstVCall> &VCallList,
3395097a140dSpatrick const char *Tag) {
339609467b48Spatrick Out << Tag << ": (";
339709467b48Spatrick FieldSeparator FS;
339809467b48Spatrick for (auto &ConstVCall : VCallList) {
339909467b48Spatrick Out << FS;
340009467b48Spatrick Out << "(";
340109467b48Spatrick printVFuncId(ConstVCall.VFunc);
340209467b48Spatrick if (!ConstVCall.Args.empty()) {
340309467b48Spatrick Out << ", ";
340409467b48Spatrick printArgs(ConstVCall.Args);
340509467b48Spatrick }
340609467b48Spatrick Out << ")";
340709467b48Spatrick }
340809467b48Spatrick Out << ")";
340909467b48Spatrick }
341009467b48Spatrick
printSummary(const GlobalValueSummary & Summary)341109467b48Spatrick void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
341209467b48Spatrick GlobalValueSummary::GVFlags GVFlags = Summary.flags();
341309467b48Spatrick GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
341409467b48Spatrick Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
341509467b48Spatrick Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
341609467b48Spatrick << ", flags: (";
341709467b48Spatrick Out << "linkage: " << getLinkageName(LT);
341873471bf0Spatrick Out << ", visibility: "
341973471bf0Spatrick << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);
342009467b48Spatrick Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
342109467b48Spatrick Out << ", live: " << GVFlags.Live;
342209467b48Spatrick Out << ", dsoLocal: " << GVFlags.DSOLocal;
342309467b48Spatrick Out << ", canAutoHide: " << GVFlags.CanAutoHide;
342409467b48Spatrick Out << ")";
342509467b48Spatrick
342609467b48Spatrick if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
342709467b48Spatrick printAliasSummary(cast<AliasSummary>(&Summary));
342809467b48Spatrick else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
342909467b48Spatrick printFunctionSummary(cast<FunctionSummary>(&Summary));
343009467b48Spatrick else
343109467b48Spatrick printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
343209467b48Spatrick
343309467b48Spatrick auto RefList = Summary.refs();
343409467b48Spatrick if (!RefList.empty()) {
343509467b48Spatrick Out << ", refs: (";
343609467b48Spatrick FieldSeparator FS;
343709467b48Spatrick for (auto &Ref : RefList) {
343809467b48Spatrick Out << FS;
343909467b48Spatrick if (Ref.isReadOnly())
344009467b48Spatrick Out << "readonly ";
344109467b48Spatrick else if (Ref.isWriteOnly())
344209467b48Spatrick Out << "writeonly ";
344309467b48Spatrick Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
344409467b48Spatrick }
344509467b48Spatrick Out << ")";
344609467b48Spatrick }
344709467b48Spatrick
344809467b48Spatrick Out << ")";
344909467b48Spatrick }
345009467b48Spatrick
printSummaryInfo(unsigned Slot,const ValueInfo & VI)345109467b48Spatrick void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
345209467b48Spatrick Out << "^" << Slot << " = gv: (";
345309467b48Spatrick if (!VI.name().empty())
345409467b48Spatrick Out << "name: \"" << VI.name() << "\"";
345509467b48Spatrick else
345609467b48Spatrick Out << "guid: " << VI.getGUID();
345709467b48Spatrick if (!VI.getSummaryList().empty()) {
345809467b48Spatrick Out << ", summaries: (";
345909467b48Spatrick FieldSeparator FS;
346009467b48Spatrick for (auto &Summary : VI.getSummaryList()) {
346109467b48Spatrick Out << FS;
346209467b48Spatrick printSummary(*Summary);
346309467b48Spatrick }
346409467b48Spatrick Out << ")";
346509467b48Spatrick }
346609467b48Spatrick Out << ")";
346709467b48Spatrick if (!VI.name().empty())
346809467b48Spatrick Out << " ; guid = " << VI.getGUID();
346909467b48Spatrick Out << "\n";
347009467b48Spatrick }
347109467b48Spatrick
printMetadataIdentifier(StringRef Name,formatted_raw_ostream & Out)347209467b48Spatrick static void printMetadataIdentifier(StringRef Name,
347309467b48Spatrick formatted_raw_ostream &Out) {
347409467b48Spatrick if (Name.empty()) {
347509467b48Spatrick Out << "<empty name> ";
347609467b48Spatrick } else {
347709467b48Spatrick if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
347809467b48Spatrick Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
347909467b48Spatrick Out << Name[0];
348009467b48Spatrick else
348109467b48Spatrick Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
348209467b48Spatrick for (unsigned i = 1, e = Name.size(); i != e; ++i) {
348309467b48Spatrick unsigned char C = Name[i];
348409467b48Spatrick if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
348509467b48Spatrick C == '.' || C == '_')
348609467b48Spatrick Out << C;
348709467b48Spatrick else
348809467b48Spatrick Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
348909467b48Spatrick }
349009467b48Spatrick }
349109467b48Spatrick }
349209467b48Spatrick
printNamedMDNode(const NamedMDNode * NMD)349309467b48Spatrick void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
349409467b48Spatrick Out << '!';
349509467b48Spatrick printMetadataIdentifier(NMD->getName(), Out);
349609467b48Spatrick Out << " = !{";
349709467b48Spatrick for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
349809467b48Spatrick if (i)
349909467b48Spatrick Out << ", ";
350009467b48Spatrick
350109467b48Spatrick // Write DIExpressions inline.
350209467b48Spatrick // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
350309467b48Spatrick MDNode *Op = NMD->getOperand(i);
350473471bf0Spatrick assert(!isa<DIArgList>(Op) &&
350573471bf0Spatrick "DIArgLists should not appear in NamedMDNodes");
350609467b48Spatrick if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3507*d415bd75Srobert writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
350809467b48Spatrick continue;
350909467b48Spatrick }
351009467b48Spatrick
351109467b48Spatrick int Slot = Machine.getMetadataSlot(Op);
351209467b48Spatrick if (Slot == -1)
351309467b48Spatrick Out << "<badref>";
351409467b48Spatrick else
351509467b48Spatrick Out << '!' << Slot;
351609467b48Spatrick }
351709467b48Spatrick Out << "}\n";
351809467b48Spatrick }
351909467b48Spatrick
PrintVisibility(GlobalValue::VisibilityTypes Vis,formatted_raw_ostream & Out)352009467b48Spatrick static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
352109467b48Spatrick formatted_raw_ostream &Out) {
352209467b48Spatrick switch (Vis) {
352309467b48Spatrick case GlobalValue::DefaultVisibility: break;
352409467b48Spatrick case GlobalValue::HiddenVisibility: Out << "hidden "; break;
352509467b48Spatrick case GlobalValue::ProtectedVisibility: Out << "protected "; break;
352609467b48Spatrick }
352709467b48Spatrick }
352809467b48Spatrick
PrintDSOLocation(const GlobalValue & GV,formatted_raw_ostream & Out)352909467b48Spatrick static void PrintDSOLocation(const GlobalValue &GV,
353009467b48Spatrick formatted_raw_ostream &Out) {
3531097a140dSpatrick if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
353209467b48Spatrick Out << "dso_local ";
353309467b48Spatrick }
353409467b48Spatrick
PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,formatted_raw_ostream & Out)353509467b48Spatrick static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
353609467b48Spatrick formatted_raw_ostream &Out) {
353709467b48Spatrick switch (SCT) {
353809467b48Spatrick case GlobalValue::DefaultStorageClass: break;
353909467b48Spatrick case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
354009467b48Spatrick case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
354109467b48Spatrick }
354209467b48Spatrick }
354309467b48Spatrick
PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,formatted_raw_ostream & Out)354409467b48Spatrick static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
354509467b48Spatrick formatted_raw_ostream &Out) {
354609467b48Spatrick switch (TLM) {
354709467b48Spatrick case GlobalVariable::NotThreadLocal:
354809467b48Spatrick break;
354909467b48Spatrick case GlobalVariable::GeneralDynamicTLSModel:
355009467b48Spatrick Out << "thread_local ";
355109467b48Spatrick break;
355209467b48Spatrick case GlobalVariable::LocalDynamicTLSModel:
355309467b48Spatrick Out << "thread_local(localdynamic) ";
355409467b48Spatrick break;
355509467b48Spatrick case GlobalVariable::InitialExecTLSModel:
355609467b48Spatrick Out << "thread_local(initialexec) ";
355709467b48Spatrick break;
355809467b48Spatrick case GlobalVariable::LocalExecTLSModel:
355909467b48Spatrick Out << "thread_local(localexec) ";
356009467b48Spatrick break;
356109467b48Spatrick }
356209467b48Spatrick }
356309467b48Spatrick
getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA)356409467b48Spatrick static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
356509467b48Spatrick switch (UA) {
356609467b48Spatrick case GlobalVariable::UnnamedAddr::None:
356709467b48Spatrick return "";
356809467b48Spatrick case GlobalVariable::UnnamedAddr::Local:
356909467b48Spatrick return "local_unnamed_addr";
357009467b48Spatrick case GlobalVariable::UnnamedAddr::Global:
357109467b48Spatrick return "unnamed_addr";
357209467b48Spatrick }
357309467b48Spatrick llvm_unreachable("Unknown UnnamedAddr");
357409467b48Spatrick }
357509467b48Spatrick
maybePrintComdat(formatted_raw_ostream & Out,const GlobalObject & GO)357609467b48Spatrick static void maybePrintComdat(formatted_raw_ostream &Out,
357709467b48Spatrick const GlobalObject &GO) {
357809467b48Spatrick const Comdat *C = GO.getComdat();
357909467b48Spatrick if (!C)
358009467b48Spatrick return;
358109467b48Spatrick
358209467b48Spatrick if (isa<GlobalVariable>(GO))
358309467b48Spatrick Out << ',';
358409467b48Spatrick Out << " comdat";
358509467b48Spatrick
358609467b48Spatrick if (GO.getName() == C->getName())
358709467b48Spatrick return;
358809467b48Spatrick
358909467b48Spatrick Out << '(';
359009467b48Spatrick PrintLLVMName(Out, C->getName(), ComdatPrefix);
359109467b48Spatrick Out << ')';
359209467b48Spatrick }
359309467b48Spatrick
printGlobal(const GlobalVariable * GV)359409467b48Spatrick void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
359509467b48Spatrick if (GV->isMaterializable())
359609467b48Spatrick Out << "; Materializable\n";
359709467b48Spatrick
3598*d415bd75Srobert AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3599*d415bd75Srobert WriteAsOperandInternal(Out, GV, WriterCtx);
360009467b48Spatrick Out << " = ";
360109467b48Spatrick
360209467b48Spatrick if (!GV->hasInitializer() && GV->hasExternalLinkage())
360309467b48Spatrick Out << "external ";
360409467b48Spatrick
360509467b48Spatrick Out << getLinkageNameWithSpace(GV->getLinkage());
360609467b48Spatrick PrintDSOLocation(*GV, Out);
360709467b48Spatrick PrintVisibility(GV->getVisibility(), Out);
360809467b48Spatrick PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
360909467b48Spatrick PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
361009467b48Spatrick StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
361109467b48Spatrick if (!UA.empty())
361209467b48Spatrick Out << UA << ' ';
361309467b48Spatrick
361409467b48Spatrick if (unsigned AddressSpace = GV->getType()->getAddressSpace())
361509467b48Spatrick Out << "addrspace(" << AddressSpace << ") ";
361609467b48Spatrick if (GV->isExternallyInitialized()) Out << "externally_initialized ";
361709467b48Spatrick Out << (GV->isConstant() ? "constant " : "global ");
361809467b48Spatrick TypePrinter.print(GV->getValueType(), Out);
361909467b48Spatrick
362009467b48Spatrick if (GV->hasInitializer()) {
362109467b48Spatrick Out << ' ';
362209467b48Spatrick writeOperand(GV->getInitializer(), false);
362309467b48Spatrick }
362409467b48Spatrick
362509467b48Spatrick if (GV->hasSection()) {
362609467b48Spatrick Out << ", section \"";
362709467b48Spatrick printEscapedString(GV->getSection(), Out);
362809467b48Spatrick Out << '"';
362909467b48Spatrick }
363009467b48Spatrick if (GV->hasPartition()) {
363109467b48Spatrick Out << ", partition \"";
363209467b48Spatrick printEscapedString(GV->getPartition(), Out);
363309467b48Spatrick Out << '"';
363409467b48Spatrick }
363509467b48Spatrick
3636*d415bd75Srobert using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
3637*d415bd75Srobert if (GV->hasSanitizerMetadata()) {
3638*d415bd75Srobert SanitizerMetadata MD = GV->getSanitizerMetadata();
3639*d415bd75Srobert if (MD.NoAddress)
3640*d415bd75Srobert Out << ", no_sanitize_address";
3641*d415bd75Srobert if (MD.NoHWAddress)
3642*d415bd75Srobert Out << ", no_sanitize_hwaddress";
3643*d415bd75Srobert if (MD.Memtag)
3644*d415bd75Srobert Out << ", sanitize_memtag";
3645*d415bd75Srobert if (MD.IsDynInit)
3646*d415bd75Srobert Out << ", sanitize_address_dyninit";
3647*d415bd75Srobert }
3648*d415bd75Srobert
364909467b48Spatrick maybePrintComdat(Out, *GV);
3650*d415bd75Srobert if (MaybeAlign A = GV->getAlign())
3651*d415bd75Srobert Out << ", align " << A->value();
365209467b48Spatrick
365309467b48Spatrick SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
365409467b48Spatrick GV->getAllMetadata(MDs);
365509467b48Spatrick printMetadataAttachments(MDs, ", ");
365609467b48Spatrick
365709467b48Spatrick auto Attrs = GV->getAttributes();
365809467b48Spatrick if (Attrs.hasAttributes())
365909467b48Spatrick Out << " #" << Machine.getAttributeGroupSlot(Attrs);
366009467b48Spatrick
366109467b48Spatrick printInfoComment(*GV);
366209467b48Spatrick }
366309467b48Spatrick
printAlias(const GlobalAlias * GA)3664*d415bd75Srobert void AssemblyWriter::printAlias(const GlobalAlias *GA) {
3665*d415bd75Srobert if (GA->isMaterializable())
366609467b48Spatrick Out << "; Materializable\n";
366709467b48Spatrick
3668*d415bd75Srobert AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
3669*d415bd75Srobert WriteAsOperandInternal(Out, GA, WriterCtx);
367009467b48Spatrick Out << " = ";
367109467b48Spatrick
3672*d415bd75Srobert Out << getLinkageNameWithSpace(GA->getLinkage());
3673*d415bd75Srobert PrintDSOLocation(*GA, Out);
3674*d415bd75Srobert PrintVisibility(GA->getVisibility(), Out);
3675*d415bd75Srobert PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
3676*d415bd75Srobert PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
3677*d415bd75Srobert StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());
367809467b48Spatrick if (!UA.empty())
367909467b48Spatrick Out << UA << ' ';
368009467b48Spatrick
368109467b48Spatrick Out << "alias ";
368209467b48Spatrick
3683*d415bd75Srobert TypePrinter.print(GA->getValueType(), Out);
368409467b48Spatrick Out << ", ";
368509467b48Spatrick
3686*d415bd75Srobert if (const Constant *Aliasee = GA->getAliasee()) {
3687*d415bd75Srobert writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
368809467b48Spatrick } else {
3689*d415bd75Srobert TypePrinter.print(GA->getType(), Out);
3690*d415bd75Srobert Out << " <<NULL ALIASEE>>";
369109467b48Spatrick }
369209467b48Spatrick
3693*d415bd75Srobert if (GA->hasPartition()) {
369409467b48Spatrick Out << ", partition \"";
3695*d415bd75Srobert printEscapedString(GA->getPartition(), Out);
369609467b48Spatrick Out << '"';
369709467b48Spatrick }
369809467b48Spatrick
3699*d415bd75Srobert printInfoComment(*GA);
3700*d415bd75Srobert Out << '\n';
3701*d415bd75Srobert }
3702*d415bd75Srobert
printIFunc(const GlobalIFunc * GI)3703*d415bd75Srobert void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
3704*d415bd75Srobert if (GI->isMaterializable())
3705*d415bd75Srobert Out << "; Materializable\n";
3706*d415bd75Srobert
3707*d415bd75Srobert AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
3708*d415bd75Srobert WriteAsOperandInternal(Out, GI, WriterCtx);
3709*d415bd75Srobert Out << " = ";
3710*d415bd75Srobert
3711*d415bd75Srobert Out << getLinkageNameWithSpace(GI->getLinkage());
3712*d415bd75Srobert PrintDSOLocation(*GI, Out);
3713*d415bd75Srobert PrintVisibility(GI->getVisibility(), Out);
3714*d415bd75Srobert
3715*d415bd75Srobert Out << "ifunc ";
3716*d415bd75Srobert
3717*d415bd75Srobert TypePrinter.print(GI->getValueType(), Out);
3718*d415bd75Srobert Out << ", ";
3719*d415bd75Srobert
3720*d415bd75Srobert if (const Constant *Resolver = GI->getResolver()) {
3721*d415bd75Srobert writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
3722*d415bd75Srobert } else {
3723*d415bd75Srobert TypePrinter.print(GI->getType(), Out);
3724*d415bd75Srobert Out << " <<NULL RESOLVER>>";
3725*d415bd75Srobert }
3726*d415bd75Srobert
3727*d415bd75Srobert if (GI->hasPartition()) {
3728*d415bd75Srobert Out << ", partition \"";
3729*d415bd75Srobert printEscapedString(GI->getPartition(), Out);
3730*d415bd75Srobert Out << '"';
3731*d415bd75Srobert }
3732*d415bd75Srobert
3733*d415bd75Srobert printInfoComment(*GI);
373409467b48Spatrick Out << '\n';
373509467b48Spatrick }
373609467b48Spatrick
printComdat(const Comdat * C)373709467b48Spatrick void AssemblyWriter::printComdat(const Comdat *C) {
373809467b48Spatrick C->print(Out);
373909467b48Spatrick }
374009467b48Spatrick
printTypeIdentities()374109467b48Spatrick void AssemblyWriter::printTypeIdentities() {
374209467b48Spatrick if (TypePrinter.empty())
374309467b48Spatrick return;
374409467b48Spatrick
374509467b48Spatrick Out << '\n';
374609467b48Spatrick
374709467b48Spatrick // Emit all numbered types.
374809467b48Spatrick auto &NumberedTypes = TypePrinter.getNumberedTypes();
374909467b48Spatrick for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
375009467b48Spatrick Out << '%' << I << " = type ";
375109467b48Spatrick
375209467b48Spatrick // Make sure we print out at least one level of the type structure, so
375309467b48Spatrick // that we do not get %2 = type %2
375409467b48Spatrick TypePrinter.printStructBody(NumberedTypes[I], Out);
375509467b48Spatrick Out << '\n';
375609467b48Spatrick }
375709467b48Spatrick
375809467b48Spatrick auto &NamedTypes = TypePrinter.getNamedTypes();
3759*d415bd75Srobert for (StructType *NamedType : NamedTypes) {
3760*d415bd75Srobert PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
376109467b48Spatrick Out << " = type ";
376209467b48Spatrick
376309467b48Spatrick // Make sure we print out at least one level of the type structure, so
376409467b48Spatrick // that we do not get %FILE = type %FILE
3765*d415bd75Srobert TypePrinter.printStructBody(NamedType, Out);
376609467b48Spatrick Out << '\n';
376709467b48Spatrick }
376809467b48Spatrick }
376909467b48Spatrick
377009467b48Spatrick /// printFunction - Print all aspects of a function.
printFunction(const Function * F)377109467b48Spatrick void AssemblyWriter::printFunction(const Function *F) {
377209467b48Spatrick if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
377309467b48Spatrick
377409467b48Spatrick if (F->isMaterializable())
377509467b48Spatrick Out << "; Materializable\n";
377609467b48Spatrick
377709467b48Spatrick const AttributeList &Attrs = F->getAttributes();
3778*d415bd75Srobert if (Attrs.hasFnAttrs()) {
3779*d415bd75Srobert AttributeSet AS = Attrs.getFnAttrs();
378009467b48Spatrick std::string AttrStr;
378109467b48Spatrick
378209467b48Spatrick for (const Attribute &Attr : AS) {
378309467b48Spatrick if (!Attr.isStringAttribute()) {
378409467b48Spatrick if (!AttrStr.empty()) AttrStr += ' ';
378509467b48Spatrick AttrStr += Attr.getAsString();
378609467b48Spatrick }
378709467b48Spatrick }
378809467b48Spatrick
378909467b48Spatrick if (!AttrStr.empty())
379009467b48Spatrick Out << "; Function Attrs: " << AttrStr << '\n';
379109467b48Spatrick }
379209467b48Spatrick
379309467b48Spatrick Machine.incorporateFunction(F);
379409467b48Spatrick
379509467b48Spatrick if (F->isDeclaration()) {
379609467b48Spatrick Out << "declare";
379709467b48Spatrick SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
379809467b48Spatrick F->getAllMetadata(MDs);
379909467b48Spatrick printMetadataAttachments(MDs, " ");
380009467b48Spatrick Out << ' ';
380109467b48Spatrick } else
380209467b48Spatrick Out << "define ";
380309467b48Spatrick
380409467b48Spatrick Out << getLinkageNameWithSpace(F->getLinkage());
380509467b48Spatrick PrintDSOLocation(*F, Out);
380609467b48Spatrick PrintVisibility(F->getVisibility(), Out);
380709467b48Spatrick PrintDLLStorageClass(F->getDLLStorageClass(), Out);
380809467b48Spatrick
380909467b48Spatrick // Print the calling convention.
381009467b48Spatrick if (F->getCallingConv() != CallingConv::C) {
381109467b48Spatrick PrintCallingConv(F->getCallingConv(), Out);
381209467b48Spatrick Out << " ";
381309467b48Spatrick }
381409467b48Spatrick
381509467b48Spatrick FunctionType *FT = F->getFunctionType();
3816*d415bd75Srobert if (Attrs.hasRetAttrs())
381709467b48Spatrick Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
381809467b48Spatrick TypePrinter.print(F->getReturnType(), Out);
3819*d415bd75Srobert AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
382009467b48Spatrick Out << ' ';
3821*d415bd75Srobert WriteAsOperandInternal(Out, F, WriterCtx);
382209467b48Spatrick Out << '(';
382309467b48Spatrick
382409467b48Spatrick // Loop over the arguments, printing them...
382509467b48Spatrick if (F->isDeclaration() && !IsForDebug) {
382609467b48Spatrick // We're only interested in the type here - don't print argument names.
382709467b48Spatrick for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
382809467b48Spatrick // Insert commas as we go... the first arg doesn't get a comma
382909467b48Spatrick if (I)
383009467b48Spatrick Out << ", ";
383109467b48Spatrick // Output type...
383209467b48Spatrick TypePrinter.print(FT->getParamType(I), Out);
383309467b48Spatrick
3834*d415bd75Srobert AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
383509467b48Spatrick if (ArgAttrs.hasAttributes()) {
383609467b48Spatrick Out << ' ';
383709467b48Spatrick writeAttributeSet(ArgAttrs);
383809467b48Spatrick }
383909467b48Spatrick }
384009467b48Spatrick } else {
384109467b48Spatrick // The arguments are meaningful here, print them in detail.
384209467b48Spatrick for (const Argument &Arg : F->args()) {
384309467b48Spatrick // Insert commas as we go... the first arg doesn't get a comma
384409467b48Spatrick if (Arg.getArgNo() != 0)
384509467b48Spatrick Out << ", ";
3846*d415bd75Srobert printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
384709467b48Spatrick }
384809467b48Spatrick }
384909467b48Spatrick
385009467b48Spatrick // Finish printing arguments...
385109467b48Spatrick if (FT->isVarArg()) {
385209467b48Spatrick if (FT->getNumParams()) Out << ", ";
385309467b48Spatrick Out << "..."; // Output varargs portion of signature!
385409467b48Spatrick }
385509467b48Spatrick Out << ')';
385609467b48Spatrick StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
385709467b48Spatrick if (!UA.empty())
385809467b48Spatrick Out << ' ' << UA;
385909467b48Spatrick // We print the function address space if it is non-zero or if we are writing
386009467b48Spatrick // a module with a non-zero program address space or if there is no valid
386109467b48Spatrick // Module* so that the file can be parsed without the datalayout string.
386209467b48Spatrick const Module *Mod = F->getParent();
386309467b48Spatrick if (F->getAddressSpace() != 0 || !Mod ||
386409467b48Spatrick Mod->getDataLayout().getProgramAddressSpace() != 0)
386509467b48Spatrick Out << " addrspace(" << F->getAddressSpace() << ")";
3866*d415bd75Srobert if (Attrs.hasFnAttrs())
3867*d415bd75Srobert Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
386809467b48Spatrick if (F->hasSection()) {
386909467b48Spatrick Out << " section \"";
387009467b48Spatrick printEscapedString(F->getSection(), Out);
387109467b48Spatrick Out << '"';
387209467b48Spatrick }
387309467b48Spatrick if (F->hasPartition()) {
387409467b48Spatrick Out << " partition \"";
387509467b48Spatrick printEscapedString(F->getPartition(), Out);
387609467b48Spatrick Out << '"';
387709467b48Spatrick }
387809467b48Spatrick maybePrintComdat(Out, *F);
3879*d415bd75Srobert if (MaybeAlign A = F->getAlign())
3880*d415bd75Srobert Out << " align " << A->value();
388109467b48Spatrick if (F->hasGC())
388209467b48Spatrick Out << " gc \"" << F->getGC() << '"';
388309467b48Spatrick if (F->hasPrefixData()) {
388409467b48Spatrick Out << " prefix ";
388509467b48Spatrick writeOperand(F->getPrefixData(), true);
388609467b48Spatrick }
388709467b48Spatrick if (F->hasPrologueData()) {
388809467b48Spatrick Out << " prologue ";
388909467b48Spatrick writeOperand(F->getPrologueData(), true);
389009467b48Spatrick }
389109467b48Spatrick if (F->hasPersonalityFn()) {
389209467b48Spatrick Out << " personality ";
389309467b48Spatrick writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
389409467b48Spatrick }
389509467b48Spatrick
389609467b48Spatrick if (F->isDeclaration()) {
389709467b48Spatrick Out << '\n';
389809467b48Spatrick } else {
389909467b48Spatrick SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
390009467b48Spatrick F->getAllMetadata(MDs);
390109467b48Spatrick printMetadataAttachments(MDs, " ");
390209467b48Spatrick
390309467b48Spatrick Out << " {";
390409467b48Spatrick // Output all of the function's basic blocks.
390509467b48Spatrick for (const BasicBlock &BB : *F)
390609467b48Spatrick printBasicBlock(&BB);
390709467b48Spatrick
390809467b48Spatrick // Output the function's use-lists.
390909467b48Spatrick printUseLists(F);
391009467b48Spatrick
391109467b48Spatrick Out << "}\n";
391209467b48Spatrick }
391309467b48Spatrick
391409467b48Spatrick Machine.purgeFunction();
391509467b48Spatrick }
391609467b48Spatrick
391709467b48Spatrick /// printArgument - This member is called for every argument that is passed into
391809467b48Spatrick /// the function. Simply print it out
printArgument(const Argument * Arg,AttributeSet Attrs)391909467b48Spatrick void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
392009467b48Spatrick // Output type...
392109467b48Spatrick TypePrinter.print(Arg->getType(), Out);
392209467b48Spatrick
392309467b48Spatrick // Output parameter attributes list
392409467b48Spatrick if (Attrs.hasAttributes()) {
392509467b48Spatrick Out << ' ';
392609467b48Spatrick writeAttributeSet(Attrs);
392709467b48Spatrick }
392809467b48Spatrick
392909467b48Spatrick // Output name, if available...
393009467b48Spatrick if (Arg->hasName()) {
393109467b48Spatrick Out << ' ';
393209467b48Spatrick PrintLLVMName(Out, Arg);
393309467b48Spatrick } else {
393409467b48Spatrick int Slot = Machine.getLocalSlot(Arg);
393509467b48Spatrick assert(Slot != -1 && "expect argument in function here");
393609467b48Spatrick Out << " %" << Slot;
393709467b48Spatrick }
393809467b48Spatrick }
393909467b48Spatrick
394009467b48Spatrick /// printBasicBlock - This member is called for each basic block in a method.
printBasicBlock(const BasicBlock * BB)394109467b48Spatrick void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
394273471bf0Spatrick bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
394309467b48Spatrick if (BB->hasName()) { // Print out the label if it exists...
394409467b48Spatrick Out << "\n";
394509467b48Spatrick PrintLLVMName(Out, BB->getName(), LabelPrefix);
394609467b48Spatrick Out << ':';
394709467b48Spatrick } else if (!IsEntryBlock) {
394809467b48Spatrick Out << "\n";
394909467b48Spatrick int Slot = Machine.getLocalSlot(BB);
395009467b48Spatrick if (Slot != -1)
395109467b48Spatrick Out << Slot << ":";
395209467b48Spatrick else
395309467b48Spatrick Out << "<badref>:";
395409467b48Spatrick }
395509467b48Spatrick
395609467b48Spatrick if (!IsEntryBlock) {
395709467b48Spatrick // Output predecessors for the block.
395809467b48Spatrick Out.PadToColumn(50);
395909467b48Spatrick Out << ";";
396009467b48Spatrick const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
396109467b48Spatrick
396209467b48Spatrick if (PI == PE) {
396309467b48Spatrick Out << " No predecessors!";
396409467b48Spatrick } else {
396509467b48Spatrick Out << " preds = ";
396609467b48Spatrick writeOperand(*PI, false);
396709467b48Spatrick for (++PI; PI != PE; ++PI) {
396809467b48Spatrick Out << ", ";
396909467b48Spatrick writeOperand(*PI, false);
397009467b48Spatrick }
397109467b48Spatrick }
397209467b48Spatrick }
397309467b48Spatrick
397409467b48Spatrick Out << "\n";
397509467b48Spatrick
397609467b48Spatrick if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
397709467b48Spatrick
397809467b48Spatrick // Output all of the instructions in the basic block...
397909467b48Spatrick for (const Instruction &I : *BB) {
398009467b48Spatrick printInstructionLine(I);
398109467b48Spatrick }
398209467b48Spatrick
398309467b48Spatrick if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
398409467b48Spatrick }
398509467b48Spatrick
398609467b48Spatrick /// printInstructionLine - Print an instruction and a newline character.
printInstructionLine(const Instruction & I)398709467b48Spatrick void AssemblyWriter::printInstructionLine(const Instruction &I) {
398809467b48Spatrick printInstruction(I);
398909467b48Spatrick Out << '\n';
399009467b48Spatrick }
399109467b48Spatrick
399209467b48Spatrick /// printGCRelocateComment - print comment after call to the gc.relocate
399309467b48Spatrick /// intrinsic indicating base and derived pointer names.
printGCRelocateComment(const GCRelocateInst & Relocate)399409467b48Spatrick void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
399509467b48Spatrick Out << " ; (";
399609467b48Spatrick writeOperand(Relocate.getBasePtr(), false);
399709467b48Spatrick Out << ", ";
399809467b48Spatrick writeOperand(Relocate.getDerivedPtr(), false);
399909467b48Spatrick Out << ")";
400009467b48Spatrick }
400109467b48Spatrick
400209467b48Spatrick /// printInfoComment - Print a little comment after the instruction indicating
400309467b48Spatrick /// which slot it occupies.
printInfoComment(const Value & V)400409467b48Spatrick void AssemblyWriter::printInfoComment(const Value &V) {
400509467b48Spatrick if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
400609467b48Spatrick printGCRelocateComment(*Relocate);
400709467b48Spatrick
400809467b48Spatrick if (AnnotationWriter)
400909467b48Spatrick AnnotationWriter->printInfoComment(V, Out);
401009467b48Spatrick }
401109467b48Spatrick
maybePrintCallAddrSpace(const Value * Operand,const Instruction * I,raw_ostream & Out)401209467b48Spatrick static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
401309467b48Spatrick raw_ostream &Out) {
401409467b48Spatrick // We print the address space of the call if it is non-zero.
4015*d415bd75Srobert if (Operand == nullptr) {
4016*d415bd75Srobert Out << " <cannot get addrspace!>";
4017*d415bd75Srobert return;
4018*d415bd75Srobert }
401909467b48Spatrick unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
402009467b48Spatrick bool PrintAddrSpace = CallAddrSpace != 0;
402109467b48Spatrick if (!PrintAddrSpace) {
402209467b48Spatrick const Module *Mod = getModuleFromVal(I);
402309467b48Spatrick // We also print it if it is zero but not equal to the program address space
402409467b48Spatrick // or if we can't find a valid Module* to make it possible to parse
402509467b48Spatrick // the resulting file even without a datalayout string.
402609467b48Spatrick if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
402709467b48Spatrick PrintAddrSpace = true;
402809467b48Spatrick }
402909467b48Spatrick if (PrintAddrSpace)
403009467b48Spatrick Out << " addrspace(" << CallAddrSpace << ")";
403109467b48Spatrick }
403209467b48Spatrick
403309467b48Spatrick // This member is called for each Instruction in a function..
printInstruction(const Instruction & I)403409467b48Spatrick void AssemblyWriter::printInstruction(const Instruction &I) {
403509467b48Spatrick if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
403609467b48Spatrick
403709467b48Spatrick // Print out indentation for an instruction.
403809467b48Spatrick Out << " ";
403909467b48Spatrick
404009467b48Spatrick // Print out name if it exists...
404109467b48Spatrick if (I.hasName()) {
404209467b48Spatrick PrintLLVMName(Out, &I);
404309467b48Spatrick Out << " = ";
404409467b48Spatrick } else if (!I.getType()->isVoidTy()) {
404509467b48Spatrick // Print out the def slot taken.
404609467b48Spatrick int SlotNum = Machine.getLocalSlot(&I);
404709467b48Spatrick if (SlotNum == -1)
404809467b48Spatrick Out << "<badref> = ";
404909467b48Spatrick else
405009467b48Spatrick Out << '%' << SlotNum << " = ";
405109467b48Spatrick }
405209467b48Spatrick
405309467b48Spatrick if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
405409467b48Spatrick if (CI->isMustTailCall())
405509467b48Spatrick Out << "musttail ";
405609467b48Spatrick else if (CI->isTailCall())
405709467b48Spatrick Out << "tail ";
405809467b48Spatrick else if (CI->isNoTailCall())
405909467b48Spatrick Out << "notail ";
406009467b48Spatrick }
406109467b48Spatrick
406209467b48Spatrick // Print out the opcode...
406309467b48Spatrick Out << I.getOpcodeName();
406409467b48Spatrick
406509467b48Spatrick // If this is an atomic load or store, print out the atomic marker.
406609467b48Spatrick if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
406709467b48Spatrick (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
406809467b48Spatrick Out << " atomic";
406909467b48Spatrick
407009467b48Spatrick if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
407109467b48Spatrick Out << " weak";
407209467b48Spatrick
407309467b48Spatrick // If this is a volatile operation, print out the volatile marker.
407409467b48Spatrick if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
407509467b48Spatrick (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
407609467b48Spatrick (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
407709467b48Spatrick (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
407809467b48Spatrick Out << " volatile";
407909467b48Spatrick
408009467b48Spatrick // Print out optimization information.
408109467b48Spatrick WriteOptimizationInfo(Out, &I);
408209467b48Spatrick
408309467b48Spatrick // Print out the compare instruction predicates
408409467b48Spatrick if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
408509467b48Spatrick Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
408609467b48Spatrick
408709467b48Spatrick // Print out the atomicrmw operation
408809467b48Spatrick if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
408909467b48Spatrick Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
409009467b48Spatrick
409109467b48Spatrick // Print out the type of the operands...
409209467b48Spatrick const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
409309467b48Spatrick
409409467b48Spatrick // Special case conditional branches to swizzle the condition out to the front
409509467b48Spatrick if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
409609467b48Spatrick const BranchInst &BI(cast<BranchInst>(I));
409709467b48Spatrick Out << ' ';
409809467b48Spatrick writeOperand(BI.getCondition(), true);
409909467b48Spatrick Out << ", ";
410009467b48Spatrick writeOperand(BI.getSuccessor(0), true);
410109467b48Spatrick Out << ", ";
410209467b48Spatrick writeOperand(BI.getSuccessor(1), true);
410309467b48Spatrick
410409467b48Spatrick } else if (isa<SwitchInst>(I)) {
410509467b48Spatrick const SwitchInst& SI(cast<SwitchInst>(I));
410609467b48Spatrick // Special case switch instruction to get formatting nice and correct.
410709467b48Spatrick Out << ' ';
410809467b48Spatrick writeOperand(SI.getCondition(), true);
410909467b48Spatrick Out << ", ";
411009467b48Spatrick writeOperand(SI.getDefaultDest(), true);
411109467b48Spatrick Out << " [";
411209467b48Spatrick for (auto Case : SI.cases()) {
411309467b48Spatrick Out << "\n ";
411409467b48Spatrick writeOperand(Case.getCaseValue(), true);
411509467b48Spatrick Out << ", ";
411609467b48Spatrick writeOperand(Case.getCaseSuccessor(), true);
411709467b48Spatrick }
411809467b48Spatrick Out << "\n ]";
411909467b48Spatrick } else if (isa<IndirectBrInst>(I)) {
412009467b48Spatrick // Special case indirectbr instruction to get formatting nice and correct.
412109467b48Spatrick Out << ' ';
412209467b48Spatrick writeOperand(Operand, true);
412309467b48Spatrick Out << ", [";
412409467b48Spatrick
412509467b48Spatrick for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
412609467b48Spatrick if (i != 1)
412709467b48Spatrick Out << ", ";
412809467b48Spatrick writeOperand(I.getOperand(i), true);
412909467b48Spatrick }
413009467b48Spatrick Out << ']';
413109467b48Spatrick } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
413209467b48Spatrick Out << ' ';
413309467b48Spatrick TypePrinter.print(I.getType(), Out);
413409467b48Spatrick Out << ' ';
413509467b48Spatrick
413609467b48Spatrick for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
413709467b48Spatrick if (op) Out << ", ";
413809467b48Spatrick Out << "[ ";
413909467b48Spatrick writeOperand(PN->getIncomingValue(op), false); Out << ", ";
414009467b48Spatrick writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
414109467b48Spatrick }
414209467b48Spatrick } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
414309467b48Spatrick Out << ' ';
414409467b48Spatrick writeOperand(I.getOperand(0), true);
414573471bf0Spatrick for (unsigned i : EVI->indices())
414673471bf0Spatrick Out << ", " << i;
414709467b48Spatrick } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
414809467b48Spatrick Out << ' ';
414909467b48Spatrick writeOperand(I.getOperand(0), true); Out << ", ";
415009467b48Spatrick writeOperand(I.getOperand(1), true);
415173471bf0Spatrick for (unsigned i : IVI->indices())
415273471bf0Spatrick Out << ", " << i;
415309467b48Spatrick } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
415409467b48Spatrick Out << ' ';
415509467b48Spatrick TypePrinter.print(I.getType(), Out);
415609467b48Spatrick if (LPI->isCleanup() || LPI->getNumClauses() != 0)
415709467b48Spatrick Out << '\n';
415809467b48Spatrick
415909467b48Spatrick if (LPI->isCleanup())
416009467b48Spatrick Out << " cleanup";
416109467b48Spatrick
416209467b48Spatrick for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
416309467b48Spatrick if (i != 0 || LPI->isCleanup()) Out << "\n";
416409467b48Spatrick if (LPI->isCatch(i))
416509467b48Spatrick Out << " catch ";
416609467b48Spatrick else
416709467b48Spatrick Out << " filter ";
416809467b48Spatrick
416909467b48Spatrick writeOperand(LPI->getClause(i), true);
417009467b48Spatrick }
417109467b48Spatrick } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
417209467b48Spatrick Out << " within ";
417309467b48Spatrick writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
417409467b48Spatrick Out << " [";
417509467b48Spatrick unsigned Op = 0;
417609467b48Spatrick for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
417709467b48Spatrick if (Op > 0)
417809467b48Spatrick Out << ", ";
417909467b48Spatrick writeOperand(PadBB, /*PrintType=*/true);
418009467b48Spatrick ++Op;
418109467b48Spatrick }
418209467b48Spatrick Out << "] unwind ";
418309467b48Spatrick if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
418409467b48Spatrick writeOperand(UnwindDest, /*PrintType=*/true);
418509467b48Spatrick else
418609467b48Spatrick Out << "to caller";
418709467b48Spatrick } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
418809467b48Spatrick Out << " within ";
418909467b48Spatrick writeOperand(FPI->getParentPad(), /*PrintType=*/false);
419009467b48Spatrick Out << " [";
4191*d415bd75Srobert for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
419209467b48Spatrick if (Op > 0)
419309467b48Spatrick Out << ", ";
419409467b48Spatrick writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
419509467b48Spatrick }
419609467b48Spatrick Out << ']';
419709467b48Spatrick } else if (isa<ReturnInst>(I) && !Operand) {
419809467b48Spatrick Out << " void";
419909467b48Spatrick } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
420009467b48Spatrick Out << " from ";
420109467b48Spatrick writeOperand(CRI->getOperand(0), /*PrintType=*/false);
420209467b48Spatrick
420309467b48Spatrick Out << " to ";
420409467b48Spatrick writeOperand(CRI->getOperand(1), /*PrintType=*/true);
420509467b48Spatrick } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
420609467b48Spatrick Out << " from ";
420709467b48Spatrick writeOperand(CRI->getOperand(0), /*PrintType=*/false);
420809467b48Spatrick
420909467b48Spatrick Out << " unwind ";
421009467b48Spatrick if (CRI->hasUnwindDest())
421109467b48Spatrick writeOperand(CRI->getOperand(1), /*PrintType=*/true);
421209467b48Spatrick else
421309467b48Spatrick Out << "to caller";
421409467b48Spatrick } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
421509467b48Spatrick // Print the calling convention being used.
421609467b48Spatrick if (CI->getCallingConv() != CallingConv::C) {
421709467b48Spatrick Out << " ";
421809467b48Spatrick PrintCallingConv(CI->getCallingConv(), Out);
421909467b48Spatrick }
422009467b48Spatrick
4221097a140dSpatrick Operand = CI->getCalledOperand();
422209467b48Spatrick FunctionType *FTy = CI->getFunctionType();
422309467b48Spatrick Type *RetTy = FTy->getReturnType();
422409467b48Spatrick const AttributeList &PAL = CI->getAttributes();
422509467b48Spatrick
4226*d415bd75Srobert if (PAL.hasRetAttrs())
422709467b48Spatrick Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
422809467b48Spatrick
422909467b48Spatrick // Only print addrspace(N) if necessary:
423009467b48Spatrick maybePrintCallAddrSpace(Operand, &I, Out);
423109467b48Spatrick
423209467b48Spatrick // If possible, print out the short form of the call instruction. We can
423309467b48Spatrick // only do this if the first argument is a pointer to a nonvararg function,
423409467b48Spatrick // and if the return type is not a pointer to a function.
423509467b48Spatrick Out << ' ';
423609467b48Spatrick TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
423709467b48Spatrick Out << ' ';
423809467b48Spatrick writeOperand(Operand, false);
423909467b48Spatrick Out << '(';
4240*d415bd75Srobert for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
424109467b48Spatrick if (op > 0)
424209467b48Spatrick Out << ", ";
4243*d415bd75Srobert writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
424409467b48Spatrick }
424509467b48Spatrick
424609467b48Spatrick // Emit an ellipsis if this is a musttail call in a vararg function. This
424709467b48Spatrick // is only to aid readability, musttail calls forward varargs by default.
424809467b48Spatrick if (CI->isMustTailCall() && CI->getParent() &&
424909467b48Spatrick CI->getParent()->getParent() &&
4250*d415bd75Srobert CI->getParent()->getParent()->isVarArg()) {
4251*d415bd75Srobert if (CI->arg_size() > 0)
4252*d415bd75Srobert Out << ", ";
4253*d415bd75Srobert Out << "...";
4254*d415bd75Srobert }
425509467b48Spatrick
425609467b48Spatrick Out << ')';
4257*d415bd75Srobert if (PAL.hasFnAttrs())
4258*d415bd75Srobert Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
425909467b48Spatrick
426009467b48Spatrick writeOperandBundles(CI);
426109467b48Spatrick } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4262097a140dSpatrick Operand = II->getCalledOperand();
426309467b48Spatrick FunctionType *FTy = II->getFunctionType();
426409467b48Spatrick Type *RetTy = FTy->getReturnType();
426509467b48Spatrick const AttributeList &PAL = II->getAttributes();
426609467b48Spatrick
426709467b48Spatrick // Print the calling convention being used.
426809467b48Spatrick if (II->getCallingConv() != CallingConv::C) {
426909467b48Spatrick Out << " ";
427009467b48Spatrick PrintCallingConv(II->getCallingConv(), Out);
427109467b48Spatrick }
427209467b48Spatrick
4273*d415bd75Srobert if (PAL.hasRetAttrs())
427409467b48Spatrick Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
427509467b48Spatrick
427609467b48Spatrick // Only print addrspace(N) if necessary:
427709467b48Spatrick maybePrintCallAddrSpace(Operand, &I, Out);
427809467b48Spatrick
427909467b48Spatrick // If possible, print out the short form of the invoke instruction. We can
428009467b48Spatrick // only do this if the first argument is a pointer to a nonvararg function,
428109467b48Spatrick // and if the return type is not a pointer to a function.
428209467b48Spatrick //
428309467b48Spatrick Out << ' ';
428409467b48Spatrick TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
428509467b48Spatrick Out << ' ';
428609467b48Spatrick writeOperand(Operand, false);
428709467b48Spatrick Out << '(';
4288*d415bd75Srobert for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
428909467b48Spatrick if (op)
429009467b48Spatrick Out << ", ";
4291*d415bd75Srobert writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
429209467b48Spatrick }
429309467b48Spatrick
429409467b48Spatrick Out << ')';
4295*d415bd75Srobert if (PAL.hasFnAttrs())
4296*d415bd75Srobert Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
429709467b48Spatrick
429809467b48Spatrick writeOperandBundles(II);
429909467b48Spatrick
430009467b48Spatrick Out << "\n to ";
430109467b48Spatrick writeOperand(II->getNormalDest(), true);
430209467b48Spatrick Out << " unwind ";
430309467b48Spatrick writeOperand(II->getUnwindDest(), true);
430409467b48Spatrick } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4305097a140dSpatrick Operand = CBI->getCalledOperand();
430609467b48Spatrick FunctionType *FTy = CBI->getFunctionType();
430709467b48Spatrick Type *RetTy = FTy->getReturnType();
430809467b48Spatrick const AttributeList &PAL = CBI->getAttributes();
430909467b48Spatrick
431009467b48Spatrick // Print the calling convention being used.
431109467b48Spatrick if (CBI->getCallingConv() != CallingConv::C) {
431209467b48Spatrick Out << " ";
431309467b48Spatrick PrintCallingConv(CBI->getCallingConv(), Out);
431409467b48Spatrick }
431509467b48Spatrick
4316*d415bd75Srobert if (PAL.hasRetAttrs())
431709467b48Spatrick Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
431809467b48Spatrick
431909467b48Spatrick // If possible, print out the short form of the callbr instruction. We can
432009467b48Spatrick // only do this if the first argument is a pointer to a nonvararg function,
432109467b48Spatrick // and if the return type is not a pointer to a function.
432209467b48Spatrick //
432309467b48Spatrick Out << ' ';
432409467b48Spatrick TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
432509467b48Spatrick Out << ' ';
432609467b48Spatrick writeOperand(Operand, false);
432709467b48Spatrick Out << '(';
4328*d415bd75Srobert for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
432909467b48Spatrick if (op)
433009467b48Spatrick Out << ", ";
4331*d415bd75Srobert writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
433209467b48Spatrick }
433309467b48Spatrick
433409467b48Spatrick Out << ')';
4335*d415bd75Srobert if (PAL.hasFnAttrs())
4336*d415bd75Srobert Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
433709467b48Spatrick
433809467b48Spatrick writeOperandBundles(CBI);
433909467b48Spatrick
434009467b48Spatrick Out << "\n to ";
434109467b48Spatrick writeOperand(CBI->getDefaultDest(), true);
434209467b48Spatrick Out << " [";
434309467b48Spatrick for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
434409467b48Spatrick if (i != 0)
434509467b48Spatrick Out << ", ";
434609467b48Spatrick writeOperand(CBI->getIndirectDest(i), true);
434709467b48Spatrick }
434809467b48Spatrick Out << ']';
434909467b48Spatrick } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
435009467b48Spatrick Out << ' ';
435109467b48Spatrick if (AI->isUsedWithInAlloca())
435209467b48Spatrick Out << "inalloca ";
435309467b48Spatrick if (AI->isSwiftError())
435409467b48Spatrick Out << "swifterror ";
435509467b48Spatrick TypePrinter.print(AI->getAllocatedType(), Out);
435609467b48Spatrick
435709467b48Spatrick // Explicitly write the array size if the code is broken, if it's an array
435809467b48Spatrick // allocation, or if the type is not canonical for scalar allocations. The
435909467b48Spatrick // latter case prevents the type from mutating when round-tripping through
436009467b48Spatrick // assembly.
436109467b48Spatrick if (!AI->getArraySize() || AI->isArrayAllocation() ||
436209467b48Spatrick !AI->getArraySize()->getType()->isIntegerTy(32)) {
436309467b48Spatrick Out << ", ";
436409467b48Spatrick writeOperand(AI->getArraySize(), true);
436509467b48Spatrick }
4366*d415bd75Srobert if (MaybeAlign A = AI->getAlign()) {
4367*d415bd75Srobert Out << ", align " << A->value();
436809467b48Spatrick }
436909467b48Spatrick
4370*d415bd75Srobert unsigned AddrSpace = AI->getAddressSpace();
437109467b48Spatrick if (AddrSpace != 0) {
437209467b48Spatrick Out << ", addrspace(" << AddrSpace << ')';
437309467b48Spatrick }
437409467b48Spatrick } else if (isa<CastInst>(I)) {
437509467b48Spatrick if (Operand) {
437609467b48Spatrick Out << ' ';
437709467b48Spatrick writeOperand(Operand, true); // Work with broken code
437809467b48Spatrick }
437909467b48Spatrick Out << " to ";
438009467b48Spatrick TypePrinter.print(I.getType(), Out);
438109467b48Spatrick } else if (isa<VAArgInst>(I)) {
438209467b48Spatrick if (Operand) {
438309467b48Spatrick Out << ' ';
438409467b48Spatrick writeOperand(Operand, true); // Work with broken code
438509467b48Spatrick }
438609467b48Spatrick Out << ", ";
438709467b48Spatrick TypePrinter.print(I.getType(), Out);
438809467b48Spatrick } else if (Operand) { // Print the normal way.
438909467b48Spatrick if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
439009467b48Spatrick Out << ' ';
439109467b48Spatrick TypePrinter.print(GEP->getSourceElementType(), Out);
439209467b48Spatrick Out << ',';
439309467b48Spatrick } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
439409467b48Spatrick Out << ' ';
439509467b48Spatrick TypePrinter.print(LI->getType(), Out);
439609467b48Spatrick Out << ',';
439709467b48Spatrick }
439809467b48Spatrick
439909467b48Spatrick // PrintAllTypes - Instructions who have operands of all the same type
440009467b48Spatrick // omit the type from all but the first operand. If the instruction has
440109467b48Spatrick // different type operands (for example br), then they are all printed.
440209467b48Spatrick bool PrintAllTypes = false;
440309467b48Spatrick Type *TheType = Operand->getType();
440409467b48Spatrick
4405*d415bd75Srobert // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4406*d415bd75Srobert // types.
4407*d415bd75Srobert if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4408*d415bd75Srobert isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
4409*d415bd75Srobert isa<AtomicRMWInst>(I)) {
441009467b48Spatrick PrintAllTypes = true;
441109467b48Spatrick } else {
441209467b48Spatrick for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
441309467b48Spatrick Operand = I.getOperand(i);
441409467b48Spatrick // note that Operand shouldn't be null, but the test helps make dump()
441509467b48Spatrick // more tolerant of malformed IR
441609467b48Spatrick if (Operand && Operand->getType() != TheType) {
441709467b48Spatrick PrintAllTypes = true; // We have differing types! Print them all!
441809467b48Spatrick break;
441909467b48Spatrick }
442009467b48Spatrick }
442109467b48Spatrick }
442209467b48Spatrick
442309467b48Spatrick if (!PrintAllTypes) {
442409467b48Spatrick Out << ' ';
442509467b48Spatrick TypePrinter.print(TheType, Out);
442609467b48Spatrick }
442709467b48Spatrick
442809467b48Spatrick Out << ' ';
442909467b48Spatrick for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
443009467b48Spatrick if (i) Out << ", ";
443109467b48Spatrick writeOperand(I.getOperand(i), PrintAllTypes);
443209467b48Spatrick }
443309467b48Spatrick }
443409467b48Spatrick
443509467b48Spatrick // Print atomic ordering/alignment for memory operations
443609467b48Spatrick if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
443709467b48Spatrick if (LI->isAtomic())
443809467b48Spatrick writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4439*d415bd75Srobert if (MaybeAlign A = LI->getAlign())
4440*d415bd75Srobert Out << ", align " << A->value();
444109467b48Spatrick } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
444209467b48Spatrick if (SI->isAtomic())
444309467b48Spatrick writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4444*d415bd75Srobert if (MaybeAlign A = SI->getAlign())
4445*d415bd75Srobert Out << ", align " << A->value();
444609467b48Spatrick } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
444709467b48Spatrick writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
444809467b48Spatrick CXI->getFailureOrdering(), CXI->getSyncScopeID());
444973471bf0Spatrick Out << ", align " << CXI->getAlign().value();
445009467b48Spatrick } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
445109467b48Spatrick writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
445209467b48Spatrick RMWI->getSyncScopeID());
445373471bf0Spatrick Out << ", align " << RMWI->getAlign().value();
445409467b48Spatrick } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
445509467b48Spatrick writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4456097a140dSpatrick } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4457097a140dSpatrick PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
445809467b48Spatrick }
445909467b48Spatrick
446009467b48Spatrick // Print Metadata info.
446109467b48Spatrick SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
446209467b48Spatrick I.getAllMetadata(InstMD);
446309467b48Spatrick printMetadataAttachments(InstMD, ", ");
446409467b48Spatrick
446509467b48Spatrick // Print a nice comment.
446609467b48Spatrick printInfoComment(I);
446709467b48Spatrick }
446809467b48Spatrick
printMetadataAttachments(const SmallVectorImpl<std::pair<unsigned,MDNode * >> & MDs,StringRef Separator)446909467b48Spatrick void AssemblyWriter::printMetadataAttachments(
447009467b48Spatrick const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
447109467b48Spatrick StringRef Separator) {
447209467b48Spatrick if (MDs.empty())
447309467b48Spatrick return;
447409467b48Spatrick
447509467b48Spatrick if (MDNames.empty())
447609467b48Spatrick MDs[0].second->getContext().getMDKindNames(MDNames);
447709467b48Spatrick
4478*d415bd75Srobert auto WriterCtx = getContext();
447909467b48Spatrick for (const auto &I : MDs) {
448009467b48Spatrick unsigned Kind = I.first;
448109467b48Spatrick Out << Separator;
448209467b48Spatrick if (Kind < MDNames.size()) {
448309467b48Spatrick Out << "!";
448409467b48Spatrick printMetadataIdentifier(MDNames[Kind], Out);
448509467b48Spatrick } else
448609467b48Spatrick Out << "!<unknown kind #" << Kind << ">";
448709467b48Spatrick Out << ' ';
4488*d415bd75Srobert WriteAsOperandInternal(Out, I.second, WriterCtx);
448909467b48Spatrick }
449009467b48Spatrick }
449109467b48Spatrick
writeMDNode(unsigned Slot,const MDNode * Node)449209467b48Spatrick void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
449309467b48Spatrick Out << '!' << Slot << " = ";
449409467b48Spatrick printMDNodeBody(Node);
449509467b48Spatrick Out << "\n";
449609467b48Spatrick }
449709467b48Spatrick
writeAllMDNodes()449809467b48Spatrick void AssemblyWriter::writeAllMDNodes() {
449909467b48Spatrick SmallVector<const MDNode *, 16> Nodes;
450009467b48Spatrick Nodes.resize(Machine.mdn_size());
450173471bf0Spatrick for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
450273471bf0Spatrick Nodes[I.second] = cast<MDNode>(I.first);
450309467b48Spatrick
450409467b48Spatrick for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
450509467b48Spatrick writeMDNode(i, Nodes[i]);
450609467b48Spatrick }
450709467b48Spatrick }
450809467b48Spatrick
printMDNodeBody(const MDNode * Node)450909467b48Spatrick void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4510*d415bd75Srobert auto WriterCtx = getContext();
4511*d415bd75Srobert WriteMDNodeBodyInternal(Out, Node, WriterCtx);
451209467b48Spatrick }
451309467b48Spatrick
writeAttribute(const Attribute & Attr,bool InAttrGroup)451409467b48Spatrick void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
451509467b48Spatrick if (!Attr.isTypeAttribute()) {
451609467b48Spatrick Out << Attr.getAsString(InAttrGroup);
451709467b48Spatrick return;
451809467b48Spatrick }
451909467b48Spatrick
452073471bf0Spatrick Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
452109467b48Spatrick if (Type *Ty = Attr.getValueAsType()) {
452209467b48Spatrick Out << '(';
452309467b48Spatrick TypePrinter.print(Ty, Out);
452409467b48Spatrick Out << ')';
452509467b48Spatrick }
452609467b48Spatrick }
452709467b48Spatrick
writeAttributeSet(const AttributeSet & AttrSet,bool InAttrGroup)452809467b48Spatrick void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
452909467b48Spatrick bool InAttrGroup) {
453009467b48Spatrick bool FirstAttr = true;
453109467b48Spatrick for (const auto &Attr : AttrSet) {
453209467b48Spatrick if (!FirstAttr)
453309467b48Spatrick Out << ' ';
453409467b48Spatrick writeAttribute(Attr, InAttrGroup);
453509467b48Spatrick FirstAttr = false;
453609467b48Spatrick }
453709467b48Spatrick }
453809467b48Spatrick
writeAllAttributeGroups()453909467b48Spatrick void AssemblyWriter::writeAllAttributeGroups() {
454009467b48Spatrick std::vector<std::pair<AttributeSet, unsigned>> asVec;
454109467b48Spatrick asVec.resize(Machine.as_size());
454209467b48Spatrick
454373471bf0Spatrick for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
454473471bf0Spatrick asVec[I.second] = I;
454509467b48Spatrick
454609467b48Spatrick for (const auto &I : asVec)
454709467b48Spatrick Out << "attributes #" << I.second << " = { "
454809467b48Spatrick << I.first.getAsString(true) << " }\n";
454909467b48Spatrick }
455009467b48Spatrick
printUseListOrder(const Value * V,const std::vector<unsigned> & Shuffle)455173471bf0Spatrick void AssemblyWriter::printUseListOrder(const Value *V,
455273471bf0Spatrick const std::vector<unsigned> &Shuffle) {
455309467b48Spatrick bool IsInFunction = Machine.getFunction();
455409467b48Spatrick if (IsInFunction)
455509467b48Spatrick Out << " ";
455609467b48Spatrick
455709467b48Spatrick Out << "uselistorder";
455873471bf0Spatrick if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
455909467b48Spatrick Out << "_bb ";
456009467b48Spatrick writeOperand(BB->getParent(), false);
456109467b48Spatrick Out << ", ";
456209467b48Spatrick writeOperand(BB, false);
456309467b48Spatrick } else {
456409467b48Spatrick Out << " ";
456573471bf0Spatrick writeOperand(V, true);
456609467b48Spatrick }
456709467b48Spatrick Out << ", { ";
456809467b48Spatrick
456973471bf0Spatrick assert(Shuffle.size() >= 2 && "Shuffle too small");
457073471bf0Spatrick Out << Shuffle[0];
457173471bf0Spatrick for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
457273471bf0Spatrick Out << ", " << Shuffle[I];
457309467b48Spatrick Out << " }\n";
457409467b48Spatrick }
457509467b48Spatrick
printUseLists(const Function * F)457609467b48Spatrick void AssemblyWriter::printUseLists(const Function *F) {
457773471bf0Spatrick auto It = UseListOrders.find(F);
457873471bf0Spatrick if (It == UseListOrders.end())
457909467b48Spatrick return;
458009467b48Spatrick
458109467b48Spatrick Out << "\n; uselistorder directives\n";
458273471bf0Spatrick for (const auto &Pair : It->second)
458373471bf0Spatrick printUseListOrder(Pair.first, Pair.second);
458409467b48Spatrick }
458509467b48Spatrick
458609467b48Spatrick //===----------------------------------------------------------------------===//
458709467b48Spatrick // External Interface declarations
458809467b48Spatrick //===----------------------------------------------------------------------===//
458909467b48Spatrick
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const459009467b48Spatrick void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
459109467b48Spatrick bool ShouldPreserveUseListOrder,
459209467b48Spatrick bool IsForDebug) const {
459309467b48Spatrick SlotTracker SlotTable(this->getParent());
459409467b48Spatrick formatted_raw_ostream OS(ROS);
459509467b48Spatrick AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
459609467b48Spatrick IsForDebug,
459709467b48Spatrick ShouldPreserveUseListOrder);
459809467b48Spatrick W.printFunction(this);
459909467b48Spatrick }
460009467b48Spatrick
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const4601097a140dSpatrick void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4602097a140dSpatrick bool ShouldPreserveUseListOrder,
4603097a140dSpatrick bool IsForDebug) const {
460473471bf0Spatrick SlotTracker SlotTable(this->getParent());
4605097a140dSpatrick formatted_raw_ostream OS(ROS);
4606097a140dSpatrick AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
4607097a140dSpatrick IsForDebug,
4608097a140dSpatrick ShouldPreserveUseListOrder);
4609097a140dSpatrick W.printBasicBlock(this);
4610097a140dSpatrick }
4611097a140dSpatrick
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW,bool ShouldPreserveUseListOrder,bool IsForDebug) const461209467b48Spatrick void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
461309467b48Spatrick bool ShouldPreserveUseListOrder, bool IsForDebug) const {
461409467b48Spatrick SlotTracker SlotTable(this);
461509467b48Spatrick formatted_raw_ostream OS(ROS);
461609467b48Spatrick AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
461709467b48Spatrick ShouldPreserveUseListOrder);
461809467b48Spatrick W.printModule(this);
461909467b48Spatrick }
462009467b48Spatrick
print(raw_ostream & ROS,bool IsForDebug) const462109467b48Spatrick void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
462209467b48Spatrick SlotTracker SlotTable(getParent());
462309467b48Spatrick formatted_raw_ostream OS(ROS);
462409467b48Spatrick AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
462509467b48Spatrick W.printNamedMDNode(this);
462609467b48Spatrick }
462709467b48Spatrick
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const462809467b48Spatrick void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
462909467b48Spatrick bool IsForDebug) const {
4630*d415bd75Srobert std::optional<SlotTracker> LocalST;
463109467b48Spatrick SlotTracker *SlotTable;
463209467b48Spatrick if (auto *ST = MST.getMachine())
463309467b48Spatrick SlotTable = ST;
463409467b48Spatrick else {
463509467b48Spatrick LocalST.emplace(getParent());
463609467b48Spatrick SlotTable = &*LocalST;
463709467b48Spatrick }
463809467b48Spatrick
463909467b48Spatrick formatted_raw_ostream OS(ROS);
464009467b48Spatrick AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
464109467b48Spatrick W.printNamedMDNode(this);
464209467b48Spatrick }
464309467b48Spatrick
print(raw_ostream & ROS,bool) const464409467b48Spatrick void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
464509467b48Spatrick PrintLLVMName(ROS, getName(), ComdatPrefix);
464609467b48Spatrick ROS << " = comdat ";
464709467b48Spatrick
464809467b48Spatrick switch (getSelectionKind()) {
464909467b48Spatrick case Comdat::Any:
465009467b48Spatrick ROS << "any";
465109467b48Spatrick break;
465209467b48Spatrick case Comdat::ExactMatch:
465309467b48Spatrick ROS << "exactmatch";
465409467b48Spatrick break;
465509467b48Spatrick case Comdat::Largest:
465609467b48Spatrick ROS << "largest";
465709467b48Spatrick break;
465873471bf0Spatrick case Comdat::NoDeduplicate:
465973471bf0Spatrick ROS << "nodeduplicate";
466009467b48Spatrick break;
466109467b48Spatrick case Comdat::SameSize:
466209467b48Spatrick ROS << "samesize";
466309467b48Spatrick break;
466409467b48Spatrick }
466509467b48Spatrick
466609467b48Spatrick ROS << '\n';
466709467b48Spatrick }
466809467b48Spatrick
print(raw_ostream & OS,bool,bool NoDetails) const466909467b48Spatrick void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
467009467b48Spatrick TypePrinting TP;
467109467b48Spatrick TP.print(const_cast<Type*>(this), OS);
467209467b48Spatrick
467309467b48Spatrick if (NoDetails)
467409467b48Spatrick return;
467509467b48Spatrick
467609467b48Spatrick // If the type is a named struct type, print the body as well.
467709467b48Spatrick if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
467809467b48Spatrick if (!STy->isLiteral()) {
467909467b48Spatrick OS << " = type ";
468009467b48Spatrick TP.printStructBody(STy, OS);
468109467b48Spatrick }
468209467b48Spatrick }
468309467b48Spatrick
isReferencingMDNode(const Instruction & I)468409467b48Spatrick static bool isReferencingMDNode(const Instruction &I) {
468509467b48Spatrick if (const auto *CI = dyn_cast<CallInst>(&I))
468609467b48Spatrick if (Function *F = CI->getCalledFunction())
468709467b48Spatrick if (F->isIntrinsic())
468809467b48Spatrick for (auto &Op : I.operands())
468909467b48Spatrick if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
469009467b48Spatrick if (isa<MDNode>(V->getMetadata()))
469109467b48Spatrick return true;
469209467b48Spatrick return false;
469309467b48Spatrick }
469409467b48Spatrick
print(raw_ostream & ROS,bool IsForDebug) const469509467b48Spatrick void Value::print(raw_ostream &ROS, bool IsForDebug) const {
469609467b48Spatrick bool ShouldInitializeAllMetadata = false;
469709467b48Spatrick if (auto *I = dyn_cast<Instruction>(this))
469809467b48Spatrick ShouldInitializeAllMetadata = isReferencingMDNode(*I);
469909467b48Spatrick else if (isa<Function>(this) || isa<MetadataAsValue>(this))
470009467b48Spatrick ShouldInitializeAllMetadata = true;
470109467b48Spatrick
470209467b48Spatrick ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
470309467b48Spatrick print(ROS, MST, IsForDebug);
470409467b48Spatrick }
470509467b48Spatrick
print(raw_ostream & ROS,ModuleSlotTracker & MST,bool IsForDebug) const470609467b48Spatrick void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
470709467b48Spatrick bool IsForDebug) const {
470809467b48Spatrick formatted_raw_ostream OS(ROS);
470909467b48Spatrick SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
471009467b48Spatrick SlotTracker &SlotTable =
471109467b48Spatrick MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
471209467b48Spatrick auto incorporateFunction = [&](const Function *F) {
471309467b48Spatrick if (F)
471409467b48Spatrick MST.incorporateFunction(*F);
471509467b48Spatrick };
471609467b48Spatrick
471709467b48Spatrick if (const Instruction *I = dyn_cast<Instruction>(this)) {
471809467b48Spatrick incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
471909467b48Spatrick AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
472009467b48Spatrick W.printInstruction(*I);
472109467b48Spatrick } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
472209467b48Spatrick incorporateFunction(BB->getParent());
472309467b48Spatrick AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
472409467b48Spatrick W.printBasicBlock(BB);
472509467b48Spatrick } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
472609467b48Spatrick AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
472709467b48Spatrick if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
472809467b48Spatrick W.printGlobal(V);
472909467b48Spatrick else if (const Function *F = dyn_cast<Function>(GV))
473009467b48Spatrick W.printFunction(F);
4731*d415bd75Srobert else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
4732*d415bd75Srobert W.printAlias(A);
4733*d415bd75Srobert else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
4734*d415bd75Srobert W.printIFunc(I);
473509467b48Spatrick else
4736*d415bd75Srobert llvm_unreachable("Unknown GlobalValue to print out!");
473709467b48Spatrick } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
473809467b48Spatrick V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
473909467b48Spatrick } else if (const Constant *C = dyn_cast<Constant>(this)) {
474009467b48Spatrick TypePrinting TypePrinter;
474109467b48Spatrick TypePrinter.print(C->getType(), OS);
474209467b48Spatrick OS << ' ';
4743*d415bd75Srobert AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
4744*d415bd75Srobert WriteConstantInternal(OS, C, WriterCtx);
474509467b48Spatrick } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
474609467b48Spatrick this->printAsOperand(OS, /* PrintType */ true, MST);
474709467b48Spatrick } else {
474809467b48Spatrick llvm_unreachable("Unknown value to print out!");
474909467b48Spatrick }
475009467b48Spatrick }
475109467b48Spatrick
475209467b48Spatrick /// Print without a type, skipping the TypePrinting object.
475309467b48Spatrick ///
475409467b48Spatrick /// \return \c true iff printing was successful.
printWithoutType(const Value & V,raw_ostream & O,SlotTracker * Machine,const Module * M)475509467b48Spatrick static bool printWithoutType(const Value &V, raw_ostream &O,
475609467b48Spatrick SlotTracker *Machine, const Module *M) {
475709467b48Spatrick if (V.hasName() || isa<GlobalValue>(V) ||
475809467b48Spatrick (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4759*d415bd75Srobert AsmWriterContext WriterCtx(nullptr, Machine, M);
4760*d415bd75Srobert WriteAsOperandInternal(O, &V, WriterCtx);
476109467b48Spatrick return true;
476209467b48Spatrick }
476309467b48Spatrick return false;
476409467b48Spatrick }
476509467b48Spatrick
printAsOperandImpl(const Value & V,raw_ostream & O,bool PrintType,ModuleSlotTracker & MST)476609467b48Spatrick static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
476709467b48Spatrick ModuleSlotTracker &MST) {
476809467b48Spatrick TypePrinting TypePrinter(MST.getModule());
476909467b48Spatrick if (PrintType) {
477009467b48Spatrick TypePrinter.print(V.getType(), O);
477109467b48Spatrick O << ' ';
477209467b48Spatrick }
477309467b48Spatrick
4774*d415bd75Srobert AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
4775*d415bd75Srobert WriteAsOperandInternal(O, &V, WriterCtx);
477609467b48Spatrick }
477709467b48Spatrick
printAsOperand(raw_ostream & O,bool PrintType,const Module * M) const477809467b48Spatrick void Value::printAsOperand(raw_ostream &O, bool PrintType,
477909467b48Spatrick const Module *M) const {
478009467b48Spatrick if (!M)
478109467b48Spatrick M = getModuleFromVal(this);
478209467b48Spatrick
478309467b48Spatrick if (!PrintType)
478409467b48Spatrick if (printWithoutType(*this, O, nullptr, M))
478509467b48Spatrick return;
478609467b48Spatrick
478709467b48Spatrick SlotTracker Machine(
478809467b48Spatrick M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
478909467b48Spatrick ModuleSlotTracker MST(Machine, M);
479009467b48Spatrick printAsOperandImpl(*this, O, PrintType, MST);
479109467b48Spatrick }
479209467b48Spatrick
printAsOperand(raw_ostream & O,bool PrintType,ModuleSlotTracker & MST) const479309467b48Spatrick void Value::printAsOperand(raw_ostream &O, bool PrintType,
479409467b48Spatrick ModuleSlotTracker &MST) const {
479509467b48Spatrick if (!PrintType)
479609467b48Spatrick if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
479709467b48Spatrick return;
479809467b48Spatrick
479909467b48Spatrick printAsOperandImpl(*this, O, PrintType, MST);
480009467b48Spatrick }
480109467b48Spatrick
4802*d415bd75Srobert /// Recursive version of printMetadataImpl.
printMetadataImplRec(raw_ostream & ROS,const Metadata & MD,AsmWriterContext & WriterCtx)4803*d415bd75Srobert static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
4804*d415bd75Srobert AsmWriterContext &WriterCtx) {
4805*d415bd75Srobert formatted_raw_ostream OS(ROS);
4806*d415bd75Srobert WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
4807*d415bd75Srobert
4808*d415bd75Srobert auto *N = dyn_cast<MDNode>(&MD);
4809*d415bd75Srobert if (!N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4810*d415bd75Srobert return;
4811*d415bd75Srobert
4812*d415bd75Srobert OS << " = ";
4813*d415bd75Srobert WriteMDNodeBodyInternal(OS, N, WriterCtx);
4814*d415bd75Srobert }
4815*d415bd75Srobert
4816*d415bd75Srobert namespace {
4817*d415bd75Srobert struct MDTreeAsmWriterContext : public AsmWriterContext {
4818*d415bd75Srobert unsigned Level;
4819*d415bd75Srobert // {Level, Printed string}
4820*d415bd75Srobert using EntryTy = std::pair<unsigned, std::string>;
4821*d415bd75Srobert SmallVector<EntryTy, 4> Buffer;
4822*d415bd75Srobert
4823*d415bd75Srobert // Used to break the cycle in case there is any.
4824*d415bd75Srobert SmallPtrSet<const Metadata *, 4> Visited;
4825*d415bd75Srobert
4826*d415bd75Srobert raw_ostream &MainOS;
4827*d415bd75Srobert
MDTreeAsmWriterContext__anon4f18fdef0d11::MDTreeAsmWriterContext4828*d415bd75Srobert MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
4829*d415bd75Srobert raw_ostream &OS, const Metadata *InitMD)
4830*d415bd75Srobert : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
4831*d415bd75Srobert
onWriteMetadataAsOperand__anon4f18fdef0d11::MDTreeAsmWriterContext4832*d415bd75Srobert void onWriteMetadataAsOperand(const Metadata *MD) override {
4833*d415bd75Srobert if (!Visited.insert(MD).second)
4834*d415bd75Srobert return;
4835*d415bd75Srobert
4836*d415bd75Srobert std::string Str;
4837*d415bd75Srobert raw_string_ostream SS(Str);
4838*d415bd75Srobert ++Level;
4839*d415bd75Srobert // A placeholder entry to memorize the correct
4840*d415bd75Srobert // position in buffer.
4841*d415bd75Srobert Buffer.emplace_back(std::make_pair(Level, ""));
4842*d415bd75Srobert unsigned InsertIdx = Buffer.size() - 1;
4843*d415bd75Srobert
4844*d415bd75Srobert printMetadataImplRec(SS, *MD, *this);
4845*d415bd75Srobert Buffer[InsertIdx].second = std::move(SS.str());
4846*d415bd75Srobert --Level;
4847*d415bd75Srobert }
4848*d415bd75Srobert
~MDTreeAsmWriterContext__anon4f18fdef0d11::MDTreeAsmWriterContext4849*d415bd75Srobert ~MDTreeAsmWriterContext() {
4850*d415bd75Srobert for (const auto &Entry : Buffer) {
4851*d415bd75Srobert MainOS << "\n";
4852*d415bd75Srobert unsigned NumIndent = Entry.first * 2U;
4853*d415bd75Srobert MainOS.indent(NumIndent) << Entry.second;
4854*d415bd75Srobert }
4855*d415bd75Srobert }
4856*d415bd75Srobert };
4857*d415bd75Srobert } // end anonymous namespace
4858*d415bd75Srobert
printMetadataImpl(raw_ostream & ROS,const Metadata & MD,ModuleSlotTracker & MST,const Module * M,bool OnlyAsOperand,bool PrintAsTree=false)485909467b48Spatrick static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
486009467b48Spatrick ModuleSlotTracker &MST, const Module *M,
4861*d415bd75Srobert bool OnlyAsOperand, bool PrintAsTree = false) {
486209467b48Spatrick formatted_raw_ostream OS(ROS);
486309467b48Spatrick
486409467b48Spatrick TypePrinting TypePrinter(M);
486509467b48Spatrick
4866*d415bd75Srobert std::unique_ptr<AsmWriterContext> WriterCtx;
4867*d415bd75Srobert if (PrintAsTree && !OnlyAsOperand)
4868*d415bd75Srobert WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
4869*d415bd75Srobert &TypePrinter, MST.getMachine(), M, OS, &MD);
4870*d415bd75Srobert else
4871*d415bd75Srobert WriterCtx =
4872*d415bd75Srobert std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
4873*d415bd75Srobert
4874*d415bd75Srobert WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
487509467b48Spatrick
487609467b48Spatrick auto *N = dyn_cast<MDNode>(&MD);
487773471bf0Spatrick if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
487809467b48Spatrick return;
487909467b48Spatrick
488009467b48Spatrick OS << " = ";
4881*d415bd75Srobert WriteMDNodeBodyInternal(OS, N, *WriterCtx);
488209467b48Spatrick }
488309467b48Spatrick
printAsOperand(raw_ostream & OS,const Module * M) const488409467b48Spatrick void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
488509467b48Spatrick ModuleSlotTracker MST(M, isa<MDNode>(this));
488609467b48Spatrick printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
488709467b48Spatrick }
488809467b48Spatrick
printAsOperand(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M) const488909467b48Spatrick void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
489009467b48Spatrick const Module *M) const {
489109467b48Spatrick printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
489209467b48Spatrick }
489309467b48Spatrick
print(raw_ostream & OS,const Module * M,bool) const489409467b48Spatrick void Metadata::print(raw_ostream &OS, const Module *M,
489509467b48Spatrick bool /*IsForDebug*/) const {
489609467b48Spatrick ModuleSlotTracker MST(M, isa<MDNode>(this));
489709467b48Spatrick printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
489809467b48Spatrick }
489909467b48Spatrick
print(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M,bool) const490009467b48Spatrick void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
490109467b48Spatrick const Module *M, bool /*IsForDebug*/) const {
490209467b48Spatrick printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
490309467b48Spatrick }
490409467b48Spatrick
printTree(raw_ostream & OS,const Module * M) const4905*d415bd75Srobert void MDNode::printTree(raw_ostream &OS, const Module *M) const {
4906*d415bd75Srobert ModuleSlotTracker MST(M, true);
4907*d415bd75Srobert printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
4908*d415bd75Srobert /*PrintAsTree=*/true);
4909*d415bd75Srobert }
4910*d415bd75Srobert
printTree(raw_ostream & OS,ModuleSlotTracker & MST,const Module * M) const4911*d415bd75Srobert void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
4912*d415bd75Srobert const Module *M) const {
4913*d415bd75Srobert printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
4914*d415bd75Srobert /*PrintAsTree=*/true);
4915*d415bd75Srobert }
4916*d415bd75Srobert
print(raw_ostream & ROS,bool IsForDebug) const491709467b48Spatrick void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
491809467b48Spatrick SlotTracker SlotTable(this);
491909467b48Spatrick formatted_raw_ostream OS(ROS);
492009467b48Spatrick AssemblyWriter W(OS, SlotTable, this, IsForDebug);
492109467b48Spatrick W.printModuleSummaryIndex();
492209467b48Spatrick }
492309467b48Spatrick
collectMDNodes(MachineMDNodeListType & L,unsigned LB,unsigned UB) const492473471bf0Spatrick void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,
492573471bf0Spatrick unsigned UB) const {
492673471bf0Spatrick SlotTracker *ST = MachineStorage.get();
492773471bf0Spatrick if (!ST)
492873471bf0Spatrick return;
492973471bf0Spatrick
493073471bf0Spatrick for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
493173471bf0Spatrick if (I.second >= LB && I.second < UB)
493273471bf0Spatrick L.push_back(std::make_pair(I.second, I.first));
493373471bf0Spatrick }
493473471bf0Spatrick
493509467b48Spatrick #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
493609467b48Spatrick // Value::dump - allow easy printing of Values from the debugger.
493709467b48Spatrick LLVM_DUMP_METHOD
dump() const493809467b48Spatrick void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
493909467b48Spatrick
494009467b48Spatrick // Type::dump - allow easy printing of Types from the debugger.
494109467b48Spatrick LLVM_DUMP_METHOD
dump() const494209467b48Spatrick void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
494309467b48Spatrick
494409467b48Spatrick // Module::dump() - Allow printing of Modules from the debugger.
494509467b48Spatrick LLVM_DUMP_METHOD
dump() const494609467b48Spatrick void Module::dump() const {
494709467b48Spatrick print(dbgs(), nullptr,
494809467b48Spatrick /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
494909467b48Spatrick }
495009467b48Spatrick
495109467b48Spatrick // Allow printing of Comdats from the debugger.
495209467b48Spatrick LLVM_DUMP_METHOD
dump() const495309467b48Spatrick void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
495409467b48Spatrick
495509467b48Spatrick // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
495609467b48Spatrick LLVM_DUMP_METHOD
dump() const495709467b48Spatrick void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
495809467b48Spatrick
495909467b48Spatrick LLVM_DUMP_METHOD
dump() const496009467b48Spatrick void Metadata::dump() const { dump(nullptr); }
496109467b48Spatrick
496209467b48Spatrick LLVM_DUMP_METHOD
dump(const Module * M) const496309467b48Spatrick void Metadata::dump(const Module *M) const {
496409467b48Spatrick print(dbgs(), M, /*IsForDebug=*/true);
496509467b48Spatrick dbgs() << '\n';
496609467b48Spatrick }
496709467b48Spatrick
4968*d415bd75Srobert LLVM_DUMP_METHOD
dumpTree() const4969*d415bd75Srobert void MDNode::dumpTree() const { dumpTree(nullptr); }
4970*d415bd75Srobert
4971*d415bd75Srobert LLVM_DUMP_METHOD
dumpTree(const Module * M) const4972*d415bd75Srobert void MDNode::dumpTree(const Module *M) const {
4973*d415bd75Srobert printTree(dbgs(), M);
4974*d415bd75Srobert dbgs() << '\n';
4975*d415bd75Srobert }
4976*d415bd75Srobert
497709467b48Spatrick // Allow printing of ModuleSummaryIndex from the debugger.
497809467b48Spatrick LLVM_DUMP_METHOD
dump() const497909467b48Spatrick void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
498009467b48Spatrick #endif
4981