xref: /freebsd/contrib/llvm-project/llvm/lib/IR/AsmWriter.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
10b57cec5SDimitry Andric //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This library implements `print` family of functions in classes like
100b57cec5SDimitry Andric // Module, Function, Value, etc. In-memory representation of those classes is
110b57cec5SDimitry Andric // converted to IR strings.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // Note that these routines must be extremely tolerant of various errors in the
140b57cec5SDimitry Andric // LLVM code, because it can be used for debugging transformations.
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
190b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
200b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
210b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
220b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
24349cc55cSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
250b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
260b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
270b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
280b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
290b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
300b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
310b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
320b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
330b57cec5SDimitry Andric #include "llvm/IR/AssemblyAnnotationWriter.h"
340b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
350b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
360b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
370b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
380b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
390b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
400b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
410b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
42*5f757f3fSDimitry Andric #include "llvm/IR/DebugProgramInstruction.h"
430b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
440b57cec5SDimitry Andric #include "llvm/IR/Function.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
460b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
470b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
480b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
490b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
500b57cec5SDimitry Andric #include "llvm/IR/IRPrintingPasses.h"
510b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
520b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
530b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
540b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
55fe6060f1SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
560b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
570b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
580b57cec5SDimitry Andric #include "llvm/IR/Module.h"
590b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
600b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
610b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
620b57cec5SDimitry Andric #include "llvm/IR/Type.h"
630b57cec5SDimitry Andric #include "llvm/IR/TypeFinder.h"
64bdd1243dSDimitry Andric #include "llvm/IR/TypedPointerType.h"
650b57cec5SDimitry Andric #include "llvm/IR/Use.h"
660b57cec5SDimitry Andric #include "llvm/IR/User.h"
670b57cec5SDimitry Andric #include "llvm/IR/Value.h"
680b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
690b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
700b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
710b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
720b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
730b57cec5SDimitry Andric #include "llvm/Support/Format.h"
740b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
75349cc55cSDimitry Andric #include "llvm/Support/SaveAndRestore.h"
760b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
770b57cec5SDimitry Andric #include <algorithm>
780b57cec5SDimitry Andric #include <cassert>
790b57cec5SDimitry Andric #include <cctype>
800b57cec5SDimitry Andric #include <cstddef>
810b57cec5SDimitry Andric #include <cstdint>
820b57cec5SDimitry Andric #include <iterator>
830b57cec5SDimitry Andric #include <memory>
84bdd1243dSDimitry Andric #include <optional>
850b57cec5SDimitry Andric #include <string>
860b57cec5SDimitry Andric #include <tuple>
870b57cec5SDimitry Andric #include <utility>
880b57cec5SDimitry Andric #include <vector>
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric using namespace llvm;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric // Make virtual table appear in this compilation unit.
930b57cec5SDimitry Andric AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
960b57cec5SDimitry Andric // Helper Functions
970b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
980b57cec5SDimitry Andric 
99fe6060f1SDimitry Andric using OrderMap = MapVector<const Value *, unsigned>;
1000b57cec5SDimitry Andric 
101fe6060f1SDimitry Andric using UseListOrderMap =
102fe6060f1SDimitry Andric     DenseMap<const Function *, MapVector<const Value *, std::vector<unsigned>>>;
1030b57cec5SDimitry Andric 
104e8d8bef9SDimitry Andric /// Look for a value that might be wrapped as metadata, e.g. a value in a
105e8d8bef9SDimitry Andric /// metadata operand. Returns the input value as-is if it is not wrapped.
106e8d8bef9SDimitry Andric static const Value *skipMetadataWrapper(const Value *V) {
107e8d8bef9SDimitry Andric   if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
108e8d8bef9SDimitry Andric     if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
109e8d8bef9SDimitry Andric       return VAM->getValue();
110e8d8bef9SDimitry Andric   return V;
111e8d8bef9SDimitry Andric }
112e8d8bef9SDimitry Andric 
1130b57cec5SDimitry Andric static void orderValue(const Value *V, OrderMap &OM) {
114fe6060f1SDimitry Andric   if (OM.lookup(V))
1150b57cec5SDimitry Andric     return;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   if (const Constant *C = dyn_cast<Constant>(V))
1180b57cec5SDimitry Andric     if (C->getNumOperands() && !isa<GlobalValue>(C))
1190b57cec5SDimitry Andric       for (const Value *Op : C->operands())
1200b57cec5SDimitry Andric         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
1210b57cec5SDimitry Andric           orderValue(Op, OM);
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // Note: we cannot cache this lookup above, since inserting into the map
1240b57cec5SDimitry Andric   // changes the map's size, and thus affects the other IDs.
125fe6060f1SDimitry Andric   unsigned ID = OM.size() + 1;
126fe6060f1SDimitry Andric   OM[V] = ID;
1270b57cec5SDimitry Andric }
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric static OrderMap orderModule(const Module *M) {
1300b57cec5SDimitry Andric   OrderMap OM;
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   for (const GlobalVariable &G : M->globals()) {
1330b57cec5SDimitry Andric     if (G.hasInitializer())
1340b57cec5SDimitry Andric       if (!isa<GlobalValue>(G.getInitializer()))
1350b57cec5SDimitry Andric         orderValue(G.getInitializer(), OM);
1360b57cec5SDimitry Andric     orderValue(&G, OM);
1370b57cec5SDimitry Andric   }
1380b57cec5SDimitry Andric   for (const GlobalAlias &A : M->aliases()) {
1390b57cec5SDimitry Andric     if (!isa<GlobalValue>(A.getAliasee()))
1400b57cec5SDimitry Andric       orderValue(A.getAliasee(), OM);
1410b57cec5SDimitry Andric     orderValue(&A, OM);
1420b57cec5SDimitry Andric   }
1430b57cec5SDimitry Andric   for (const GlobalIFunc &I : M->ifuncs()) {
1440b57cec5SDimitry Andric     if (!isa<GlobalValue>(I.getResolver()))
1450b57cec5SDimitry Andric       orderValue(I.getResolver(), OM);
1460b57cec5SDimitry Andric     orderValue(&I, OM);
1470b57cec5SDimitry Andric   }
1480b57cec5SDimitry Andric   for (const Function &F : *M) {
1490b57cec5SDimitry Andric     for (const Use &U : F.operands())
1500b57cec5SDimitry Andric       if (!isa<GlobalValue>(U.get()))
1510b57cec5SDimitry Andric         orderValue(U.get(), OM);
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric     orderValue(&F, OM);
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     if (F.isDeclaration())
1560b57cec5SDimitry Andric       continue;
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric     for (const Argument &A : F.args())
1590b57cec5SDimitry Andric       orderValue(&A, OM);
1600b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
1610b57cec5SDimitry Andric       orderValue(&BB, OM);
1620b57cec5SDimitry Andric       for (const Instruction &I : BB) {
163e8d8bef9SDimitry Andric         for (const Value *Op : I.operands()) {
164e8d8bef9SDimitry Andric           Op = skipMetadataWrapper(Op);
1650b57cec5SDimitry Andric           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
1660b57cec5SDimitry Andric               isa<InlineAsm>(*Op))
1670b57cec5SDimitry Andric             orderValue(Op, OM);
168e8d8bef9SDimitry Andric         }
1690b57cec5SDimitry Andric         orderValue(&I, OM);
1700b57cec5SDimitry Andric       }
1710b57cec5SDimitry Andric     }
1720b57cec5SDimitry Andric   }
1730b57cec5SDimitry Andric   return OM;
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
176fe6060f1SDimitry Andric static std::vector<unsigned>
177fe6060f1SDimitry Andric predictValueUseListOrder(const Value *V, unsigned ID, const OrderMap &OM) {
1780b57cec5SDimitry Andric   // Predict use-list order for this one.
1790b57cec5SDimitry Andric   using Entry = std::pair<const Use *, unsigned>;
1800b57cec5SDimitry Andric   SmallVector<Entry, 64> List;
1810b57cec5SDimitry Andric   for (const Use &U : V->uses())
1820b57cec5SDimitry Andric     // Check if this user will be serialized.
183fe6060f1SDimitry Andric     if (OM.lookup(U.getUser()))
1840b57cec5SDimitry Andric       List.push_back(std::make_pair(&U, List.size()));
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   if (List.size() < 2)
1870b57cec5SDimitry Andric     // We may have lost some users.
188fe6060f1SDimitry Andric     return {};
1890b57cec5SDimitry Andric 
190fe6060f1SDimitry Andric   // When referencing a value before its declaration, a temporary value is
191fe6060f1SDimitry Andric   // created, which will later be RAUWed with the actual value. This reverses
192fe6060f1SDimitry Andric   // the use list. This happens for all values apart from basic blocks.
193fe6060f1SDimitry Andric   bool GetsReversed = !isa<BasicBlock>(V);
1940b57cec5SDimitry Andric   if (auto *BA = dyn_cast<BlockAddress>(V))
195fe6060f1SDimitry Andric     ID = OM.lookup(BA->getBasicBlock());
1960b57cec5SDimitry Andric   llvm::sort(List, [&](const Entry &L, const Entry &R) {
1970b57cec5SDimitry Andric     const Use *LU = L.first;
1980b57cec5SDimitry Andric     const Use *RU = R.first;
1990b57cec5SDimitry Andric     if (LU == RU)
2000b57cec5SDimitry Andric       return false;
2010b57cec5SDimitry Andric 
202fe6060f1SDimitry Andric     auto LID = OM.lookup(LU->getUser());
203fe6060f1SDimitry Andric     auto RID = OM.lookup(RU->getUser());
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric     // If ID is 4, then expect: 7 6 5 1 2 3.
2060b57cec5SDimitry Andric     if (LID < RID) {
2070b57cec5SDimitry Andric       if (GetsReversed)
2080b57cec5SDimitry Andric         if (RID <= ID)
2090b57cec5SDimitry Andric           return true;
2100b57cec5SDimitry Andric       return false;
2110b57cec5SDimitry Andric     }
2120b57cec5SDimitry Andric     if (RID < LID) {
2130b57cec5SDimitry Andric       if (GetsReversed)
2140b57cec5SDimitry Andric         if (LID <= ID)
2150b57cec5SDimitry Andric           return false;
2160b57cec5SDimitry Andric       return true;
2170b57cec5SDimitry Andric     }
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric     // LID and RID are equal, so we have different operands of the same user.
2200b57cec5SDimitry Andric     // Assume operands are added in order for all instructions.
2210b57cec5SDimitry Andric     if (GetsReversed)
2220b57cec5SDimitry Andric       if (LID <= ID)
2230b57cec5SDimitry Andric         return LU->getOperandNo() < RU->getOperandNo();
2240b57cec5SDimitry Andric     return LU->getOperandNo() > RU->getOperandNo();
2250b57cec5SDimitry Andric   });
2260b57cec5SDimitry Andric 
22781ad6265SDimitry Andric   if (llvm::is_sorted(List, llvm::less_second()))
2280b57cec5SDimitry Andric     // Order is already correct.
229fe6060f1SDimitry Andric     return {};
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   // Store the shuffle.
232fe6060f1SDimitry Andric   std::vector<unsigned> Shuffle(List.size());
2330b57cec5SDimitry Andric   for (size_t I = 0, E = List.size(); I != E; ++I)
234fe6060f1SDimitry Andric     Shuffle[I] = List[I].second;
235fe6060f1SDimitry Andric   return Shuffle;
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric 
238fe6060f1SDimitry Andric static UseListOrderMap predictUseListOrder(const Module *M) {
2390b57cec5SDimitry Andric   OrderMap OM = orderModule(M);
240fe6060f1SDimitry Andric   UseListOrderMap ULOM;
241fe6060f1SDimitry Andric   for (const auto &Pair : OM) {
242fe6060f1SDimitry Andric     const Value *V = Pair.first;
243fe6060f1SDimitry Andric     if (V->use_empty() || std::next(V->use_begin()) == V->use_end())
2440b57cec5SDimitry Andric       continue;
2450b57cec5SDimitry Andric 
246fe6060f1SDimitry Andric     std::vector<unsigned> Shuffle =
247fe6060f1SDimitry Andric         predictValueUseListOrder(V, Pair.second, OM);
248fe6060f1SDimitry Andric     if (Shuffle.empty())
249fe6060f1SDimitry Andric       continue;
2500b57cec5SDimitry Andric 
251fe6060f1SDimitry Andric     const Function *F = nullptr;
252fe6060f1SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V))
253fe6060f1SDimitry Andric       F = I->getFunction();
254fe6060f1SDimitry Andric     if (auto *A = dyn_cast<Argument>(V))
255fe6060f1SDimitry Andric       F = A->getParent();
256fe6060f1SDimitry Andric     if (auto *BB = dyn_cast<BasicBlock>(V))
257fe6060f1SDimitry Andric       F = BB->getParent();
258fe6060f1SDimitry Andric     ULOM[F][V] = std::move(Shuffle);
259fe6060f1SDimitry Andric   }
260fe6060f1SDimitry Andric   return ULOM;
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric static const Module *getModuleFromVal(const Value *V) {
2640b57cec5SDimitry Andric   if (const Argument *MA = dyn_cast<Argument>(V))
2650b57cec5SDimitry Andric     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
2680b57cec5SDimitry Andric     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2710b57cec5SDimitry Andric     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
2720b57cec5SDimitry Andric     return M ? M->getParent() : nullptr;
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2760b57cec5SDimitry Andric     return GV->getParent();
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
2790b57cec5SDimitry Andric     for (const User *U : MAV->users())
2800b57cec5SDimitry Andric       if (isa<Instruction>(U))
2810b57cec5SDimitry Andric         if (const Module *M = getModuleFromVal(U))
2820b57cec5SDimitry Andric           return M;
2830b57cec5SDimitry Andric     return nullptr;
2840b57cec5SDimitry Andric   }
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   return nullptr;
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric 
289*5f757f3fSDimitry Andric static const Module *getModuleFromDPI(const DPMarker *Marker) {
290*5f757f3fSDimitry Andric   const Function *M =
291*5f757f3fSDimitry Andric       Marker->getParent() ? Marker->getParent()->getParent() : nullptr;
292*5f757f3fSDimitry Andric   return M ? M->getParent() : nullptr;
293*5f757f3fSDimitry Andric }
294*5f757f3fSDimitry Andric 
295*5f757f3fSDimitry Andric static const Module *getModuleFromDPI(const DPValue *DPV) {
296*5f757f3fSDimitry Andric   return getModuleFromDPI(DPV->getMarker());
297*5f757f3fSDimitry Andric }
298*5f757f3fSDimitry Andric 
2990b57cec5SDimitry Andric static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
3000b57cec5SDimitry Andric   switch (cc) {
3010b57cec5SDimitry Andric   default:                         Out << "cc" << cc; break;
3020b57cec5SDimitry Andric   case CallingConv::Fast:          Out << "fastcc"; break;
3030b57cec5SDimitry Andric   case CallingConv::Cold:          Out << "coldcc"; break;
3040b57cec5SDimitry Andric   case CallingConv::AnyReg:        Out << "anyregcc"; break;
3050b57cec5SDimitry Andric   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
3060b57cec5SDimitry Andric   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
3070b57cec5SDimitry Andric   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
3080b57cec5SDimitry Andric   case CallingConv::GHC:           Out << "ghccc"; break;
3098bcb0991SDimitry Andric   case CallingConv::Tail:          Out << "tailcc"; break;
310*5f757f3fSDimitry Andric   case CallingConv::GRAAL:         Out << "graalcc"; break;
311480093f4SDimitry Andric   case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
3120b57cec5SDimitry Andric   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
3130b57cec5SDimitry Andric   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
3140b57cec5SDimitry Andric   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
3150b57cec5SDimitry Andric   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
3160b57cec5SDimitry Andric   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
3170b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
3180b57cec5SDimitry Andric   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
3190b57cec5SDimitry Andric   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
3200b57cec5SDimitry Andric   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
3210b57cec5SDimitry Andric   case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
322480093f4SDimitry Andric   case CallingConv::AArch64_SVE_VectorCall:
323480093f4SDimitry Andric     Out << "aarch64_sve_vector_pcs";
324480093f4SDimitry Andric     break;
325bdd1243dSDimitry Andric   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0:
326bdd1243dSDimitry Andric     Out << "aarch64_sme_preservemost_from_x0";
327bdd1243dSDimitry Andric     break;
328bdd1243dSDimitry Andric   case CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2:
329bdd1243dSDimitry Andric     Out << "aarch64_sme_preservemost_from_x2";
330bdd1243dSDimitry Andric     break;
3310b57cec5SDimitry Andric   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
3320b57cec5SDimitry Andric   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
3330b57cec5SDimitry Andric   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
3340b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
3350b57cec5SDimitry Andric   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
3360b57cec5SDimitry Andric   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
3370b57cec5SDimitry Andric   case CallingConv::Win64:         Out << "win64cc"; break;
3380b57cec5SDimitry Andric   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
3390b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
3400b57cec5SDimitry Andric   case CallingConv::Swift:         Out << "swiftcc"; break;
341fe6060f1SDimitry Andric   case CallingConv::SwiftTail:     Out << "swifttailcc"; break;
3420b57cec5SDimitry Andric   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
34306c3fb27SDimitry Andric   case CallingConv::DUMMY_HHVM:
34406c3fb27SDimitry Andric     Out << "hhvmcc";
34506c3fb27SDimitry Andric     break;
34606c3fb27SDimitry Andric   case CallingConv::DUMMY_HHVM_C:
34706c3fb27SDimitry Andric     Out << "hhvm_ccc";
34806c3fb27SDimitry Andric     break;
3490b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
3500b57cec5SDimitry Andric   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
3510b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
3520b57cec5SDimitry Andric   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
3530b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
3540b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
3550b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
35606c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_Chain:
35706c3fb27SDimitry Andric     Out << "amdgpu_cs_chain";
35806c3fb27SDimitry Andric     break;
35906c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_ChainPreserve:
36006c3fb27SDimitry Andric     Out << "amdgpu_cs_chain_preserve";
36106c3fb27SDimitry Andric     break;
3620b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
363e8d8bef9SDimitry Andric   case CallingConv::AMDGPU_Gfx:    Out << "amdgpu_gfx"; break;
364*5f757f3fSDimitry Andric   case CallingConv::M68k_RTD:      Out << "m68k_rtdcc"; break;
3650b57cec5SDimitry Andric   }
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric enum PrefixType {
3690b57cec5SDimitry Andric   GlobalPrefix,
3700b57cec5SDimitry Andric   ComdatPrefix,
3710b57cec5SDimitry Andric   LabelPrefix,
3720b57cec5SDimitry Andric   LocalPrefix,
3730b57cec5SDimitry Andric   NoPrefix
3740b57cec5SDimitry Andric };
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
3770b57cec5SDimitry Andric   assert(!Name.empty() && "Cannot get empty name!");
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   // Scan the name to see if it needs quotes first.
3800b57cec5SDimitry Andric   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
3810b57cec5SDimitry Andric   if (!NeedsQuotes) {
3824824e7fdSDimitry Andric     for (unsigned char C : Name) {
3830b57cec5SDimitry Andric       // By making this unsigned, the value passed in to isalnum will always be
3840b57cec5SDimitry Andric       // in the range 0-255.  This is important when building with MSVC because
3850b57cec5SDimitry Andric       // its implementation will assert.  This situation can arise when dealing
3860b57cec5SDimitry Andric       // with UTF-8 multibyte characters.
3870b57cec5SDimitry Andric       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
3880b57cec5SDimitry Andric           C != '_') {
3890b57cec5SDimitry Andric         NeedsQuotes = true;
3900b57cec5SDimitry Andric         break;
3910b57cec5SDimitry Andric       }
3920b57cec5SDimitry Andric     }
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // If we didn't need any quotes, just write out the name in one blast.
3960b57cec5SDimitry Andric   if (!NeedsQuotes) {
3970b57cec5SDimitry Andric     OS << Name;
3980b57cec5SDimitry Andric     return;
3990b57cec5SDimitry Andric   }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   // Okay, we need quotes.  Output the quotes and escape any scary characters as
4020b57cec5SDimitry Andric   // needed.
4030b57cec5SDimitry Andric   OS << '"';
4040b57cec5SDimitry Andric   printEscapedString(Name, OS);
4050b57cec5SDimitry Andric   OS << '"';
4060b57cec5SDimitry Andric }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric /// Turn the specified name into an 'LLVM name', which is either prefixed with %
4090b57cec5SDimitry Andric /// (if the string only contains simple characters) or is surrounded with ""'s
4100b57cec5SDimitry Andric /// (if it has special chars in it). Print it out.
4110b57cec5SDimitry Andric static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
4120b57cec5SDimitry Andric   switch (Prefix) {
4130b57cec5SDimitry Andric   case NoPrefix:
4140b57cec5SDimitry Andric     break;
4150b57cec5SDimitry Andric   case GlobalPrefix:
4160b57cec5SDimitry Andric     OS << '@';
4170b57cec5SDimitry Andric     break;
4180b57cec5SDimitry Andric   case ComdatPrefix:
4190b57cec5SDimitry Andric     OS << '$';
4200b57cec5SDimitry Andric     break;
4210b57cec5SDimitry Andric   case LabelPrefix:
4220b57cec5SDimitry Andric     break;
4230b57cec5SDimitry Andric   case LocalPrefix:
4240b57cec5SDimitry Andric     OS << '%';
4250b57cec5SDimitry Andric     break;
4260b57cec5SDimitry Andric   }
4270b57cec5SDimitry Andric   printLLVMNameWithoutPrefix(OS, Name);
4280b57cec5SDimitry Andric }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric /// Turn the specified name into an 'LLVM name', which is either prefixed with %
4310b57cec5SDimitry Andric /// (if the string only contains simple characters) or is surrounded with ""'s
4320b57cec5SDimitry Andric /// (if it has special chars in it). Print it out.
4330b57cec5SDimitry Andric static void PrintLLVMName(raw_ostream &OS, const Value *V) {
4340b57cec5SDimitry Andric   PrintLLVMName(OS, V->getName(),
4350b57cec5SDimitry Andric                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
4360b57cec5SDimitry Andric }
4370b57cec5SDimitry Andric 
4385ffd83dbSDimitry Andric static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
4395ffd83dbSDimitry Andric   Out << ", <";
4405ffd83dbSDimitry Andric   if (isa<ScalableVectorType>(Ty))
4415ffd83dbSDimitry Andric     Out << "vscale x ";
4425ffd83dbSDimitry Andric   Out << Mask.size() << " x i32> ";
4435ffd83dbSDimitry Andric   bool FirstElt = true;
4445ffd83dbSDimitry Andric   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
4455ffd83dbSDimitry Andric     Out << "zeroinitializer";
44606c3fb27SDimitry Andric   } else if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
44706c3fb27SDimitry Andric     Out << "poison";
4485ffd83dbSDimitry Andric   } else {
4495ffd83dbSDimitry Andric     Out << "<";
4505ffd83dbSDimitry Andric     for (int Elt : Mask) {
4515ffd83dbSDimitry Andric       if (FirstElt)
4525ffd83dbSDimitry Andric         FirstElt = false;
4535ffd83dbSDimitry Andric       else
4545ffd83dbSDimitry Andric         Out << ", ";
4555ffd83dbSDimitry Andric       Out << "i32 ";
45606c3fb27SDimitry Andric       if (Elt == PoisonMaskElem)
45706c3fb27SDimitry Andric         Out << "poison";
4585ffd83dbSDimitry Andric       else
4595ffd83dbSDimitry Andric         Out << Elt;
4605ffd83dbSDimitry Andric     }
4615ffd83dbSDimitry Andric     Out << ">";
4625ffd83dbSDimitry Andric   }
4635ffd83dbSDimitry Andric }
4645ffd83dbSDimitry Andric 
4650b57cec5SDimitry Andric namespace {
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric class TypePrinting {
4680b57cec5SDimitry Andric public:
4690b57cec5SDimitry Andric   TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   TypePrinting(const TypePrinting &) = delete;
4720b57cec5SDimitry Andric   TypePrinting &operator=(const TypePrinting &) = delete;
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   /// The named types that are used by the current module.
4750b57cec5SDimitry Andric   TypeFinder &getNamedTypes();
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   /// The numbered types, number to type mapping.
4780b57cec5SDimitry Andric   std::vector<StructType *> &getNumberedTypes();
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   bool empty();
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   void print(Type *Ty, raw_ostream &OS);
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric   void printStructBody(StructType *Ty, raw_ostream &OS);
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric private:
4870b57cec5SDimitry Andric   void incorporateTypes();
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   /// A module to process lazily when needed. Set to nullptr as soon as used.
4900b57cec5SDimitry Andric   const Module *DeferredM;
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   TypeFinder NamedTypes;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   // The numbered types, along with their value.
4950b57cec5SDimitry Andric   DenseMap<StructType *, unsigned> Type2Number;
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   std::vector<StructType *> NumberedTypes;
4980b57cec5SDimitry Andric };
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric } // end anonymous namespace
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric TypeFinder &TypePrinting::getNamedTypes() {
5030b57cec5SDimitry Andric   incorporateTypes();
5040b57cec5SDimitry Andric   return NamedTypes;
5050b57cec5SDimitry Andric }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric std::vector<StructType *> &TypePrinting::getNumberedTypes() {
5080b57cec5SDimitry Andric   incorporateTypes();
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric   // We know all the numbers that each type is used and we know that it is a
5110b57cec5SDimitry Andric   // dense assignment. Convert the map to an index table, if it's not done
5120b57cec5SDimitry Andric   // already (judging from the sizes):
5130b57cec5SDimitry Andric   if (NumberedTypes.size() == Type2Number.size())
5140b57cec5SDimitry Andric     return NumberedTypes;
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   NumberedTypes.resize(Type2Number.size());
5170b57cec5SDimitry Andric   for (const auto &P : Type2Number) {
5180b57cec5SDimitry Andric     assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
5190b57cec5SDimitry Andric     assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
5200b57cec5SDimitry Andric     NumberedTypes[P.second] = P.first;
5210b57cec5SDimitry Andric   }
5220b57cec5SDimitry Andric   return NumberedTypes;
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric bool TypePrinting::empty() {
5260b57cec5SDimitry Andric   incorporateTypes();
5270b57cec5SDimitry Andric   return NamedTypes.empty() && Type2Number.empty();
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric void TypePrinting::incorporateTypes() {
5310b57cec5SDimitry Andric   if (!DeferredM)
5320b57cec5SDimitry Andric     return;
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   NamedTypes.run(*DeferredM, false);
5350b57cec5SDimitry Andric   DeferredM = nullptr;
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   // The list of struct types we got back includes all the struct types, split
5380b57cec5SDimitry Andric   // the unnamed ones out to a numbering and remove the anonymous structs.
5390b57cec5SDimitry Andric   unsigned NextNumber = 0;
5400b57cec5SDimitry Andric 
5410eae32dcSDimitry Andric   std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
5420eae32dcSDimitry Andric   for (StructType *STy : NamedTypes) {
5430b57cec5SDimitry Andric     // Ignore anonymous types.
5440b57cec5SDimitry Andric     if (STy->isLiteral())
5450b57cec5SDimitry Andric       continue;
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric     if (STy->getName().empty())
5480b57cec5SDimitry Andric       Type2Number[STy] = NextNumber++;
5490b57cec5SDimitry Andric     else
5500b57cec5SDimitry Andric       *NextToUse++ = STy;
5510b57cec5SDimitry Andric   }
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric   NamedTypes.erase(NextToUse, NamedTypes.end());
5540b57cec5SDimitry Andric }
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric /// Write the specified type to the specified raw_ostream, making use of type
5570b57cec5SDimitry Andric /// names or up references to shorten the type name where possible.
5580b57cec5SDimitry Andric void TypePrinting::print(Type *Ty, raw_ostream &OS) {
5590b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
5600b57cec5SDimitry Andric   case Type::VoidTyID:      OS << "void"; return;
5610b57cec5SDimitry Andric   case Type::HalfTyID:      OS << "half"; return;
5625ffd83dbSDimitry Andric   case Type::BFloatTyID:    OS << "bfloat"; return;
5630b57cec5SDimitry Andric   case Type::FloatTyID:     OS << "float"; return;
5640b57cec5SDimitry Andric   case Type::DoubleTyID:    OS << "double"; return;
5650b57cec5SDimitry Andric   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
5660b57cec5SDimitry Andric   case Type::FP128TyID:     OS << "fp128"; return;
5670b57cec5SDimitry Andric   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
5680b57cec5SDimitry Andric   case Type::LabelTyID:     OS << "label"; return;
5690b57cec5SDimitry Andric   case Type::MetadataTyID:  OS << "metadata"; return;
5700b57cec5SDimitry Andric   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
571e8d8bef9SDimitry Andric   case Type::X86_AMXTyID:   OS << "x86_amx"; return;
5720b57cec5SDimitry Andric   case Type::TokenTyID:     OS << "token"; return;
5730b57cec5SDimitry Andric   case Type::IntegerTyID:
5740b57cec5SDimitry Andric     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
5750b57cec5SDimitry Andric     return;
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   case Type::FunctionTyID: {
5780b57cec5SDimitry Andric     FunctionType *FTy = cast<FunctionType>(Ty);
5790b57cec5SDimitry Andric     print(FTy->getReturnType(), OS);
5800b57cec5SDimitry Andric     OS << " (";
581349cc55cSDimitry Andric     ListSeparator LS;
582349cc55cSDimitry Andric     for (Type *Ty : FTy->params()) {
583349cc55cSDimitry Andric       OS << LS;
584349cc55cSDimitry Andric       print(Ty, OS);
5850b57cec5SDimitry Andric     }
586349cc55cSDimitry Andric     if (FTy->isVarArg())
587349cc55cSDimitry Andric       OS << LS << "...";
5880b57cec5SDimitry Andric     OS << ')';
5890b57cec5SDimitry Andric     return;
5900b57cec5SDimitry Andric   }
5910b57cec5SDimitry Andric   case Type::StructTyID: {
5920b57cec5SDimitry Andric     StructType *STy = cast<StructType>(Ty);
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric     if (STy->isLiteral())
5950b57cec5SDimitry Andric       return printStructBody(STy, OS);
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     if (!STy->getName().empty())
5980b57cec5SDimitry Andric       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     incorporateTypes();
6010b57cec5SDimitry Andric     const auto I = Type2Number.find(STy);
6020b57cec5SDimitry Andric     if (I != Type2Number.end())
6030b57cec5SDimitry Andric       OS << '%' << I->second;
6040b57cec5SDimitry Andric     else  // Not enumerated, print the hex address.
6050b57cec5SDimitry Andric       OS << "%\"type " << STy << '\"';
6060b57cec5SDimitry Andric     return;
6070b57cec5SDimitry Andric   }
6080b57cec5SDimitry Andric   case Type::PointerTyID: {
6090b57cec5SDimitry Andric     PointerType *PTy = cast<PointerType>(Ty);
610fe6060f1SDimitry Andric     OS << "ptr";
611fe6060f1SDimitry Andric     if (unsigned AddressSpace = PTy->getAddressSpace())
612fe6060f1SDimitry Andric       OS << " addrspace(" << AddressSpace << ')';
613fe6060f1SDimitry Andric     return;
614fe6060f1SDimitry Andric   }
6150b57cec5SDimitry Andric   case Type::ArrayTyID: {
6160b57cec5SDimitry Andric     ArrayType *ATy = cast<ArrayType>(Ty);
6170b57cec5SDimitry Andric     OS << '[' << ATy->getNumElements() << " x ";
6180b57cec5SDimitry Andric     print(ATy->getElementType(), OS);
6190b57cec5SDimitry Andric     OS << ']';
6200b57cec5SDimitry Andric     return;
6210b57cec5SDimitry Andric   }
6225ffd83dbSDimitry Andric   case Type::FixedVectorTyID:
6235ffd83dbSDimitry Andric   case Type::ScalableVectorTyID: {
6240b57cec5SDimitry Andric     VectorType *PTy = cast<VectorType>(Ty);
6255ffd83dbSDimitry Andric     ElementCount EC = PTy->getElementCount();
6260b57cec5SDimitry Andric     OS << "<";
627e8d8bef9SDimitry Andric     if (EC.isScalable())
6280b57cec5SDimitry Andric       OS << "vscale x ";
629e8d8bef9SDimitry Andric     OS << EC.getKnownMinValue() << " x ";
6300b57cec5SDimitry Andric     print(PTy->getElementType(), OS);
6310b57cec5SDimitry Andric     OS << '>';
6320b57cec5SDimitry Andric     return;
6330b57cec5SDimitry Andric   }
634bdd1243dSDimitry Andric   case Type::TypedPointerTyID: {
635bdd1243dSDimitry Andric     TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
636bdd1243dSDimitry Andric     OS << "typedptr(" << *TPTy->getElementType() << ", "
637bdd1243dSDimitry Andric        << TPTy->getAddressSpace() << ")";
638bdd1243dSDimitry Andric     return;
639bdd1243dSDimitry Andric   }
640bdd1243dSDimitry Andric   case Type::TargetExtTyID:
641bdd1243dSDimitry Andric     TargetExtType *TETy = cast<TargetExtType>(Ty);
642bdd1243dSDimitry Andric     OS << "target(\"";
643bdd1243dSDimitry Andric     printEscapedString(Ty->getTargetExtName(), OS);
644bdd1243dSDimitry Andric     OS << "\"";
645bdd1243dSDimitry Andric     for (Type *Inner : TETy->type_params())
646bdd1243dSDimitry Andric       OS << ", " << *Inner;
647bdd1243dSDimitry Andric     for (unsigned IntParam : TETy->int_params())
648bdd1243dSDimitry Andric       OS << ", " << IntParam;
649bdd1243dSDimitry Andric     OS << ")";
65081ad6265SDimitry Andric     return;
6510b57cec5SDimitry Andric   }
6520b57cec5SDimitry Andric   llvm_unreachable("Invalid TypeID");
6530b57cec5SDimitry Andric }
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
6560b57cec5SDimitry Andric   if (STy->isOpaque()) {
6570b57cec5SDimitry Andric     OS << "opaque";
6580b57cec5SDimitry Andric     return;
6590b57cec5SDimitry Andric   }
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   if (STy->isPacked())
6620b57cec5SDimitry Andric     OS << '<';
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   if (STy->getNumElements() == 0) {
6650b57cec5SDimitry Andric     OS << "{}";
6660b57cec5SDimitry Andric   } else {
6670b57cec5SDimitry Andric     OS << "{ ";
668349cc55cSDimitry Andric     ListSeparator LS;
669349cc55cSDimitry Andric     for (Type *Ty : STy->elements()) {
670349cc55cSDimitry Andric       OS << LS;
671349cc55cSDimitry Andric       print(Ty, OS);
6720b57cec5SDimitry Andric     }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     OS << " }";
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric   if (STy->isPacked())
6770b57cec5SDimitry Andric     OS << '>';
6780b57cec5SDimitry Andric }
6790b57cec5SDimitry Andric 
68081ad6265SDimitry Andric AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
681fe6060f1SDimitry Andric 
6820b57cec5SDimitry Andric namespace llvm {
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6850b57cec5SDimitry Andric // SlotTracker Class: Enumerate slot numbers for unnamed values
6860b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6870b57cec5SDimitry Andric /// This class provides computation of slot numbers for LLVM Assembly writing.
6880b57cec5SDimitry Andric ///
689fe6060f1SDimitry Andric class SlotTracker : public AbstractSlotTrackerStorage {
6900b57cec5SDimitry Andric public:
6910b57cec5SDimitry Andric   /// ValueMap - A mapping of Values to slot numbers.
6920b57cec5SDimitry Andric   using ValueMap = DenseMap<const Value *, unsigned>;
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric private:
6950b57cec5SDimitry Andric   /// TheModule - The module for which we are holding slot numbers.
6960b57cec5SDimitry Andric   const Module* TheModule;
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   /// TheFunction - The function for which we are holding slot numbers.
6990b57cec5SDimitry Andric   const Function* TheFunction = nullptr;
7000b57cec5SDimitry Andric   bool FunctionProcessed = false;
7010b57cec5SDimitry Andric   bool ShouldInitializeAllMetadata;
7020b57cec5SDimitry Andric 
703fe6060f1SDimitry Andric   std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
704fe6060f1SDimitry Andric       ProcessModuleHookFn;
705fe6060f1SDimitry Andric   std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
706fe6060f1SDimitry Andric       ProcessFunctionHookFn;
707fe6060f1SDimitry Andric 
7080b57cec5SDimitry Andric   /// The summary index for which we are holding slot numbers.
7090b57cec5SDimitry Andric   const ModuleSummaryIndex *TheIndex = nullptr;
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   /// mMap - The slot map for the module level data.
7120b57cec5SDimitry Andric   ValueMap mMap;
7130b57cec5SDimitry Andric   unsigned mNext = 0;
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric   /// fMap - The slot map for the function level data.
7160b57cec5SDimitry Andric   ValueMap fMap;
7170b57cec5SDimitry Andric   unsigned fNext = 0;
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   /// mdnMap - Map for MDNodes.
7200b57cec5SDimitry Andric   DenseMap<const MDNode*, unsigned> mdnMap;
7210b57cec5SDimitry Andric   unsigned mdnNext = 0;
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   /// asMap - The slot map for attribute sets.
7240b57cec5SDimitry Andric   DenseMap<AttributeSet, unsigned> asMap;
7250b57cec5SDimitry Andric   unsigned asNext = 0;
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   /// ModulePathMap - The slot map for Module paths used in the summary index.
7280b57cec5SDimitry Andric   StringMap<unsigned> ModulePathMap;
7290b57cec5SDimitry Andric   unsigned ModulePathNext = 0;
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   /// GUIDMap - The slot map for GUIDs used in the summary index.
7320b57cec5SDimitry Andric   DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
7330b57cec5SDimitry Andric   unsigned GUIDNext = 0;
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   /// TypeIdMap - The slot map for type ids used in the summary index.
7360b57cec5SDimitry Andric   StringMap<unsigned> TypeIdMap;
7370b57cec5SDimitry Andric   unsigned TypeIdNext = 0;
7380b57cec5SDimitry Andric 
739*5f757f3fSDimitry Andric   /// TypeIdCompatibleVtableMap - The slot map for type compatible vtable ids
740*5f757f3fSDimitry Andric   /// used in the summary index.
741*5f757f3fSDimitry Andric   StringMap<unsigned> TypeIdCompatibleVtableMap;
742*5f757f3fSDimitry Andric   unsigned TypeIdCompatibleVtableNext = 0;
743*5f757f3fSDimitry Andric 
7440b57cec5SDimitry Andric public:
7450b57cec5SDimitry Andric   /// Construct from a module.
7460b57cec5SDimitry Andric   ///
7470b57cec5SDimitry Andric   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
7480b57cec5SDimitry Andric   /// functions, giving correct numbering for metadata referenced only from
7490b57cec5SDimitry Andric   /// within a function (even if no functions have been initialized).
7500b57cec5SDimitry Andric   explicit SlotTracker(const Module *M,
7510b57cec5SDimitry Andric                        bool ShouldInitializeAllMetadata = false);
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   /// Construct from a function, starting out in incorp state.
7540b57cec5SDimitry Andric   ///
7550b57cec5SDimitry Andric   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
7560b57cec5SDimitry Andric   /// functions, giving correct numbering for metadata referenced only from
7570b57cec5SDimitry Andric   /// within a function (even if no functions have been initialized).
7580b57cec5SDimitry Andric   explicit SlotTracker(const Function *F,
7590b57cec5SDimitry Andric                        bool ShouldInitializeAllMetadata = false);
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   /// Construct from a module summary index.
7620b57cec5SDimitry Andric   explicit SlotTracker(const ModuleSummaryIndex *Index);
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   SlotTracker(const SlotTracker &) = delete;
7650b57cec5SDimitry Andric   SlotTracker &operator=(const SlotTracker &) = delete;
7660b57cec5SDimitry Andric 
767fe6060f1SDimitry Andric   ~SlotTracker() = default;
768fe6060f1SDimitry Andric 
769fe6060f1SDimitry Andric   void setProcessHook(
770fe6060f1SDimitry Andric       std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
771fe6060f1SDimitry Andric   void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
772fe6060f1SDimitry Andric                                          const Function *, bool)>);
773fe6060f1SDimitry Andric 
774fe6060f1SDimitry Andric   unsigned getNextMetadataSlot() override { return mdnNext; }
775fe6060f1SDimitry Andric 
776fe6060f1SDimitry Andric   void createMetadataSlot(const MDNode *N) override;
777fe6060f1SDimitry Andric 
7780b57cec5SDimitry Andric   /// Return the slot number of the specified value in it's type
7790b57cec5SDimitry Andric   /// plane.  If something is not in the SlotTracker, return -1.
7800b57cec5SDimitry Andric   int getLocalSlot(const Value *V);
7810b57cec5SDimitry Andric   int getGlobalSlot(const GlobalValue *V);
782fe6060f1SDimitry Andric   int getMetadataSlot(const MDNode *N) override;
7830b57cec5SDimitry Andric   int getAttributeGroupSlot(AttributeSet AS);
7840b57cec5SDimitry Andric   int getModulePathSlot(StringRef Path);
7850b57cec5SDimitry Andric   int getGUIDSlot(GlobalValue::GUID GUID);
7860b57cec5SDimitry Andric   int getTypeIdSlot(StringRef Id);
787*5f757f3fSDimitry Andric   int getTypeIdCompatibleVtableSlot(StringRef Id);
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   /// If you'd like to deal with a function instead of just a module, use
7900b57cec5SDimitry Andric   /// this method to get its data into the SlotTracker.
7910b57cec5SDimitry Andric   void incorporateFunction(const Function *F) {
7920b57cec5SDimitry Andric     TheFunction = F;
7930b57cec5SDimitry Andric     FunctionProcessed = false;
7940b57cec5SDimitry Andric   }
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   const Function *getFunction() const { return TheFunction; }
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric   /// After calling incorporateFunction, use this method to remove the
7990b57cec5SDimitry Andric   /// most recently incorporated function from the SlotTracker. This
8000b57cec5SDimitry Andric   /// will reset the state of the machine back to just the module contents.
8010b57cec5SDimitry Andric   void purgeFunction();
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   /// MDNode map iterators.
8040b57cec5SDimitry Andric   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   mdn_iterator mdn_begin() { return mdnMap.begin(); }
8070b57cec5SDimitry Andric   mdn_iterator mdn_end() { return mdnMap.end(); }
8080b57cec5SDimitry Andric   unsigned mdn_size() const { return mdnMap.size(); }
8090b57cec5SDimitry Andric   bool mdn_empty() const { return mdnMap.empty(); }
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   /// AttributeSet map iterators.
8120b57cec5SDimitry Andric   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   as_iterator as_begin()   { return asMap.begin(); }
8150b57cec5SDimitry Andric   as_iterator as_end()     { return asMap.end(); }
8160b57cec5SDimitry Andric   unsigned as_size() const { return asMap.size(); }
8170b57cec5SDimitry Andric   bool as_empty() const    { return asMap.empty(); }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   /// GUID map iterators.
8200b57cec5SDimitry Andric   using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   /// These functions do the actual initialization.
8230b57cec5SDimitry Andric   inline void initializeIfNeeded();
8245ffd83dbSDimitry Andric   int initializeIndexIfNeeded();
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   // Implementation Details
8270b57cec5SDimitry Andric private:
8280b57cec5SDimitry Andric   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
8290b57cec5SDimitry Andric   void CreateModuleSlot(const GlobalValue *V);
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
8320b57cec5SDimitry Andric   void CreateMetadataSlot(const MDNode *N);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
8350b57cec5SDimitry Andric   void CreateFunctionSlot(const Value *V);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   /// Insert the specified AttributeSet into the slot table.
8380b57cec5SDimitry Andric   void CreateAttributeSetSlot(AttributeSet AS);
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   inline void CreateModulePathSlot(StringRef Path);
8410b57cec5SDimitry Andric   void CreateGUIDSlot(GlobalValue::GUID GUID);
8420b57cec5SDimitry Andric   void CreateTypeIdSlot(StringRef Id);
843*5f757f3fSDimitry Andric   void CreateTypeIdCompatibleVtableSlot(StringRef Id);
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   /// Add all of the module level global variables (and their initializers)
8460b57cec5SDimitry Andric   /// and function declarations, but not the contents of those functions.
8470b57cec5SDimitry Andric   void processModule();
8485ffd83dbSDimitry Andric   // Returns number of allocated slots
8495ffd83dbSDimitry Andric   int processIndex();
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   /// Add all of the functions arguments, basic blocks, and instructions.
8520b57cec5SDimitry Andric   void processFunction();
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   /// Add the metadata directly attached to a GlobalObject.
8550b57cec5SDimitry Andric   void processGlobalObjectMetadata(const GlobalObject &GO);
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   /// Add all of the metadata from a function.
8580b57cec5SDimitry Andric   void processFunctionMetadata(const Function &F);
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   /// Add all of the metadata from an instruction.
8610b57cec5SDimitry Andric   void processInstructionMetadata(const Instruction &I);
8620b57cec5SDimitry Andric };
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric } // end namespace llvm
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
8670b57cec5SDimitry Andric                                      const Function *F)
8680b57cec5SDimitry Andric     : M(M), F(F), Machine(&Machine) {}
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric ModuleSlotTracker::ModuleSlotTracker(const Module *M,
8710b57cec5SDimitry Andric                                      bool ShouldInitializeAllMetadata)
8720b57cec5SDimitry Andric     : ShouldCreateStorage(M),
8730b57cec5SDimitry Andric       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric ModuleSlotTracker::~ModuleSlotTracker() = default;
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric SlotTracker *ModuleSlotTracker::getMachine() {
8780b57cec5SDimitry Andric   if (!ShouldCreateStorage)
8790b57cec5SDimitry Andric     return Machine;
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric   ShouldCreateStorage = false;
8820b57cec5SDimitry Andric   MachineStorage =
8838bcb0991SDimitry Andric       std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
8840b57cec5SDimitry Andric   Machine = MachineStorage.get();
885fe6060f1SDimitry Andric   if (ProcessModuleHookFn)
886fe6060f1SDimitry Andric     Machine->setProcessHook(ProcessModuleHookFn);
887fe6060f1SDimitry Andric   if (ProcessFunctionHookFn)
888fe6060f1SDimitry Andric     Machine->setProcessHook(ProcessFunctionHookFn);
8890b57cec5SDimitry Andric   return Machine;
8900b57cec5SDimitry Andric }
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric void ModuleSlotTracker::incorporateFunction(const Function &F) {
8930b57cec5SDimitry Andric   // Using getMachine() may lazily create the slot tracker.
8940b57cec5SDimitry Andric   if (!getMachine())
8950b57cec5SDimitry Andric     return;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   // Nothing to do if this is the right function already.
8980b57cec5SDimitry Andric   if (this->F == &F)
8990b57cec5SDimitry Andric     return;
9000b57cec5SDimitry Andric   if (this->F)
9010b57cec5SDimitry Andric     Machine->purgeFunction();
9020b57cec5SDimitry Andric   Machine->incorporateFunction(&F);
9030b57cec5SDimitry Andric   this->F = &F;
9040b57cec5SDimitry Andric }
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric int ModuleSlotTracker::getLocalSlot(const Value *V) {
9070b57cec5SDimitry Andric   assert(F && "No function incorporated");
9080b57cec5SDimitry Andric   return Machine->getLocalSlot(V);
9090b57cec5SDimitry Andric }
9100b57cec5SDimitry Andric 
911fe6060f1SDimitry Andric void ModuleSlotTracker::setProcessHook(
912fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
913fe6060f1SDimitry Andric         Fn) {
914fe6060f1SDimitry Andric   ProcessModuleHookFn = Fn;
915fe6060f1SDimitry Andric }
916fe6060f1SDimitry Andric 
917fe6060f1SDimitry Andric void ModuleSlotTracker::setProcessHook(
918fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
919fe6060f1SDimitry Andric         Fn) {
920fe6060f1SDimitry Andric   ProcessFunctionHookFn = Fn;
921fe6060f1SDimitry Andric }
922fe6060f1SDimitry Andric 
9230b57cec5SDimitry Andric static SlotTracker *createSlotTracker(const Value *V) {
9240b57cec5SDimitry Andric   if (const Argument *FA = dyn_cast<Argument>(V))
9250b57cec5SDimitry Andric     return new SlotTracker(FA->getParent());
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(V))
9280b57cec5SDimitry Andric     if (I->getParent())
9290b57cec5SDimitry Andric       return new SlotTracker(I->getParent()->getParent());
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
9320b57cec5SDimitry Andric     return new SlotTracker(BB->getParent());
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
9350b57cec5SDimitry Andric     return new SlotTracker(GV->getParent());
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
9380b57cec5SDimitry Andric     return new SlotTracker(GA->getParent());
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
9410b57cec5SDimitry Andric     return new SlotTracker(GIF->getParent());
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   if (const Function *Func = dyn_cast<Function>(V))
9440b57cec5SDimitry Andric     return new SlotTracker(Func);
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   return nullptr;
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric #if 0
9500b57cec5SDimitry Andric #define ST_DEBUG(X) dbgs() << X
9510b57cec5SDimitry Andric #else
9520b57cec5SDimitry Andric #define ST_DEBUG(X)
9530b57cec5SDimitry Andric #endif
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric // Module level constructor. Causes the contents of the Module (sans functions)
9560b57cec5SDimitry Andric // to be added to the slot table.
9570b57cec5SDimitry Andric SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
9580b57cec5SDimitry Andric     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric // Function level constructor. Causes the contents of the Module and the one
9610b57cec5SDimitry Andric // function provided to be added to the slot table.
9620b57cec5SDimitry Andric SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
9630b57cec5SDimitry Andric     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
9640b57cec5SDimitry Andric       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
9670b57cec5SDimitry Andric     : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric inline void SlotTracker::initializeIfNeeded() {
9700b57cec5SDimitry Andric   if (TheModule) {
9710b57cec5SDimitry Andric     processModule();
9720b57cec5SDimitry Andric     TheModule = nullptr; ///< Prevent re-processing next time we're called.
9730b57cec5SDimitry Andric   }
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric   if (TheFunction && !FunctionProcessed)
9760b57cec5SDimitry Andric     processFunction();
9770b57cec5SDimitry Andric }
9780b57cec5SDimitry Andric 
9795ffd83dbSDimitry Andric int SlotTracker::initializeIndexIfNeeded() {
9800b57cec5SDimitry Andric   if (!TheIndex)
9815ffd83dbSDimitry Andric     return 0;
9825ffd83dbSDimitry Andric   int NumSlots = processIndex();
9830b57cec5SDimitry Andric   TheIndex = nullptr; ///< Prevent re-processing next time we're called.
9845ffd83dbSDimitry Andric   return NumSlots;
9850b57cec5SDimitry Andric }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric // Iterate through all the global variables, functions, and global
9880b57cec5SDimitry Andric // variable initializers and create slots for them.
9890b57cec5SDimitry Andric void SlotTracker::processModule() {
9900b57cec5SDimitry Andric   ST_DEBUG("begin processModule!\n");
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   // Add all of the unnamed global variables to the value table.
9930b57cec5SDimitry Andric   for (const GlobalVariable &Var : TheModule->globals()) {
9940b57cec5SDimitry Andric     if (!Var.hasName())
9950b57cec5SDimitry Andric       CreateModuleSlot(&Var);
9960b57cec5SDimitry Andric     processGlobalObjectMetadata(Var);
9970b57cec5SDimitry Andric     auto Attrs = Var.getAttributes();
9980b57cec5SDimitry Andric     if (Attrs.hasAttributes())
9990b57cec5SDimitry Andric       CreateAttributeSetSlot(Attrs);
10000b57cec5SDimitry Andric   }
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric   for (const GlobalAlias &A : TheModule->aliases()) {
10030b57cec5SDimitry Andric     if (!A.hasName())
10040b57cec5SDimitry Andric       CreateModuleSlot(&A);
10050b57cec5SDimitry Andric   }
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   for (const GlobalIFunc &I : TheModule->ifuncs()) {
10080b57cec5SDimitry Andric     if (!I.hasName())
10090b57cec5SDimitry Andric       CreateModuleSlot(&I);
10100b57cec5SDimitry Andric   }
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   // Add metadata used by named metadata.
10130b57cec5SDimitry Andric   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
10140b57cec5SDimitry Andric     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
10150b57cec5SDimitry Andric       CreateMetadataSlot(NMD.getOperand(i));
10160b57cec5SDimitry Andric   }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   for (const Function &F : *TheModule) {
10190b57cec5SDimitry Andric     if (!F.hasName())
10200b57cec5SDimitry Andric       // Add all the unnamed functions to the table.
10210b57cec5SDimitry Andric       CreateModuleSlot(&F);
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric     if (ShouldInitializeAllMetadata)
10240b57cec5SDimitry Andric       processFunctionMetadata(F);
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric     // Add all the function attributes to the table.
10270b57cec5SDimitry Andric     // FIXME: Add attributes of other objects?
1028349cc55cSDimitry Andric     AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
10290b57cec5SDimitry Andric     if (FnAttrs.hasAttributes())
10300b57cec5SDimitry Andric       CreateAttributeSetSlot(FnAttrs);
10310b57cec5SDimitry Andric   }
10320b57cec5SDimitry Andric 
1033fe6060f1SDimitry Andric   if (ProcessModuleHookFn)
1034fe6060f1SDimitry Andric     ProcessModuleHookFn(this, TheModule, ShouldInitializeAllMetadata);
1035fe6060f1SDimitry Andric 
10360b57cec5SDimitry Andric   ST_DEBUG("end processModule!\n");
10370b57cec5SDimitry Andric }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric // Process the arguments, basic blocks, and instructions  of a function.
10400b57cec5SDimitry Andric void SlotTracker::processFunction() {
10410b57cec5SDimitry Andric   ST_DEBUG("begin processFunction!\n");
10420b57cec5SDimitry Andric   fNext = 0;
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric   // Process function metadata if it wasn't hit at the module-level.
10450b57cec5SDimitry Andric   if (!ShouldInitializeAllMetadata)
10460b57cec5SDimitry Andric     processFunctionMetadata(*TheFunction);
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric   // Add all the function arguments with no names.
10490b57cec5SDimitry Andric   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
10500b57cec5SDimitry Andric       AE = TheFunction->arg_end(); AI != AE; ++AI)
10510b57cec5SDimitry Andric     if (!AI->hasName())
10520b57cec5SDimitry Andric       CreateFunctionSlot(&*AI);
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   ST_DEBUG("Inserting Instructions:\n");
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   // Add all of the basic blocks and instructions with no names.
10570b57cec5SDimitry Andric   for (auto &BB : *TheFunction) {
10580b57cec5SDimitry Andric     if (!BB.hasName())
10590b57cec5SDimitry Andric       CreateFunctionSlot(&BB);
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric     for (auto &I : BB) {
10620b57cec5SDimitry Andric       if (!I.getType()->isVoidTy() && !I.hasName())
10630b57cec5SDimitry Andric         CreateFunctionSlot(&I);
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric       // We allow direct calls to any llvm.foo function here, because the
10660b57cec5SDimitry Andric       // target may not be linked into the optimizer.
10670b57cec5SDimitry Andric       if (const auto *Call = dyn_cast<CallBase>(&I)) {
10680b57cec5SDimitry Andric         // Add all the call attributes to the table.
1069349cc55cSDimitry Andric         AttributeSet Attrs = Call->getAttributes().getFnAttrs();
10700b57cec5SDimitry Andric         if (Attrs.hasAttributes())
10710b57cec5SDimitry Andric           CreateAttributeSetSlot(Attrs);
10720b57cec5SDimitry Andric       }
10730b57cec5SDimitry Andric     }
10740b57cec5SDimitry Andric   }
10750b57cec5SDimitry Andric 
1076fe6060f1SDimitry Andric   if (ProcessFunctionHookFn)
1077fe6060f1SDimitry Andric     ProcessFunctionHookFn(this, TheFunction, ShouldInitializeAllMetadata);
1078fe6060f1SDimitry Andric 
10790b57cec5SDimitry Andric   FunctionProcessed = true;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   ST_DEBUG("end processFunction!\n");
10820b57cec5SDimitry Andric }
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric // Iterate through all the GUID in the index and create slots for them.
10855ffd83dbSDimitry Andric int SlotTracker::processIndex() {
10860b57cec5SDimitry Andric   ST_DEBUG("begin processIndex!\n");
10870b57cec5SDimitry Andric   assert(TheIndex);
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   // The first block of slots are just the module ids, which start at 0 and are
10900b57cec5SDimitry Andric   // assigned consecutively. Since the StringMap iteration order isn't
1091*5f757f3fSDimitry Andric   // guaranteed, order by path string before assigning slots.
1092*5f757f3fSDimitry Andric   std::vector<StringRef> ModulePaths;
1093*5f757f3fSDimitry Andric   for (auto &[ModPath, _] : TheIndex->modulePaths())
1094*5f757f3fSDimitry Andric     ModulePaths.push_back(ModPath);
1095*5f757f3fSDimitry Andric   llvm::sort(ModulePaths.begin(), ModulePaths.end());
1096*5f757f3fSDimitry Andric   for (auto &ModPath : ModulePaths)
1097*5f757f3fSDimitry Andric     CreateModulePathSlot(ModPath);
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   // Start numbering the GUIDs after the module ids.
11000b57cec5SDimitry Andric   GUIDNext = ModulePathNext;
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric   for (auto &GlobalList : *TheIndex)
11030b57cec5SDimitry Andric     CreateGUIDSlot(GlobalList.first);
11040b57cec5SDimitry Andric 
1105*5f757f3fSDimitry Andric   // Start numbering the TypeIdCompatibleVtables after the GUIDs.
1106*5f757f3fSDimitry Andric   TypeIdCompatibleVtableNext = GUIDNext;
11075ffd83dbSDimitry Andric   for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1108*5f757f3fSDimitry Andric     CreateTypeIdCompatibleVtableSlot(TId.first);
11095ffd83dbSDimitry Andric 
1110*5f757f3fSDimitry Andric   // Start numbering the TypeIds after the TypeIdCompatibleVtables.
1111*5f757f3fSDimitry Andric   TypeIdNext = TypeIdCompatibleVtableNext;
1112fe6060f1SDimitry Andric   for (const auto &TID : TheIndex->typeIds())
1113fe6060f1SDimitry Andric     CreateTypeIdSlot(TID.second.first);
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   ST_DEBUG("end processIndex!\n");
11165ffd83dbSDimitry Andric   return TypeIdNext;
11170b57cec5SDimitry Andric }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
11200b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
11210b57cec5SDimitry Andric   GO.getAllMetadata(MDs);
11220b57cec5SDimitry Andric   for (auto &MD : MDs)
11230b57cec5SDimitry Andric     CreateMetadataSlot(MD.second);
11240b57cec5SDimitry Andric }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric void SlotTracker::processFunctionMetadata(const Function &F) {
11270b57cec5SDimitry Andric   processGlobalObjectMetadata(F);
11280b57cec5SDimitry Andric   for (auto &BB : F) {
11290b57cec5SDimitry Andric     for (auto &I : BB)
11300b57cec5SDimitry Andric       processInstructionMetadata(I);
11310b57cec5SDimitry Andric   }
11320b57cec5SDimitry Andric }
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric void SlotTracker::processInstructionMetadata(const Instruction &I) {
11350b57cec5SDimitry Andric   // Process metadata used directly by intrinsics.
11360b57cec5SDimitry Andric   if (const CallInst *CI = dyn_cast<CallInst>(&I))
11370b57cec5SDimitry Andric     if (Function *F = CI->getCalledFunction())
11380b57cec5SDimitry Andric       if (F->isIntrinsic())
11390b57cec5SDimitry Andric         for (auto &Op : I.operands())
11400b57cec5SDimitry Andric           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
11410b57cec5SDimitry Andric             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
11420b57cec5SDimitry Andric               CreateMetadataSlot(N);
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric   // Process metadata attached to this instruction.
11450b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
11460b57cec5SDimitry Andric   I.getAllMetadata(MDs);
11470b57cec5SDimitry Andric   for (auto &MD : MDs)
11480b57cec5SDimitry Andric     CreateMetadataSlot(MD.second);
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric /// Clean up after incorporating a function. This is the only way to get out of
11520b57cec5SDimitry Andric /// the function incorporation state that affects get*Slot/Create*Slot. Function
11530b57cec5SDimitry Andric /// incorporation state is indicated by TheFunction != 0.
11540b57cec5SDimitry Andric void SlotTracker::purgeFunction() {
11550b57cec5SDimitry Andric   ST_DEBUG("begin purgeFunction!\n");
11560b57cec5SDimitry Andric   fMap.clear(); // Simply discard the function level map
11570b57cec5SDimitry Andric   TheFunction = nullptr;
11580b57cec5SDimitry Andric   FunctionProcessed = false;
11590b57cec5SDimitry Andric   ST_DEBUG("end purgeFunction!\n");
11600b57cec5SDimitry Andric }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric /// getGlobalSlot - Get the slot number of a global value.
11630b57cec5SDimitry Andric int SlotTracker::getGlobalSlot(const GlobalValue *V) {
11640b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
11650b57cec5SDimitry Andric   initializeIfNeeded();
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric   // Find the value in the module map
11680b57cec5SDimitry Andric   ValueMap::iterator MI = mMap.find(V);
11690b57cec5SDimitry Andric   return MI == mMap.end() ? -1 : (int)MI->second;
11700b57cec5SDimitry Andric }
11710b57cec5SDimitry Andric 
1172fe6060f1SDimitry Andric void SlotTracker::setProcessHook(
1173fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
1174fe6060f1SDimitry Andric         Fn) {
1175fe6060f1SDimitry Andric   ProcessModuleHookFn = Fn;
1176fe6060f1SDimitry Andric }
1177fe6060f1SDimitry Andric 
1178fe6060f1SDimitry Andric void SlotTracker::setProcessHook(
1179fe6060f1SDimitry Andric     std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
1180fe6060f1SDimitry Andric         Fn) {
1181fe6060f1SDimitry Andric   ProcessFunctionHookFn = Fn;
1182fe6060f1SDimitry Andric }
1183fe6060f1SDimitry Andric 
1184fe6060f1SDimitry Andric /// getMetadataSlot - Get the slot number of a MDNode.
1185fe6060f1SDimitry Andric void SlotTracker::createMetadataSlot(const MDNode *N) { CreateMetadataSlot(N); }
1186fe6060f1SDimitry Andric 
11870b57cec5SDimitry Andric /// getMetadataSlot - Get the slot number of a MDNode.
11880b57cec5SDimitry Andric int SlotTracker::getMetadataSlot(const MDNode *N) {
11890b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
11900b57cec5SDimitry Andric   initializeIfNeeded();
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   // Find the MDNode in the module map
11930b57cec5SDimitry Andric   mdn_iterator MI = mdnMap.find(N);
11940b57cec5SDimitry Andric   return MI == mdnMap.end() ? -1 : (int)MI->second;
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric /// getLocalSlot - Get the slot number for a value that is local to a function.
11980b57cec5SDimitry Andric int SlotTracker::getLocalSlot(const Value *V) {
11990b57cec5SDimitry Andric   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12020b57cec5SDimitry Andric   initializeIfNeeded();
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric   ValueMap::iterator FI = fMap.find(V);
12050b57cec5SDimitry Andric   return FI == fMap.end() ? -1 : (int)FI->second;
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
12090b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12100b57cec5SDimitry Andric   initializeIfNeeded();
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric   // Find the AttributeSet in the module map.
12130b57cec5SDimitry Andric   as_iterator AI = asMap.find(AS);
12140b57cec5SDimitry Andric   return AI == asMap.end() ? -1 : (int)AI->second;
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric int SlotTracker::getModulePathSlot(StringRef Path) {
12180b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12190b57cec5SDimitry Andric   initializeIndexIfNeeded();
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric   // Find the Module path in the map
12220b57cec5SDimitry Andric   auto I = ModulePathMap.find(Path);
12230b57cec5SDimitry Andric   return I == ModulePathMap.end() ? -1 : (int)I->second;
12240b57cec5SDimitry Andric }
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
12270b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12280b57cec5SDimitry Andric   initializeIndexIfNeeded();
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Find the GUID in the map
12310b57cec5SDimitry Andric   guid_iterator I = GUIDMap.find(GUID);
12320b57cec5SDimitry Andric   return I == GUIDMap.end() ? -1 : (int)I->second;
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric int SlotTracker::getTypeIdSlot(StringRef Id) {
12360b57cec5SDimitry Andric   // Check for uninitialized state and do lazy initialization.
12370b57cec5SDimitry Andric   initializeIndexIfNeeded();
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric   // Find the TypeId string in the map
12400b57cec5SDimitry Andric   auto I = TypeIdMap.find(Id);
12410b57cec5SDimitry Andric   return I == TypeIdMap.end() ? -1 : (int)I->second;
12420b57cec5SDimitry Andric }
12430b57cec5SDimitry Andric 
1244*5f757f3fSDimitry Andric int SlotTracker::getTypeIdCompatibleVtableSlot(StringRef Id) {
1245*5f757f3fSDimitry Andric   // Check for uninitialized state and do lazy initialization.
1246*5f757f3fSDimitry Andric   initializeIndexIfNeeded();
1247*5f757f3fSDimitry Andric 
1248*5f757f3fSDimitry Andric   // Find the TypeIdCompatibleVtable string in the map
1249*5f757f3fSDimitry Andric   auto I = TypeIdCompatibleVtableMap.find(Id);
1250*5f757f3fSDimitry Andric   return I == TypeIdCompatibleVtableMap.end() ? -1 : (int)I->second;
1251*5f757f3fSDimitry Andric }
1252*5f757f3fSDimitry Andric 
12530b57cec5SDimitry Andric /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
12540b57cec5SDimitry Andric void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
12550b57cec5SDimitry Andric   assert(V && "Can't insert a null Value into SlotTracker!");
12560b57cec5SDimitry Andric   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
12570b57cec5SDimitry Andric   assert(!V->hasName() && "Doesn't need a slot!");
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric   unsigned DestSlot = mNext++;
12600b57cec5SDimitry Andric   mMap[V] = DestSlot;
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
12630b57cec5SDimitry Andric            DestSlot << " [");
12640b57cec5SDimitry Andric   // G = Global, F = Function, A = Alias, I = IFunc, o = other
12650b57cec5SDimitry Andric   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
12660b57cec5SDimitry Andric             (isa<Function>(V) ? 'F' :
12670b57cec5SDimitry Andric              (isa<GlobalAlias>(V) ? 'A' :
12680b57cec5SDimitry Andric               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
12690b57cec5SDimitry Andric }
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric /// CreateSlot - Create a new slot for the specified value if it has no name.
12720b57cec5SDimitry Andric void SlotTracker::CreateFunctionSlot(const Value *V) {
12730b57cec5SDimitry Andric   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   unsigned DestSlot = fNext++;
12760b57cec5SDimitry Andric   fMap[V] = DestSlot;
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   // G = Global, F = Function, o = other
12790b57cec5SDimitry Andric   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
12800b57cec5SDimitry Andric            DestSlot << " [o]\n");
12810b57cec5SDimitry Andric }
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
12840b57cec5SDimitry Andric void SlotTracker::CreateMetadataSlot(const MDNode *N) {
12850b57cec5SDimitry Andric   assert(N && "Can't insert a null Value into SlotTracker!");
12860b57cec5SDimitry Andric 
1287*5f757f3fSDimitry Andric   // Don't make slots for DIExpressions. We just print them inline everywhere.
1288*5f757f3fSDimitry Andric   if (isa<DIExpression>(N))
12890b57cec5SDimitry Andric     return;
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric   unsigned DestSlot = mdnNext;
12920b57cec5SDimitry Andric   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
12930b57cec5SDimitry Andric     return;
12940b57cec5SDimitry Andric   ++mdnNext;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   // Recursively add any MDNodes referenced by operands.
12970b57cec5SDimitry Andric   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
12980b57cec5SDimitry Andric     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
12990b57cec5SDimitry Andric       CreateMetadataSlot(Op);
13000b57cec5SDimitry Andric }
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
13030b57cec5SDimitry Andric   assert(AS.hasAttributes() && "Doesn't need a slot!");
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   as_iterator I = asMap.find(AS);
13060b57cec5SDimitry Andric   if (I != asMap.end())
13070b57cec5SDimitry Andric     return;
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   unsigned DestSlot = asNext++;
13100b57cec5SDimitry Andric   asMap[AS] = DestSlot;
13110b57cec5SDimitry Andric }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric /// Create a new slot for the specified Module
13140b57cec5SDimitry Andric void SlotTracker::CreateModulePathSlot(StringRef Path) {
13150b57cec5SDimitry Andric   ModulePathMap[Path] = ModulePathNext++;
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric /// Create a new slot for the specified GUID
13190b57cec5SDimitry Andric void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
13200b57cec5SDimitry Andric   GUIDMap[GUID] = GUIDNext++;
13210b57cec5SDimitry Andric }
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric /// Create a new slot for the specified Id
13240b57cec5SDimitry Andric void SlotTracker::CreateTypeIdSlot(StringRef Id) {
13250b57cec5SDimitry Andric   TypeIdMap[Id] = TypeIdNext++;
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
1328*5f757f3fSDimitry Andric /// Create a new slot for the specified Id
1329*5f757f3fSDimitry Andric void SlotTracker::CreateTypeIdCompatibleVtableSlot(StringRef Id) {
1330*5f757f3fSDimitry Andric   TypeIdCompatibleVtableMap[Id] = TypeIdCompatibleVtableNext++;
1331*5f757f3fSDimitry Andric }
1332*5f757f3fSDimitry Andric 
1333349cc55cSDimitry Andric namespace {
1334349cc55cSDimitry Andric /// Common instances used by most of the printer functions.
1335349cc55cSDimitry Andric struct AsmWriterContext {
1336349cc55cSDimitry Andric   TypePrinting *TypePrinter = nullptr;
1337349cc55cSDimitry Andric   SlotTracker *Machine = nullptr;
1338349cc55cSDimitry Andric   const Module *Context = nullptr;
1339349cc55cSDimitry Andric 
1340349cc55cSDimitry Andric   AsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M = nullptr)
1341349cc55cSDimitry Andric       : TypePrinter(TP), Machine(ST), Context(M) {}
1342349cc55cSDimitry Andric 
1343349cc55cSDimitry Andric   static AsmWriterContext &getEmpty() {
1344349cc55cSDimitry Andric     static AsmWriterContext EmptyCtx(nullptr, nullptr);
1345349cc55cSDimitry Andric     return EmptyCtx;
1346349cc55cSDimitry Andric   }
1347349cc55cSDimitry Andric 
1348349cc55cSDimitry Andric   /// A callback that will be triggered when the underlying printer
1349349cc55cSDimitry Andric   /// prints a Metadata as operand.
1350349cc55cSDimitry Andric   virtual void onWriteMetadataAsOperand(const Metadata *) {}
1351349cc55cSDimitry Andric 
135281ad6265SDimitry Andric   virtual ~AsmWriterContext() = default;
1353349cc55cSDimitry Andric };
1354349cc55cSDimitry Andric } // end anonymous namespace
1355349cc55cSDimitry Andric 
13560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13570b57cec5SDimitry Andric // AsmWriter Implementation
13580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1361349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx);
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1364349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx,
13650b57cec5SDimitry Andric                                    bool FromValue = false);
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
13684824e7fdSDimitry Andric   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
13694824e7fdSDimitry Andric     Out << FPO->getFastMathFlags();
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   if (const OverflowingBinaryOperator *OBO =
13720b57cec5SDimitry Andric         dyn_cast<OverflowingBinaryOperator>(U)) {
13730b57cec5SDimitry Andric     if (OBO->hasNoUnsignedWrap())
13740b57cec5SDimitry Andric       Out << " nuw";
13750b57cec5SDimitry Andric     if (OBO->hasNoSignedWrap())
13760b57cec5SDimitry Andric       Out << " nsw";
13770b57cec5SDimitry Andric   } else if (const PossiblyExactOperator *Div =
13780b57cec5SDimitry Andric                dyn_cast<PossiblyExactOperator>(U)) {
13790b57cec5SDimitry Andric     if (Div->isExact())
13800b57cec5SDimitry Andric       Out << " exact";
1381*5f757f3fSDimitry Andric   } else if (const PossiblyDisjointInst *PDI =
1382*5f757f3fSDimitry Andric                  dyn_cast<PossiblyDisjointInst>(U)) {
1383*5f757f3fSDimitry Andric     if (PDI->isDisjoint())
1384*5f757f3fSDimitry Andric       Out << " disjoint";
13850b57cec5SDimitry Andric   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
13860b57cec5SDimitry Andric     if (GEP->isInBounds())
13870b57cec5SDimitry Andric       Out << " inbounds";
1388*5f757f3fSDimitry Andric   } else if (const auto *NNI = dyn_cast<PossiblyNonNegInst>(U)) {
1389*5f757f3fSDimitry Andric     if (NNI->hasNonNeg())
1390*5f757f3fSDimitry Andric       Out << " nneg";
13910b57cec5SDimitry Andric   }
13920b57cec5SDimitry Andric }
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1395349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
13960b57cec5SDimitry Andric   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
13970b57cec5SDimitry Andric     if (CI->getType()->isIntegerTy(1)) {
13980b57cec5SDimitry Andric       Out << (CI->getZExtValue() ? "true" : "false");
13990b57cec5SDimitry Andric       return;
14000b57cec5SDimitry Andric     }
14010b57cec5SDimitry Andric     Out << CI->getValue();
14020b57cec5SDimitry Andric     return;
14030b57cec5SDimitry Andric   }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
14060b57cec5SDimitry Andric     const APFloat &APF = CFP->getValueAPF();
14070b57cec5SDimitry Andric     if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
14080b57cec5SDimitry Andric         &APF.getSemantics() == &APFloat::IEEEdouble()) {
14090b57cec5SDimitry Andric       // We would like to output the FP constant value in exponential notation,
14100b57cec5SDimitry Andric       // but we cannot do this if doing so will lose precision.  Check here to
14110b57cec5SDimitry Andric       // make sure that we only output it in exponential format if we can parse
14120b57cec5SDimitry Andric       // the value back and get the same value.
14130b57cec5SDimitry Andric       //
14140b57cec5SDimitry Andric       bool ignored;
14150b57cec5SDimitry Andric       bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
14160b57cec5SDimitry Andric       bool isInf = APF.isInfinity();
14170b57cec5SDimitry Andric       bool isNaN = APF.isNaN();
14180b57cec5SDimitry Andric       if (!isInf && !isNaN) {
1419fe6060f1SDimitry Andric         double Val = APF.convertToDouble();
14200b57cec5SDimitry Andric         SmallString<128> StrVal;
14210b57cec5SDimitry Andric         APF.toString(StrVal, 6, 0, false);
14220b57cec5SDimitry Andric         // Check to make sure that the stringized number is not some string like
14230b57cec5SDimitry Andric         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
14240b57cec5SDimitry Andric         // that the string matches the "[-+]?[0-9]" regex.
14250b57cec5SDimitry Andric         //
1426e8d8bef9SDimitry Andric         assert((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') &&
1427e8d8bef9SDimitry Andric                                        isDigit(StrVal[1]))) &&
14280b57cec5SDimitry Andric                "[-+]?[0-9] regex does not match!");
14290b57cec5SDimitry Andric         // Reparse stringized version!
14300b57cec5SDimitry Andric         if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
14310b57cec5SDimitry Andric           Out << StrVal;
14320b57cec5SDimitry Andric           return;
14330b57cec5SDimitry Andric         }
14340b57cec5SDimitry Andric       }
14350b57cec5SDimitry Andric       // Otherwise we could not reparse it to exactly the same value, so we must
14360b57cec5SDimitry Andric       // output the string in hexadecimal format!  Note that loading and storing
14370b57cec5SDimitry Andric       // floating point types changes the bits of NaNs on some hosts, notably
14380b57cec5SDimitry Andric       // x86, so we must not use these types.
14390b57cec5SDimitry Andric       static_assert(sizeof(double) == sizeof(uint64_t),
14400b57cec5SDimitry Andric                     "assuming that double is 64 bits!");
14410b57cec5SDimitry Andric       APFloat apf = APF;
14420b57cec5SDimitry Andric       // Floats are represented in ASCII IR as double, convert.
1443e8d8bef9SDimitry Andric       // FIXME: We should allow 32-bit hex float and remove this.
1444e8d8bef9SDimitry Andric       if (!isDouble) {
1445e8d8bef9SDimitry Andric         // A signaling NaN is quieted on conversion, so we need to recreate the
1446e8d8bef9SDimitry Andric         // expected value after convert (quiet bit of the payload is clear).
1447e8d8bef9SDimitry Andric         bool IsSNAN = apf.isSignaling();
14480b57cec5SDimitry Andric         apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
14490b57cec5SDimitry Andric                     &ignored);
1450e8d8bef9SDimitry Andric         if (IsSNAN) {
1451e8d8bef9SDimitry Andric           APInt Payload = apf.bitcastToAPInt();
1452e8d8bef9SDimitry Andric           apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(),
1453e8d8bef9SDimitry Andric                                  &Payload);
1454e8d8bef9SDimitry Andric         }
1455e8d8bef9SDimitry Andric       }
14560b57cec5SDimitry Andric       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
14570b57cec5SDimitry Andric       return;
14580b57cec5SDimitry Andric     }
14590b57cec5SDimitry Andric 
14605ffd83dbSDimitry Andric     // Either half, bfloat or some form of long double.
14610b57cec5SDimitry Andric     // These appear as a magic letter identifying the type, then a
14620b57cec5SDimitry Andric     // fixed number of hex digits.
14630b57cec5SDimitry Andric     Out << "0x";
14640b57cec5SDimitry Andric     APInt API = APF.bitcastToAPInt();
14650b57cec5SDimitry Andric     if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
14660b57cec5SDimitry Andric       Out << 'K';
14670b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
14680b57cec5SDimitry Andric                                   /*Upper=*/true);
14690b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
14700b57cec5SDimitry Andric                                   /*Upper=*/true);
14710b57cec5SDimitry Andric       return;
14720b57cec5SDimitry Andric     } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
14730b57cec5SDimitry Andric       Out << 'L';
14740b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
14750b57cec5SDimitry Andric                                   /*Upper=*/true);
14760b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
14770b57cec5SDimitry Andric                                   /*Upper=*/true);
14780b57cec5SDimitry Andric     } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
14790b57cec5SDimitry Andric       Out << 'M';
14800b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
14810b57cec5SDimitry Andric                                   /*Upper=*/true);
14820b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
14830b57cec5SDimitry Andric                                   /*Upper=*/true);
14840b57cec5SDimitry Andric     } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
14850b57cec5SDimitry Andric       Out << 'H';
14860b57cec5SDimitry Andric       Out << format_hex_no_prefix(API.getZExtValue(), 4,
14870b57cec5SDimitry Andric                                   /*Upper=*/true);
14885ffd83dbSDimitry Andric     } else if (&APF.getSemantics() == &APFloat::BFloat()) {
14895ffd83dbSDimitry Andric       Out << 'R';
14905ffd83dbSDimitry Andric       Out << format_hex_no_prefix(API.getZExtValue(), 4,
14915ffd83dbSDimitry Andric                                   /*Upper=*/true);
14920b57cec5SDimitry Andric     } else
14930b57cec5SDimitry Andric       llvm_unreachable("Unsupported floating point type");
14940b57cec5SDimitry Andric     return;
14950b57cec5SDimitry Andric   }
14960b57cec5SDimitry Andric 
1497bdd1243dSDimitry Andric   if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
14980b57cec5SDimitry Andric     Out << "zeroinitializer";
14990b57cec5SDimitry Andric     return;
15000b57cec5SDimitry Andric   }
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
15030b57cec5SDimitry Andric     Out << "blockaddress(";
1504349cc55cSDimitry Andric     WriteAsOperandInternal(Out, BA->getFunction(), WriterCtx);
15050b57cec5SDimitry Andric     Out << ", ";
1506349cc55cSDimitry Andric     WriteAsOperandInternal(Out, BA->getBasicBlock(), WriterCtx);
15070b57cec5SDimitry Andric     Out << ")";
15080b57cec5SDimitry Andric     return;
15090b57cec5SDimitry Andric   }
15100b57cec5SDimitry Andric 
1511e8d8bef9SDimitry Andric   if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1512e8d8bef9SDimitry Andric     Out << "dso_local_equivalent ";
1513349cc55cSDimitry Andric     WriteAsOperandInternal(Out, Equiv->getGlobalValue(), WriterCtx);
1514e8d8bef9SDimitry Andric     return;
1515e8d8bef9SDimitry Andric   }
1516e8d8bef9SDimitry Andric 
15170eae32dcSDimitry Andric   if (const auto *NC = dyn_cast<NoCFIValue>(CV)) {
15180eae32dcSDimitry Andric     Out << "no_cfi ";
15190eae32dcSDimitry Andric     WriteAsOperandInternal(Out, NC->getGlobalValue(), WriterCtx);
15200eae32dcSDimitry Andric     return;
15210eae32dcSDimitry Andric   }
15220eae32dcSDimitry Andric 
15230b57cec5SDimitry Andric   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
15240b57cec5SDimitry Andric     Type *ETy = CA->getType()->getElementType();
15250b57cec5SDimitry Andric     Out << '[';
1526349cc55cSDimitry Andric     WriterCtx.TypePrinter->print(ETy, Out);
15270b57cec5SDimitry Andric     Out << ' ';
1528349cc55cSDimitry Andric     WriteAsOperandInternal(Out, CA->getOperand(0), WriterCtx);
15290b57cec5SDimitry Andric     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
15300b57cec5SDimitry Andric       Out << ", ";
1531349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(ETy, Out);
15320b57cec5SDimitry Andric       Out << ' ';
1533349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CA->getOperand(i), WriterCtx);
15340b57cec5SDimitry Andric     }
15350b57cec5SDimitry Andric     Out << ']';
15360b57cec5SDimitry Andric     return;
15370b57cec5SDimitry Andric   }
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
15400b57cec5SDimitry Andric     // As a special case, print the array as a string if it is an array of
15410b57cec5SDimitry Andric     // i8 with ConstantInt values.
15420b57cec5SDimitry Andric     if (CA->isString()) {
15430b57cec5SDimitry Andric       Out << "c\"";
15440b57cec5SDimitry Andric       printEscapedString(CA->getAsString(), Out);
15450b57cec5SDimitry Andric       Out << '"';
15460b57cec5SDimitry Andric       return;
15470b57cec5SDimitry Andric     }
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric     Type *ETy = CA->getType()->getElementType();
15500b57cec5SDimitry Andric     Out << '[';
1551349cc55cSDimitry Andric     WriterCtx.TypePrinter->print(ETy, Out);
15520b57cec5SDimitry Andric     Out << ' ';
1553349cc55cSDimitry Andric     WriteAsOperandInternal(Out, CA->getElementAsConstant(0), WriterCtx);
15540b57cec5SDimitry Andric     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
15550b57cec5SDimitry Andric       Out << ", ";
1556349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(ETy, Out);
15570b57cec5SDimitry Andric       Out << ' ';
1558349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), WriterCtx);
15590b57cec5SDimitry Andric     }
15600b57cec5SDimitry Andric     Out << ']';
15610b57cec5SDimitry Andric     return;
15620b57cec5SDimitry Andric   }
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
15650b57cec5SDimitry Andric     if (CS->getType()->isPacked())
15660b57cec5SDimitry Andric       Out << '<';
15670b57cec5SDimitry Andric     Out << '{';
15680b57cec5SDimitry Andric     unsigned N = CS->getNumOperands();
15690b57cec5SDimitry Andric     if (N) {
15700b57cec5SDimitry Andric       Out << ' ';
1571349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
15720b57cec5SDimitry Andric       Out << ' ';
15730b57cec5SDimitry Andric 
1574349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CS->getOperand(0), WriterCtx);
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric       for (unsigned i = 1; i < N; i++) {
15770b57cec5SDimitry Andric         Out << ", ";
1578349cc55cSDimitry Andric         WriterCtx.TypePrinter->print(CS->getOperand(i)->getType(), Out);
15790b57cec5SDimitry Andric         Out << ' ';
15800b57cec5SDimitry Andric 
1581349cc55cSDimitry Andric         WriteAsOperandInternal(Out, CS->getOperand(i), WriterCtx);
15820b57cec5SDimitry Andric       }
15830b57cec5SDimitry Andric       Out << ' ';
15840b57cec5SDimitry Andric     }
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric     Out << '}';
15870b57cec5SDimitry Andric     if (CS->getType()->isPacked())
15880b57cec5SDimitry Andric       Out << '>';
15890b57cec5SDimitry Andric     return;
15900b57cec5SDimitry Andric   }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1593e8d8bef9SDimitry Andric     auto *CVVTy = cast<FixedVectorType>(CV->getType());
15945ffd83dbSDimitry Andric     Type *ETy = CVVTy->getElementType();
15950b57cec5SDimitry Andric     Out << '<';
1596349cc55cSDimitry Andric     WriterCtx.TypePrinter->print(ETy, Out);
15970b57cec5SDimitry Andric     Out << ' ';
1598349cc55cSDimitry Andric     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
15995ffd83dbSDimitry Andric     for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
16000b57cec5SDimitry Andric       Out << ", ";
1601349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(ETy, Out);
16020b57cec5SDimitry Andric       Out << ' ';
1603349cc55cSDimitry Andric       WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
16040b57cec5SDimitry Andric     }
16050b57cec5SDimitry Andric     Out << '>';
16060b57cec5SDimitry Andric     return;
16070b57cec5SDimitry Andric   }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric   if (isa<ConstantPointerNull>(CV)) {
16100b57cec5SDimitry Andric     Out << "null";
16110b57cec5SDimitry Andric     return;
16120b57cec5SDimitry Andric   }
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric   if (isa<ConstantTokenNone>(CV)) {
16150b57cec5SDimitry Andric     Out << "none";
16160b57cec5SDimitry Andric     return;
16170b57cec5SDimitry Andric   }
16180b57cec5SDimitry Andric 
1619e8d8bef9SDimitry Andric   if (isa<PoisonValue>(CV)) {
1620e8d8bef9SDimitry Andric     Out << "poison";
1621e8d8bef9SDimitry Andric     return;
1622e8d8bef9SDimitry Andric   }
1623e8d8bef9SDimitry Andric 
16240b57cec5SDimitry Andric   if (isa<UndefValue>(CV)) {
16250b57cec5SDimitry Andric     Out << "undef";
16260b57cec5SDimitry Andric     return;
16270b57cec5SDimitry Andric   }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
16300b57cec5SDimitry Andric     Out << CE->getOpcodeName();
16310b57cec5SDimitry Andric     WriteOptimizationInfo(Out, CE);
16320b57cec5SDimitry Andric     if (CE->isCompare())
163306c3fb27SDimitry Andric       Out << ' ' << static_cast<CmpInst::Predicate>(CE->getPredicate());
16340b57cec5SDimitry Andric     Out << " (";
16350b57cec5SDimitry Andric 
1636bdd1243dSDimitry Andric     std::optional<unsigned> InRangeOp;
16370b57cec5SDimitry Andric     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1638349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
16390b57cec5SDimitry Andric       Out << ", ";
16400b57cec5SDimitry Andric       InRangeOp = GEP->getInRangeIndex();
16410b57cec5SDimitry Andric       if (InRangeOp)
16420b57cec5SDimitry Andric         ++*InRangeOp;
16430b57cec5SDimitry Andric     }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
16460b57cec5SDimitry Andric       if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
16470b57cec5SDimitry Andric         Out << "inrange ";
1648349cc55cSDimitry Andric       WriterCtx.TypePrinter->print((*OI)->getType(), Out);
16490b57cec5SDimitry Andric       Out << ' ';
1650349cc55cSDimitry Andric       WriteAsOperandInternal(Out, *OI, WriterCtx);
16510b57cec5SDimitry Andric       if (OI+1 != CE->op_end())
16520b57cec5SDimitry Andric         Out << ", ";
16530b57cec5SDimitry Andric     }
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric     if (CE->isCast()) {
16560b57cec5SDimitry Andric       Out << " to ";
1657349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(CE->getType(), Out);
16580b57cec5SDimitry Andric     }
16590b57cec5SDimitry Andric 
16605ffd83dbSDimitry Andric     if (CE->getOpcode() == Instruction::ShuffleVector)
16615ffd83dbSDimitry Andric       PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
16625ffd83dbSDimitry Andric 
16630b57cec5SDimitry Andric     Out << ')';
16640b57cec5SDimitry Andric     return;
16650b57cec5SDimitry Andric   }
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric   Out << "<placeholder or erroneous Constant>";
16680b57cec5SDimitry Andric }
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1671349cc55cSDimitry Andric                          AsmWriterContext &WriterCtx) {
16720b57cec5SDimitry Andric   Out << "!{";
16730b57cec5SDimitry Andric   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
16740b57cec5SDimitry Andric     const Metadata *MD = Node->getOperand(mi);
16750b57cec5SDimitry Andric     if (!MD)
16760b57cec5SDimitry Andric       Out << "null";
16770b57cec5SDimitry Andric     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
16780b57cec5SDimitry Andric       Value *V = MDV->getValue();
1679349cc55cSDimitry Andric       WriterCtx.TypePrinter->print(V->getType(), Out);
16800b57cec5SDimitry Andric       Out << ' ';
1681349cc55cSDimitry Andric       WriteAsOperandInternal(Out, V, WriterCtx);
16820b57cec5SDimitry Andric     } else {
1683349cc55cSDimitry Andric       WriteAsOperandInternal(Out, MD, WriterCtx);
1684349cc55cSDimitry Andric       WriterCtx.onWriteMetadataAsOperand(MD);
16850b57cec5SDimitry Andric     }
16860b57cec5SDimitry Andric     if (mi + 1 != me)
16870b57cec5SDimitry Andric       Out << ", ";
16880b57cec5SDimitry Andric   }
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   Out << "}";
16910b57cec5SDimitry Andric }
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric namespace {
16940b57cec5SDimitry Andric 
16950b57cec5SDimitry Andric struct FieldSeparator {
16960b57cec5SDimitry Andric   bool Skip = true;
16970b57cec5SDimitry Andric   const char *Sep;
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
17000b57cec5SDimitry Andric };
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
17030b57cec5SDimitry Andric   if (FS.Skip) {
17040b57cec5SDimitry Andric     FS.Skip = false;
17050b57cec5SDimitry Andric     return OS;
17060b57cec5SDimitry Andric   }
17070b57cec5SDimitry Andric   return OS << FS.Sep;
17080b57cec5SDimitry Andric }
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric struct MDFieldPrinter {
17110b57cec5SDimitry Andric   raw_ostream &Out;
17120b57cec5SDimitry Andric   FieldSeparator FS;
1713349cc55cSDimitry Andric   AsmWriterContext &WriterCtx;
17140b57cec5SDimitry Andric 
1715349cc55cSDimitry Andric   explicit MDFieldPrinter(raw_ostream &Out)
1716349cc55cSDimitry Andric       : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1717349cc55cSDimitry Andric   MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1718349cc55cSDimitry Andric       : Out(Out), WriterCtx(Ctx) {}
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   void printTag(const DINode *N);
17210b57cec5SDimitry Andric   void printMacinfoType(const DIMacroNode *N);
17220b57cec5SDimitry Andric   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
17230b57cec5SDimitry Andric   void printString(StringRef Name, StringRef Value,
17240b57cec5SDimitry Andric                    bool ShouldSkipEmpty = true);
17250b57cec5SDimitry Andric   void printMetadata(StringRef Name, const Metadata *MD,
17260b57cec5SDimitry Andric                      bool ShouldSkipNull = true);
17270b57cec5SDimitry Andric   template <class IntTy>
17280b57cec5SDimitry Andric   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
17295ffd83dbSDimitry Andric   void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
17305ffd83dbSDimitry Andric                   bool ShouldSkipZero);
1731bdd1243dSDimitry Andric   void printBool(StringRef Name, bool Value,
1732bdd1243dSDimitry Andric                  std::optional<bool> Default = std::nullopt);
17330b57cec5SDimitry Andric   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
17340b57cec5SDimitry Andric   void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
17350b57cec5SDimitry Andric   template <class IntTy, class Stringifier>
17360b57cec5SDimitry Andric   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
17370b57cec5SDimitry Andric                       bool ShouldSkipZero = true);
17380b57cec5SDimitry Andric   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
17390b57cec5SDimitry Andric   void printNameTableKind(StringRef Name,
17400b57cec5SDimitry Andric                           DICompileUnit::DebugNameTableKind NTK);
17410b57cec5SDimitry Andric };
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric } // end anonymous namespace
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric void MDFieldPrinter::printTag(const DINode *N) {
17460b57cec5SDimitry Andric   Out << FS << "tag: ";
17470b57cec5SDimitry Andric   auto Tag = dwarf::TagString(N->getTag());
17480b57cec5SDimitry Andric   if (!Tag.empty())
17490b57cec5SDimitry Andric     Out << Tag;
17500b57cec5SDimitry Andric   else
17510b57cec5SDimitry Andric     Out << N->getTag();
17520b57cec5SDimitry Andric }
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
17550b57cec5SDimitry Andric   Out << FS << "type: ";
17560b57cec5SDimitry Andric   auto Type = dwarf::MacinfoString(N->getMacinfoType());
17570b57cec5SDimitry Andric   if (!Type.empty())
17580b57cec5SDimitry Andric     Out << Type;
17590b57cec5SDimitry Andric   else
17600b57cec5SDimitry Andric     Out << N->getMacinfoType();
17610b57cec5SDimitry Andric }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric void MDFieldPrinter::printChecksum(
17640b57cec5SDimitry Andric     const DIFile::ChecksumInfo<StringRef> &Checksum) {
17650b57cec5SDimitry Andric   Out << FS << "checksumkind: " << Checksum.getKindAsString();
17660b57cec5SDimitry Andric   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
17670b57cec5SDimitry Andric }
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric void MDFieldPrinter::printString(StringRef Name, StringRef Value,
17700b57cec5SDimitry Andric                                  bool ShouldSkipEmpty) {
17710b57cec5SDimitry Andric   if (ShouldSkipEmpty && Value.empty())
17720b57cec5SDimitry Andric     return;
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   Out << FS << Name << ": \"";
17750b57cec5SDimitry Andric   printEscapedString(Value, Out);
17760b57cec5SDimitry Andric   Out << "\"";
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1780349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx) {
17810b57cec5SDimitry Andric   if (!MD) {
17820b57cec5SDimitry Andric     Out << "null";
17830b57cec5SDimitry Andric     return;
17840b57cec5SDimitry Andric   }
1785349cc55cSDimitry Andric   WriteAsOperandInternal(Out, MD, WriterCtx);
1786349cc55cSDimitry Andric   WriterCtx.onWriteMetadataAsOperand(MD);
17870b57cec5SDimitry Andric }
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
17900b57cec5SDimitry Andric                                    bool ShouldSkipNull) {
17910b57cec5SDimitry Andric   if (ShouldSkipNull && !MD)
17920b57cec5SDimitry Andric     return;
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric   Out << FS << Name << ": ";
1795349cc55cSDimitry Andric   writeMetadataAsOperand(Out, MD, WriterCtx);
17960b57cec5SDimitry Andric }
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric template <class IntTy>
17990b57cec5SDimitry Andric void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
18000b57cec5SDimitry Andric   if (ShouldSkipZero && !Int)
18010b57cec5SDimitry Andric     return;
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   Out << FS << Name << ": " << Int;
18040b57cec5SDimitry Andric }
18050b57cec5SDimitry Andric 
18065ffd83dbSDimitry Andric void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
18075ffd83dbSDimitry Andric                                 bool IsUnsigned, bool ShouldSkipZero) {
1808349cc55cSDimitry Andric   if (ShouldSkipZero && Int.isZero())
18095ffd83dbSDimitry Andric     return;
18105ffd83dbSDimitry Andric 
18115ffd83dbSDimitry Andric   Out << FS << Name << ": ";
18125ffd83dbSDimitry Andric   Int.print(Out, !IsUnsigned);
18135ffd83dbSDimitry Andric }
18145ffd83dbSDimitry Andric 
18150b57cec5SDimitry Andric void MDFieldPrinter::printBool(StringRef Name, bool Value,
1816bdd1243dSDimitry Andric                                std::optional<bool> Default) {
18170b57cec5SDimitry Andric   if (Default && Value == *Default)
18180b57cec5SDimitry Andric     return;
18190b57cec5SDimitry Andric   Out << FS << Name << ": " << (Value ? "true" : "false");
18200b57cec5SDimitry Andric }
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
18230b57cec5SDimitry Andric   if (!Flags)
18240b57cec5SDimitry Andric     return;
18250b57cec5SDimitry Andric 
18260b57cec5SDimitry Andric   Out << FS << Name << ": ";
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric   SmallVector<DINode::DIFlags, 8> SplitFlags;
18290b57cec5SDimitry Andric   auto Extra = DINode::splitFlags(Flags, SplitFlags);
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   FieldSeparator FlagsFS(" | ");
18320b57cec5SDimitry Andric   for (auto F : SplitFlags) {
18330b57cec5SDimitry Andric     auto StringF = DINode::getFlagString(F);
18340b57cec5SDimitry Andric     assert(!StringF.empty() && "Expected valid flag");
18350b57cec5SDimitry Andric     Out << FlagsFS << StringF;
18360b57cec5SDimitry Andric   }
18370b57cec5SDimitry Andric   if (Extra || SplitFlags.empty())
18380b57cec5SDimitry Andric     Out << FlagsFS << Extra;
18390b57cec5SDimitry Andric }
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric void MDFieldPrinter::printDISPFlags(StringRef Name,
18420b57cec5SDimitry Andric                                     DISubprogram::DISPFlags Flags) {
18430b57cec5SDimitry Andric   // Always print this field, because no flags in the IR at all will be
18440b57cec5SDimitry Andric   // interpreted as old-style isDefinition: true.
18450b57cec5SDimitry Andric   Out << FS << Name << ": ";
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric   if (!Flags) {
18480b57cec5SDimitry Andric     Out << 0;
18490b57cec5SDimitry Andric     return;
18500b57cec5SDimitry Andric   }
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric   SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
18530b57cec5SDimitry Andric   auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric   FieldSeparator FlagsFS(" | ");
18560b57cec5SDimitry Andric   for (auto F : SplitFlags) {
18570b57cec5SDimitry Andric     auto StringF = DISubprogram::getFlagString(F);
18580b57cec5SDimitry Andric     assert(!StringF.empty() && "Expected valid flag");
18590b57cec5SDimitry Andric     Out << FlagsFS << StringF;
18600b57cec5SDimitry Andric   }
18610b57cec5SDimitry Andric   if (Extra || SplitFlags.empty())
18620b57cec5SDimitry Andric     Out << FlagsFS << Extra;
18630b57cec5SDimitry Andric }
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric void MDFieldPrinter::printEmissionKind(StringRef Name,
18660b57cec5SDimitry Andric                                        DICompileUnit::DebugEmissionKind EK) {
18670b57cec5SDimitry Andric   Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
18680b57cec5SDimitry Andric }
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric void MDFieldPrinter::printNameTableKind(StringRef Name,
18710b57cec5SDimitry Andric                                         DICompileUnit::DebugNameTableKind NTK) {
18720b57cec5SDimitry Andric   if (NTK == DICompileUnit::DebugNameTableKind::Default)
18730b57cec5SDimitry Andric     return;
18740b57cec5SDimitry Andric   Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
18750b57cec5SDimitry Andric }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric template <class IntTy, class Stringifier>
18780b57cec5SDimitry Andric void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
18790b57cec5SDimitry Andric                                     Stringifier toString, bool ShouldSkipZero) {
18800b57cec5SDimitry Andric   if (!Value)
18810b57cec5SDimitry Andric     return;
18820b57cec5SDimitry Andric 
18830b57cec5SDimitry Andric   Out << FS << Name << ": ";
18840b57cec5SDimitry Andric   auto S = toString(Value);
18850b57cec5SDimitry Andric   if (!S.empty())
18860b57cec5SDimitry Andric     Out << S;
18870b57cec5SDimitry Andric   else
18880b57cec5SDimitry Andric     Out << Value;
18890b57cec5SDimitry Andric }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1892349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
18930b57cec5SDimitry Andric   Out << "!GenericDINode(";
1894349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
18950b57cec5SDimitry Andric   Printer.printTag(N);
18960b57cec5SDimitry Andric   Printer.printString("header", N->getHeader());
18970b57cec5SDimitry Andric   if (N->getNumDwarfOperands()) {
18980b57cec5SDimitry Andric     Out << Printer.FS << "operands: {";
18990b57cec5SDimitry Andric     FieldSeparator IFS;
19000b57cec5SDimitry Andric     for (auto &I : N->dwarf_operands()) {
19010b57cec5SDimitry Andric       Out << IFS;
1902349cc55cSDimitry Andric       writeMetadataAsOperand(Out, I, WriterCtx);
19030b57cec5SDimitry Andric     }
19040b57cec5SDimitry Andric     Out << "}";
19050b57cec5SDimitry Andric   }
19060b57cec5SDimitry Andric   Out << ")";
19070b57cec5SDimitry Andric }
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1910349cc55cSDimitry Andric                             AsmWriterContext &WriterCtx) {
19110b57cec5SDimitry Andric   Out << "!DILocation(";
1912349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
19130b57cec5SDimitry Andric   // Always output the line, since 0 is a relevant and important value for it.
19140b57cec5SDimitry Andric   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
19150b57cec5SDimitry Andric   Printer.printInt("column", DL->getColumn());
19160b57cec5SDimitry Andric   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
19170b57cec5SDimitry Andric   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
19180b57cec5SDimitry Andric   Printer.printBool("isImplicitCode", DL->isImplicitCode(),
19190b57cec5SDimitry Andric                     /* Default */ false);
19200b57cec5SDimitry Andric   Out << ")";
19210b57cec5SDimitry Andric }
19220b57cec5SDimitry Andric 
1923bdd1243dSDimitry Andric static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
1924bdd1243dSDimitry Andric                             AsmWriterContext &WriterCtx) {
1925bdd1243dSDimitry Andric   Out << "!DIAssignID()";
1926bdd1243dSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
1927bdd1243dSDimitry Andric }
1928bdd1243dSDimitry Andric 
19290b57cec5SDimitry Andric static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1930349cc55cSDimitry Andric                             AsmWriterContext &WriterCtx) {
19310b57cec5SDimitry Andric   Out << "!DISubrange(";
1932349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
1933fe6060f1SDimitry Andric 
1934fe6060f1SDimitry Andric   auto *Count = N->getRawCountNode();
1935fe6060f1SDimitry Andric   if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
1936fe6060f1SDimitry Andric     auto *CV = cast<ConstantInt>(CE->getValue());
1937fe6060f1SDimitry Andric     Printer.printInt("count", CV->getSExtValue(),
1938fe6060f1SDimitry Andric                      /* ShouldSkipZero */ false);
1939fe6060f1SDimitry Andric   } else
1940fe6060f1SDimitry Andric     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
19415ffd83dbSDimitry Andric 
19425ffd83dbSDimitry Andric   // A lowerBound of constant 0 should not be skipped, since it is different
19435ffd83dbSDimitry Andric   // from an unspecified lower bound (= nullptr).
19445ffd83dbSDimitry Andric   auto *LBound = N->getRawLowerBound();
19455ffd83dbSDimitry Andric   if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
19465ffd83dbSDimitry Andric     auto *LV = cast<ConstantInt>(LE->getValue());
19475ffd83dbSDimitry Andric     Printer.printInt("lowerBound", LV->getSExtValue(),
19485ffd83dbSDimitry Andric                      /* ShouldSkipZero */ false);
19495ffd83dbSDimitry Andric   } else
19505ffd83dbSDimitry Andric     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
19515ffd83dbSDimitry Andric 
19525ffd83dbSDimitry Andric   auto *UBound = N->getRawUpperBound();
19535ffd83dbSDimitry Andric   if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
19545ffd83dbSDimitry Andric     auto *UV = cast<ConstantInt>(UE->getValue());
19555ffd83dbSDimitry Andric     Printer.printInt("upperBound", UV->getSExtValue(),
19565ffd83dbSDimitry Andric                      /* ShouldSkipZero */ false);
19575ffd83dbSDimitry Andric   } else
19585ffd83dbSDimitry Andric     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
19595ffd83dbSDimitry Andric 
19605ffd83dbSDimitry Andric   auto *Stride = N->getRawStride();
19615ffd83dbSDimitry Andric   if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
19625ffd83dbSDimitry Andric     auto *SV = cast<ConstantInt>(SE->getValue());
19635ffd83dbSDimitry Andric     Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
19645ffd83dbSDimitry Andric   } else
19655ffd83dbSDimitry Andric     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
19665ffd83dbSDimitry Andric 
19670b57cec5SDimitry Andric   Out << ")";
19680b57cec5SDimitry Andric }
19690b57cec5SDimitry Andric 
1970e8d8bef9SDimitry Andric static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1971349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx) {
1972e8d8bef9SDimitry Andric   Out << "!DIGenericSubrange(";
1973349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
1974e8d8bef9SDimitry Andric 
1975e8d8bef9SDimitry Andric   auto IsConstant = [&](Metadata *Bound) -> bool {
1976e8d8bef9SDimitry Andric     if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1977349cc55cSDimitry Andric       return BE->isConstant() &&
1978349cc55cSDimitry Andric              DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1979349cc55cSDimitry Andric                  *BE->isConstant();
1980e8d8bef9SDimitry Andric     }
1981e8d8bef9SDimitry Andric     return false;
1982e8d8bef9SDimitry Andric   };
1983e8d8bef9SDimitry Andric 
1984e8d8bef9SDimitry Andric   auto GetConstant = [&](Metadata *Bound) -> int64_t {
1985e8d8bef9SDimitry Andric     assert(IsConstant(Bound) && "Expected constant");
1986e8d8bef9SDimitry Andric     auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1987e8d8bef9SDimitry Andric     return static_cast<int64_t>(BE->getElement(1));
1988e8d8bef9SDimitry Andric   };
1989e8d8bef9SDimitry Andric 
1990e8d8bef9SDimitry Andric   auto *Count = N->getRawCountNode();
1991e8d8bef9SDimitry Andric   if (IsConstant(Count))
1992e8d8bef9SDimitry Andric     Printer.printInt("count", GetConstant(Count),
1993e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
1994e8d8bef9SDimitry Andric   else
1995e8d8bef9SDimitry Andric     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1996e8d8bef9SDimitry Andric 
1997e8d8bef9SDimitry Andric   auto *LBound = N->getRawLowerBound();
1998e8d8bef9SDimitry Andric   if (IsConstant(LBound))
1999e8d8bef9SDimitry Andric     Printer.printInt("lowerBound", GetConstant(LBound),
2000e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2001e8d8bef9SDimitry Andric   else
2002e8d8bef9SDimitry Andric     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
2003e8d8bef9SDimitry Andric 
2004e8d8bef9SDimitry Andric   auto *UBound = N->getRawUpperBound();
2005e8d8bef9SDimitry Andric   if (IsConstant(UBound))
2006e8d8bef9SDimitry Andric     Printer.printInt("upperBound", GetConstant(UBound),
2007e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2008e8d8bef9SDimitry Andric   else
2009e8d8bef9SDimitry Andric     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
2010e8d8bef9SDimitry Andric 
2011e8d8bef9SDimitry Andric   auto *Stride = N->getRawStride();
2012e8d8bef9SDimitry Andric   if (IsConstant(Stride))
2013e8d8bef9SDimitry Andric     Printer.printInt("stride", GetConstant(Stride),
2014e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2015e8d8bef9SDimitry Andric   else
2016e8d8bef9SDimitry Andric     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
2017e8d8bef9SDimitry Andric 
2018e8d8bef9SDimitry Andric   Out << ")";
2019e8d8bef9SDimitry Andric }
2020e8d8bef9SDimitry Andric 
20210b57cec5SDimitry Andric static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
2022349cc55cSDimitry Andric                               AsmWriterContext &) {
20230b57cec5SDimitry Andric   Out << "!DIEnumerator(";
20240b57cec5SDimitry Andric   MDFieldPrinter Printer(Out);
20250b57cec5SDimitry Andric   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
20265ffd83dbSDimitry Andric   Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
20275ffd83dbSDimitry Andric                      /*ShouldSkipZero=*/false);
20285ffd83dbSDimitry Andric   if (N->isUnsigned())
20290b57cec5SDimitry Andric     Printer.printBool("isUnsigned", true);
20300b57cec5SDimitry Andric   Out << ")";
20310b57cec5SDimitry Andric }
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
2034349cc55cSDimitry Andric                              AsmWriterContext &) {
20350b57cec5SDimitry Andric   Out << "!DIBasicType(";
20360b57cec5SDimitry Andric   MDFieldPrinter Printer(Out);
20370b57cec5SDimitry Andric   if (N->getTag() != dwarf::DW_TAG_base_type)
20380b57cec5SDimitry Andric     Printer.printTag(N);
20390b57cec5SDimitry Andric   Printer.printString("name", N->getName());
20400b57cec5SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
20410b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
20420b57cec5SDimitry Andric   Printer.printDwarfEnum("encoding", N->getEncoding(),
20430b57cec5SDimitry Andric                          dwarf::AttributeEncodingString);
20440b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
20450b57cec5SDimitry Andric   Out << ")";
20460b57cec5SDimitry Andric }
20470b57cec5SDimitry Andric 
2048e8d8bef9SDimitry Andric static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2049349cc55cSDimitry Andric                               AsmWriterContext &WriterCtx) {
2050e8d8bef9SDimitry Andric   Out << "!DIStringType(";
2051349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2052e8d8bef9SDimitry Andric   if (N->getTag() != dwarf::DW_TAG_string_type)
2053e8d8bef9SDimitry Andric     Printer.printTag(N);
2054e8d8bef9SDimitry Andric   Printer.printString("name", N->getName());
2055e8d8bef9SDimitry Andric   Printer.printMetadata("stringLength", N->getRawStringLength());
2056e8d8bef9SDimitry Andric   Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
205704eeddc0SDimitry Andric   Printer.printMetadata("stringLocationExpression",
205804eeddc0SDimitry Andric                         N->getRawStringLocationExp());
2059e8d8bef9SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
2060e8d8bef9SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
2061e8d8bef9SDimitry Andric   Printer.printDwarfEnum("encoding", N->getEncoding(),
2062e8d8bef9SDimitry Andric                          dwarf::AttributeEncodingString);
2063e8d8bef9SDimitry Andric   Out << ")";
2064e8d8bef9SDimitry Andric }
2065e8d8bef9SDimitry Andric 
20660b57cec5SDimitry Andric static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2067349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
20680b57cec5SDimitry Andric   Out << "!DIDerivedType(";
2069349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
20700b57cec5SDimitry Andric   Printer.printTag(N);
20710b57cec5SDimitry Andric   Printer.printString("name", N->getName());
20720b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope());
20730b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
20740b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
20750b57cec5SDimitry Andric   Printer.printMetadata("baseType", N->getRawBaseType(),
20760b57cec5SDimitry Andric                         /* ShouldSkipNull */ false);
20770b57cec5SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
20780b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
20790b57cec5SDimitry Andric   Printer.printInt("offset", N->getOffsetInBits());
20800b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
20810b57cec5SDimitry Andric   Printer.printMetadata("extraData", N->getRawExtraData());
20820b57cec5SDimitry Andric   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
20830b57cec5SDimitry Andric     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
20840b57cec5SDimitry Andric                      /* ShouldSkipZero */ false);
2085349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
20860b57cec5SDimitry Andric   Out << ")";
20870b57cec5SDimitry Andric }
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2090349cc55cSDimitry Andric                                  AsmWriterContext &WriterCtx) {
20910b57cec5SDimitry Andric   Out << "!DICompositeType(";
2092349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
20930b57cec5SDimitry Andric   Printer.printTag(N);
20940b57cec5SDimitry Andric   Printer.printString("name", N->getName());
20950b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope());
20960b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
20970b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
20980b57cec5SDimitry Andric   Printer.printMetadata("baseType", N->getRawBaseType());
20990b57cec5SDimitry Andric   Printer.printInt("size", N->getSizeInBits());
21000b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
21010b57cec5SDimitry Andric   Printer.printInt("offset", N->getOffsetInBits());
21020b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
21030b57cec5SDimitry Andric   Printer.printMetadata("elements", N->getRawElements());
21040b57cec5SDimitry Andric   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
21050b57cec5SDimitry Andric                          dwarf::LanguageString);
21060b57cec5SDimitry Andric   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
21070b57cec5SDimitry Andric   Printer.printMetadata("templateParams", N->getRawTemplateParams());
21080b57cec5SDimitry Andric   Printer.printString("identifier", N->getIdentifier());
21090b57cec5SDimitry Andric   Printer.printMetadata("discriminator", N->getRawDiscriminator());
21105ffd83dbSDimitry Andric   Printer.printMetadata("dataLocation", N->getRawDataLocation());
2111e8d8bef9SDimitry Andric   Printer.printMetadata("associated", N->getRawAssociated());
2112e8d8bef9SDimitry Andric   Printer.printMetadata("allocated", N->getRawAllocated());
2113e8d8bef9SDimitry Andric   if (auto *RankConst = N->getRankConst())
2114e8d8bef9SDimitry Andric     Printer.printInt("rank", RankConst->getSExtValue(),
2115e8d8bef9SDimitry Andric                      /* ShouldSkipZero */ false);
2116e8d8bef9SDimitry Andric   else
2117e8d8bef9SDimitry Andric     Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2118349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
21190b57cec5SDimitry Andric   Out << ")";
21200b57cec5SDimitry Andric }
21210b57cec5SDimitry Andric 
21220b57cec5SDimitry Andric static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2123349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
21240b57cec5SDimitry Andric   Out << "!DISubroutineType(";
2125349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
21260b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
21270b57cec5SDimitry Andric   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
21280b57cec5SDimitry Andric   Printer.printMetadata("types", N->getRawTypeArray(),
21290b57cec5SDimitry Andric                         /* ShouldSkipNull */ false);
21300b57cec5SDimitry Andric   Out << ")";
21310b57cec5SDimitry Andric }
21320b57cec5SDimitry Andric 
2133349cc55cSDimitry Andric static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
21340b57cec5SDimitry Andric   Out << "!DIFile(";
21350b57cec5SDimitry Andric   MDFieldPrinter Printer(Out);
21360b57cec5SDimitry Andric   Printer.printString("filename", N->getFilename(),
21370b57cec5SDimitry Andric                       /* ShouldSkipEmpty */ false);
21380b57cec5SDimitry Andric   Printer.printString("directory", N->getDirectory(),
21390b57cec5SDimitry Andric                       /* ShouldSkipEmpty */ false);
21400b57cec5SDimitry Andric   // Print all values for checksum together, or not at all.
21410b57cec5SDimitry Andric   if (N->getChecksum())
21420b57cec5SDimitry Andric     Printer.printChecksum(*N->getChecksum());
214381ad6265SDimitry Andric   Printer.printString("source", N->getSource().value_or(StringRef()),
21440b57cec5SDimitry Andric                       /* ShouldSkipEmpty */ true);
21450b57cec5SDimitry Andric   Out << ")";
21460b57cec5SDimitry Andric }
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2149349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
21500b57cec5SDimitry Andric   Out << "!DICompileUnit(";
2151349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
21520b57cec5SDimitry Andric   Printer.printDwarfEnum("language", N->getSourceLanguage(),
21530b57cec5SDimitry Andric                          dwarf::LanguageString, /* ShouldSkipZero */ false);
21540b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
21550b57cec5SDimitry Andric   Printer.printString("producer", N->getProducer());
21560b57cec5SDimitry Andric   Printer.printBool("isOptimized", N->isOptimized());
21570b57cec5SDimitry Andric   Printer.printString("flags", N->getFlags());
21580b57cec5SDimitry Andric   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
21590b57cec5SDimitry Andric                    /* ShouldSkipZero */ false);
21600b57cec5SDimitry Andric   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
21610b57cec5SDimitry Andric   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
21620b57cec5SDimitry Andric   Printer.printMetadata("enums", N->getRawEnumTypes());
21630b57cec5SDimitry Andric   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
21640b57cec5SDimitry Andric   Printer.printMetadata("globals", N->getRawGlobalVariables());
21650b57cec5SDimitry Andric   Printer.printMetadata("imports", N->getRawImportedEntities());
21660b57cec5SDimitry Andric   Printer.printMetadata("macros", N->getRawMacros());
21670b57cec5SDimitry Andric   Printer.printInt("dwoId", N->getDWOId());
21680b57cec5SDimitry Andric   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
21690b57cec5SDimitry Andric   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
21700b57cec5SDimitry Andric                     false);
21710b57cec5SDimitry Andric   Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
21720b57cec5SDimitry Andric   Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
21735ffd83dbSDimitry Andric   Printer.printString("sysroot", N->getSysRoot());
21745ffd83dbSDimitry Andric   Printer.printString("sdk", N->getSDK());
21750b57cec5SDimitry Andric   Out << ")";
21760b57cec5SDimitry Andric }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2179349cc55cSDimitry Andric                               AsmWriterContext &WriterCtx) {
21800b57cec5SDimitry Andric   Out << "!DISubprogram(";
2181349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
21820b57cec5SDimitry Andric   Printer.printString("name", N->getName());
21830b57cec5SDimitry Andric   Printer.printString("linkageName", N->getLinkageName());
21840b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
21850b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
21860b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
21870b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
21880b57cec5SDimitry Andric   Printer.printInt("scopeLine", N->getScopeLine());
21890b57cec5SDimitry Andric   Printer.printMetadata("containingType", N->getRawContainingType());
21900b57cec5SDimitry Andric   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
21910b57cec5SDimitry Andric       N->getVirtualIndex() != 0)
21920b57cec5SDimitry Andric     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
21930b57cec5SDimitry Andric   Printer.printInt("thisAdjustment", N->getThisAdjustment());
21940b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
21950b57cec5SDimitry Andric   Printer.printDISPFlags("spFlags", N->getSPFlags());
21960b57cec5SDimitry Andric   Printer.printMetadata("unit", N->getRawUnit());
21970b57cec5SDimitry Andric   Printer.printMetadata("templateParams", N->getRawTemplateParams());
21980b57cec5SDimitry Andric   Printer.printMetadata("declaration", N->getRawDeclaration());
21990b57cec5SDimitry Andric   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
22000b57cec5SDimitry Andric   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2201349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
220281ad6265SDimitry Andric   Printer.printString("targetFuncName", N->getTargetFuncName());
22030b57cec5SDimitry Andric   Out << ")";
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2207349cc55cSDimitry Andric                                 AsmWriterContext &WriterCtx) {
22080b57cec5SDimitry Andric   Out << "!DILexicalBlock(";
2209349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22100b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
22110b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
22120b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
22130b57cec5SDimitry Andric   Printer.printInt("column", N->getColumn());
22140b57cec5SDimitry Andric   Out << ")";
22150b57cec5SDimitry Andric }
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric static void writeDILexicalBlockFile(raw_ostream &Out,
22180b57cec5SDimitry Andric                                     const DILexicalBlockFile *N,
2219349cc55cSDimitry Andric                                     AsmWriterContext &WriterCtx) {
22200b57cec5SDimitry Andric   Out << "!DILexicalBlockFile(";
2221349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22220b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
22230b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
22240b57cec5SDimitry Andric   Printer.printInt("discriminator", N->getDiscriminator(),
22250b57cec5SDimitry Andric                    /* ShouldSkipZero */ false);
22260b57cec5SDimitry Andric   Out << ")";
22270b57cec5SDimitry Andric }
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2230349cc55cSDimitry Andric                              AsmWriterContext &WriterCtx) {
22310b57cec5SDimitry Andric   Out << "!DINamespace(";
2232349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22330b57cec5SDimitry Andric   Printer.printString("name", N->getName());
22340b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
22350b57cec5SDimitry Andric   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
22360b57cec5SDimitry Andric   Out << ")";
22370b57cec5SDimitry Andric }
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2240349cc55cSDimitry Andric                                AsmWriterContext &WriterCtx) {
22410b57cec5SDimitry Andric   Out << "!DICommonBlock(";
2242349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22430b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), false);
22440b57cec5SDimitry Andric   Printer.printMetadata("declaration", N->getRawDecl(), false);
22450b57cec5SDimitry Andric   Printer.printString("name", N->getName());
22460b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
22470b57cec5SDimitry Andric   Printer.printInt("line", N->getLineNo());
22480b57cec5SDimitry Andric   Out << ")";
22490b57cec5SDimitry Andric }
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2252349cc55cSDimitry Andric                          AsmWriterContext &WriterCtx) {
22530b57cec5SDimitry Andric   Out << "!DIMacro(";
2254349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22550b57cec5SDimitry Andric   Printer.printMacinfoType(N);
22560b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
22570b57cec5SDimitry Andric   Printer.printString("name", N->getName());
22580b57cec5SDimitry Andric   Printer.printString("value", N->getValue());
22590b57cec5SDimitry Andric   Out << ")";
22600b57cec5SDimitry Andric }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2263349cc55cSDimitry Andric                              AsmWriterContext &WriterCtx) {
22640b57cec5SDimitry Andric   Out << "!DIMacroFile(";
2265349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22660b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
22670b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
22680b57cec5SDimitry Andric   Printer.printMetadata("nodes", N->getRawElements());
22690b57cec5SDimitry Andric   Out << ")";
22700b57cec5SDimitry Andric }
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric static void writeDIModule(raw_ostream &Out, const DIModule *N,
2273349cc55cSDimitry Andric                           AsmWriterContext &WriterCtx) {
22740b57cec5SDimitry Andric   Out << "!DIModule(";
2275349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22760b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
22770b57cec5SDimitry Andric   Printer.printString("name", N->getName());
22780b57cec5SDimitry Andric   Printer.printString("configMacros", N->getConfigurationMacros());
22790b57cec5SDimitry Andric   Printer.printString("includePath", N->getIncludePath());
22805ffd83dbSDimitry Andric   Printer.printString("apinotes", N->getAPINotesFile());
22815ffd83dbSDimitry Andric   Printer.printMetadata("file", N->getRawFile());
22825ffd83dbSDimitry Andric   Printer.printInt("line", N->getLineNo());
2283e8d8bef9SDimitry Andric   Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
22840b57cec5SDimitry Andric   Out << ")";
22850b57cec5SDimitry Andric }
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric static void writeDITemplateTypeParameter(raw_ostream &Out,
22880b57cec5SDimitry Andric                                          const DITemplateTypeParameter *N,
2289349cc55cSDimitry Andric                                          AsmWriterContext &WriterCtx) {
22900b57cec5SDimitry Andric   Out << "!DITemplateTypeParameter(";
2291349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
22920b57cec5SDimitry Andric   Printer.printString("name", N->getName());
22930b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
22945ffd83dbSDimitry Andric   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
22950b57cec5SDimitry Andric   Out << ")";
22960b57cec5SDimitry Andric }
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric static void writeDITemplateValueParameter(raw_ostream &Out,
22990b57cec5SDimitry Andric                                           const DITemplateValueParameter *N,
2300349cc55cSDimitry Andric                                           AsmWriterContext &WriterCtx) {
23010b57cec5SDimitry Andric   Out << "!DITemplateValueParameter(";
2302349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23030b57cec5SDimitry Andric   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
23040b57cec5SDimitry Andric     Printer.printTag(N);
23050b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23060b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
23075ffd83dbSDimitry Andric   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
23080b57cec5SDimitry Andric   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
23090b57cec5SDimitry Andric   Out << ")";
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2313349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
23140b57cec5SDimitry Andric   Out << "!DIGlobalVariable(";
2315349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23160b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23170b57cec5SDimitry Andric   Printer.printString("linkageName", N->getLinkageName());
23180b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23190b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23200b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
23210b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
23220b57cec5SDimitry Andric   Printer.printBool("isLocal", N->isLocalToUnit());
23230b57cec5SDimitry Andric   Printer.printBool("isDefinition", N->isDefinition());
23240b57cec5SDimitry Andric   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
23250b57cec5SDimitry Andric   Printer.printMetadata("templateParams", N->getRawTemplateParams());
23260b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
2327349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
23280b57cec5SDimitry Andric   Out << ")";
23290b57cec5SDimitry Andric }
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2332349cc55cSDimitry Andric                                  AsmWriterContext &WriterCtx) {
23330b57cec5SDimitry Andric   Out << "!DILocalVariable(";
2334349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23350b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23360b57cec5SDimitry Andric   Printer.printInt("arg", N->getArg());
23370b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23380b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23390b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
23400b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
23410b57cec5SDimitry Andric   Printer.printDIFlags("flags", N->getFlags());
23420b57cec5SDimitry Andric   Printer.printInt("align", N->getAlignInBits());
2343349cc55cSDimitry Andric   Printer.printMetadata("annotations", N->getRawAnnotations());
23440b57cec5SDimitry Andric   Out << ")";
23450b57cec5SDimitry Andric }
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric static void writeDILabel(raw_ostream &Out, const DILabel *N,
2348349cc55cSDimitry Andric                          AsmWriterContext &WriterCtx) {
23490b57cec5SDimitry Andric   Out << "!DILabel(";
2350349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
23510b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
23520b57cec5SDimitry Andric   Printer.printString("name", N->getName());
23530b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
23540b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
23550b57cec5SDimitry Andric   Out << ")";
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2359349cc55cSDimitry Andric                               AsmWriterContext &WriterCtx) {
23600b57cec5SDimitry Andric   Out << "!DIExpression(";
23610b57cec5SDimitry Andric   FieldSeparator FS;
23620b57cec5SDimitry Andric   if (N->isValid()) {
2363fe6060f1SDimitry Andric     for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2364fe6060f1SDimitry Andric       auto OpStr = dwarf::OperationEncodingString(Op.getOp());
23650b57cec5SDimitry Andric       assert(!OpStr.empty() && "Expected valid opcode");
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric       Out << FS << OpStr;
2368fe6060f1SDimitry Andric       if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2369fe6060f1SDimitry Andric         Out << FS << Op.getArg(0);
2370fe6060f1SDimitry Andric         Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
23710b57cec5SDimitry Andric       } else {
2372fe6060f1SDimitry Andric         for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2373fe6060f1SDimitry Andric           Out << FS << Op.getArg(A);
23740b57cec5SDimitry Andric       }
23750b57cec5SDimitry Andric     }
23760b57cec5SDimitry Andric   } else {
23770b57cec5SDimitry Andric     for (const auto &I : N->getElements())
23780b57cec5SDimitry Andric       Out << FS << I;
23790b57cec5SDimitry Andric   }
23800b57cec5SDimitry Andric   Out << ")";
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric 
2383fe6060f1SDimitry Andric static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2384349cc55cSDimitry Andric                            AsmWriterContext &WriterCtx,
2385349cc55cSDimitry Andric                            bool FromValue = false) {
2386fe6060f1SDimitry Andric   assert(FromValue &&
2387fe6060f1SDimitry Andric          "Unexpected DIArgList metadata outside of value argument");
2388fe6060f1SDimitry Andric   Out << "!DIArgList(";
2389fe6060f1SDimitry Andric   FieldSeparator FS;
2390349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
2391fe6060f1SDimitry Andric   for (Metadata *Arg : N->getArgs()) {
2392fe6060f1SDimitry Andric     Out << FS;
2393349cc55cSDimitry Andric     WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2394fe6060f1SDimitry Andric   }
2395fe6060f1SDimitry Andric   Out << ")";
2396fe6060f1SDimitry Andric }
2397fe6060f1SDimitry Andric 
23980b57cec5SDimitry Andric static void writeDIGlobalVariableExpression(raw_ostream &Out,
23990b57cec5SDimitry Andric                                             const DIGlobalVariableExpression *N,
2400349cc55cSDimitry Andric                                             AsmWriterContext &WriterCtx) {
24010b57cec5SDimitry Andric   Out << "!DIGlobalVariableExpression(";
2402349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24030b57cec5SDimitry Andric   Printer.printMetadata("var", N->getVariable());
24040b57cec5SDimitry Andric   Printer.printMetadata("expr", N->getExpression());
24050b57cec5SDimitry Andric   Out << ")";
24060b57cec5SDimitry Andric }
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2409349cc55cSDimitry Andric                                 AsmWriterContext &WriterCtx) {
24100b57cec5SDimitry Andric   Out << "!DIObjCProperty(";
2411349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24120b57cec5SDimitry Andric   Printer.printString("name", N->getName());
24130b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
24140b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
24150b57cec5SDimitry Andric   Printer.printString("setter", N->getSetterName());
24160b57cec5SDimitry Andric   Printer.printString("getter", N->getGetterName());
24170b57cec5SDimitry Andric   Printer.printInt("attributes", N->getAttributes());
24180b57cec5SDimitry Andric   Printer.printMetadata("type", N->getRawType());
24190b57cec5SDimitry Andric   Out << ")";
24200b57cec5SDimitry Andric }
24210b57cec5SDimitry Andric 
24220b57cec5SDimitry Andric static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2423349cc55cSDimitry Andric                                   AsmWriterContext &WriterCtx) {
24240b57cec5SDimitry Andric   Out << "!DIImportedEntity(";
2425349cc55cSDimitry Andric   MDFieldPrinter Printer(Out, WriterCtx);
24260b57cec5SDimitry Andric   Printer.printTag(N);
24270b57cec5SDimitry Andric   Printer.printString("name", N->getName());
24280b57cec5SDimitry Andric   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
24290b57cec5SDimitry Andric   Printer.printMetadata("entity", N->getRawEntity());
24300b57cec5SDimitry Andric   Printer.printMetadata("file", N->getRawFile());
24310b57cec5SDimitry Andric   Printer.printInt("line", N->getLine());
2432349cc55cSDimitry Andric   Printer.printMetadata("elements", N->getRawElements());
24330b57cec5SDimitry Andric   Out << ")";
24340b57cec5SDimitry Andric }
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2437349cc55cSDimitry Andric                                     AsmWriterContext &Ctx) {
24380b57cec5SDimitry Andric   if (Node->isDistinct())
24390b57cec5SDimitry Andric     Out << "distinct ";
24400b57cec5SDimitry Andric   else if (Node->isTemporary())
24410b57cec5SDimitry Andric     Out << "<temporary!> "; // Handle broken code.
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric   switch (Node->getMetadataID()) {
24440b57cec5SDimitry Andric   default:
24450b57cec5SDimitry Andric     llvm_unreachable("Expected uniquable MDNode");
24460b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF(CLASS)                                              \
24470b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
2448349cc55cSDimitry Andric     write##CLASS(Out, cast<CLASS>(Node), Ctx);                                 \
24490b57cec5SDimitry Andric     break;
24500b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
24510b57cec5SDimitry Andric   }
24520b57cec5SDimitry Andric }
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric // Full implementation of printing a Value as an operand with support for
24550b57cec5SDimitry Andric // TypePrinting, etc.
24560b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2457349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx) {
24580b57cec5SDimitry Andric   if (V->hasName()) {
24590b57cec5SDimitry Andric     PrintLLVMName(Out, V);
24600b57cec5SDimitry Andric     return;
24610b57cec5SDimitry Andric   }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric   const Constant *CV = dyn_cast<Constant>(V);
24640b57cec5SDimitry Andric   if (CV && !isa<GlobalValue>(CV)) {
2465349cc55cSDimitry Andric     assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2466349cc55cSDimitry Andric     WriteConstantInternal(Out, CV, WriterCtx);
24670b57cec5SDimitry Andric     return;
24680b57cec5SDimitry Andric   }
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
24710b57cec5SDimitry Andric     Out << "asm ";
24720b57cec5SDimitry Andric     if (IA->hasSideEffects())
24730b57cec5SDimitry Andric       Out << "sideeffect ";
24740b57cec5SDimitry Andric     if (IA->isAlignStack())
24750b57cec5SDimitry Andric       Out << "alignstack ";
24760b57cec5SDimitry Andric     // We don't emit the AD_ATT dialect as it's the assumed default.
24770b57cec5SDimitry Andric     if (IA->getDialect() == InlineAsm::AD_Intel)
24780b57cec5SDimitry Andric       Out << "inteldialect ";
2479fe6060f1SDimitry Andric     if (IA->canThrow())
2480fe6060f1SDimitry Andric       Out << "unwind ";
24810b57cec5SDimitry Andric     Out << '"';
24820b57cec5SDimitry Andric     printEscapedString(IA->getAsmString(), Out);
24830b57cec5SDimitry Andric     Out << "\", \"";
24840b57cec5SDimitry Andric     printEscapedString(IA->getConstraintString(), Out);
24850b57cec5SDimitry Andric     Out << '"';
24860b57cec5SDimitry Andric     return;
24870b57cec5SDimitry Andric   }
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2490349cc55cSDimitry Andric     WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx,
2491349cc55cSDimitry Andric                            /* FromValue */ true);
24920b57cec5SDimitry Andric     return;
24930b57cec5SDimitry Andric   }
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   char Prefix = '%';
24960b57cec5SDimitry Andric   int Slot;
2497349cc55cSDimitry Andric   auto *Machine = WriterCtx.Machine;
24980b57cec5SDimitry Andric   // If we have a SlotTracker, use it.
24990b57cec5SDimitry Andric   if (Machine) {
25000b57cec5SDimitry Andric     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
25010b57cec5SDimitry Andric       Slot = Machine->getGlobalSlot(GV);
25020b57cec5SDimitry Andric       Prefix = '@';
25030b57cec5SDimitry Andric     } else {
25040b57cec5SDimitry Andric       Slot = Machine->getLocalSlot(V);
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric       // If the local value didn't succeed, then we may be referring to a value
25070b57cec5SDimitry Andric       // from a different function.  Translate it, as this can happen when using
25080b57cec5SDimitry Andric       // address of blocks.
25090b57cec5SDimitry Andric       if (Slot == -1)
25100b57cec5SDimitry Andric         if ((Machine = createSlotTracker(V))) {
25110b57cec5SDimitry Andric           Slot = Machine->getLocalSlot(V);
25120b57cec5SDimitry Andric           delete Machine;
25130b57cec5SDimitry Andric         }
25140b57cec5SDimitry Andric     }
25150b57cec5SDimitry Andric   } else if ((Machine = createSlotTracker(V))) {
25160b57cec5SDimitry Andric     // Otherwise, create one to get the # and then destroy it.
25170b57cec5SDimitry Andric     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
25180b57cec5SDimitry Andric       Slot = Machine->getGlobalSlot(GV);
25190b57cec5SDimitry Andric       Prefix = '@';
25200b57cec5SDimitry Andric     } else {
25210b57cec5SDimitry Andric       Slot = Machine->getLocalSlot(V);
25220b57cec5SDimitry Andric     }
25230b57cec5SDimitry Andric     delete Machine;
25240b57cec5SDimitry Andric     Machine = nullptr;
25250b57cec5SDimitry Andric   } else {
25260b57cec5SDimitry Andric     Slot = -1;
25270b57cec5SDimitry Andric   }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric   if (Slot != -1)
25300b57cec5SDimitry Andric     Out << Prefix << Slot;
25310b57cec5SDimitry Andric   else
25320b57cec5SDimitry Andric     Out << "<badref>";
25330b57cec5SDimitry Andric }
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2536349cc55cSDimitry Andric                                    AsmWriterContext &WriterCtx,
25370b57cec5SDimitry Andric                                    bool FromValue) {
2538fe6060f1SDimitry Andric   // Write DIExpressions and DIArgLists inline when used as a value. Improves
2539fe6060f1SDimitry Andric   // readability of debug info intrinsics.
25400b57cec5SDimitry Andric   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2541349cc55cSDimitry Andric     writeDIExpression(Out, Expr, WriterCtx);
25420b57cec5SDimitry Andric     return;
25430b57cec5SDimitry Andric   }
2544fe6060f1SDimitry Andric   if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2545349cc55cSDimitry Andric     writeDIArgList(Out, ArgList, WriterCtx, FromValue);
2546fe6060f1SDimitry Andric     return;
2547fe6060f1SDimitry Andric   }
25480b57cec5SDimitry Andric 
25490b57cec5SDimitry Andric   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
25500b57cec5SDimitry Andric     std::unique_ptr<SlotTracker> MachineStorage;
2551bdd1243dSDimitry Andric     SaveAndRestore SARMachine(WriterCtx.Machine);
2552349cc55cSDimitry Andric     if (!WriterCtx.Machine) {
2553349cc55cSDimitry Andric       MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2554349cc55cSDimitry Andric       WriterCtx.Machine = MachineStorage.get();
25550b57cec5SDimitry Andric     }
2556349cc55cSDimitry Andric     int Slot = WriterCtx.Machine->getMetadataSlot(N);
25570b57cec5SDimitry Andric     if (Slot == -1) {
25580b57cec5SDimitry Andric       if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2559349cc55cSDimitry Andric         writeDILocation(Out, Loc, WriterCtx);
25600b57cec5SDimitry Andric         return;
25610b57cec5SDimitry Andric       }
25620b57cec5SDimitry Andric       // Give the pointer value instead of "badref", since this comes up all
25630b57cec5SDimitry Andric       // the time when debugging.
25640b57cec5SDimitry Andric       Out << "<" << N << ">";
25650b57cec5SDimitry Andric     } else
25660b57cec5SDimitry Andric       Out << '!' << Slot;
25670b57cec5SDimitry Andric     return;
25680b57cec5SDimitry Andric   }
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
25710b57cec5SDimitry Andric     Out << "!\"";
25720b57cec5SDimitry Andric     printEscapedString(MDS->getString(), Out);
25730b57cec5SDimitry Andric     Out << '"';
25740b57cec5SDimitry Andric     return;
25750b57cec5SDimitry Andric   }
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric   auto *V = cast<ValueAsMetadata>(MD);
2578349cc55cSDimitry Andric   assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values");
25790b57cec5SDimitry Andric   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
25800b57cec5SDimitry Andric          "Unexpected function-local metadata outside of value argument");
25810b57cec5SDimitry Andric 
2582349cc55cSDimitry Andric   WriterCtx.TypePrinter->print(V->getValue()->getType(), Out);
25830b57cec5SDimitry Andric   Out << ' ';
2584349cc55cSDimitry Andric   WriteAsOperandInternal(Out, V->getValue(), WriterCtx);
25850b57cec5SDimitry Andric }
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric namespace {
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric class AssemblyWriter {
25900b57cec5SDimitry Andric   formatted_raw_ostream &Out;
25910b57cec5SDimitry Andric   const Module *TheModule = nullptr;
25920b57cec5SDimitry Andric   const ModuleSummaryIndex *TheIndex = nullptr;
25930b57cec5SDimitry Andric   std::unique_ptr<SlotTracker> SlotTrackerStorage;
25940b57cec5SDimitry Andric   SlotTracker &Machine;
25950b57cec5SDimitry Andric   TypePrinting TypePrinter;
25960b57cec5SDimitry Andric   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
25970b57cec5SDimitry Andric   SetVector<const Comdat *> Comdats;
25980b57cec5SDimitry Andric   bool IsForDebug;
25990b57cec5SDimitry Andric   bool ShouldPreserveUseListOrder;
2600fe6060f1SDimitry Andric   UseListOrderMap UseListOrders;
26010b57cec5SDimitry Andric   SmallVector<StringRef, 8> MDNames;
26020b57cec5SDimitry Andric   /// Synchronization scope names registered with LLVMContext.
26030b57cec5SDimitry Andric   SmallVector<StringRef, 8> SSNs;
26040b57cec5SDimitry Andric   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric public:
26070b57cec5SDimitry Andric   /// Construct an AssemblyWriter with an external SlotTracker
26080b57cec5SDimitry Andric   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
26090b57cec5SDimitry Andric                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
26100b57cec5SDimitry Andric                  bool ShouldPreserveUseListOrder = false);
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
26130b57cec5SDimitry Andric                  const ModuleSummaryIndex *Index, bool IsForDebug);
26140b57cec5SDimitry Andric 
2615349cc55cSDimitry Andric   AsmWriterContext getContext() {
2616349cc55cSDimitry Andric     return AsmWriterContext(&TypePrinter, &Machine, TheModule);
2617349cc55cSDimitry Andric   }
2618349cc55cSDimitry Andric 
26190b57cec5SDimitry Andric   void printMDNodeBody(const MDNode *MD);
26200b57cec5SDimitry Andric   void printNamedMDNode(const NamedMDNode *NMD);
26210b57cec5SDimitry Andric 
26220b57cec5SDimitry Andric   void printModule(const Module *M);
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric   void writeOperand(const Value *Op, bool PrintType);
26250b57cec5SDimitry Andric   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
26260b57cec5SDimitry Andric   void writeOperandBundles(const CallBase *Call);
26270b57cec5SDimitry Andric   void writeSyncScope(const LLVMContext &Context,
26280b57cec5SDimitry Andric                       SyncScope::ID SSID);
26290b57cec5SDimitry Andric   void writeAtomic(const LLVMContext &Context,
26300b57cec5SDimitry Andric                    AtomicOrdering Ordering,
26310b57cec5SDimitry Andric                    SyncScope::ID SSID);
26320b57cec5SDimitry Andric   void writeAtomicCmpXchg(const LLVMContext &Context,
26330b57cec5SDimitry Andric                           AtomicOrdering SuccessOrdering,
26340b57cec5SDimitry Andric                           AtomicOrdering FailureOrdering,
26350b57cec5SDimitry Andric                           SyncScope::ID SSID);
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   void writeAllMDNodes();
26380b57cec5SDimitry Andric   void writeMDNode(unsigned Slot, const MDNode *Node);
2639480093f4SDimitry Andric   void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2640480093f4SDimitry Andric   void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
26410b57cec5SDimitry Andric   void writeAllAttributeGroups();
26420b57cec5SDimitry Andric 
26430b57cec5SDimitry Andric   void printTypeIdentities();
26440b57cec5SDimitry Andric   void printGlobal(const GlobalVariable *GV);
2645349cc55cSDimitry Andric   void printAlias(const GlobalAlias *GA);
2646349cc55cSDimitry Andric   void printIFunc(const GlobalIFunc *GI);
26470b57cec5SDimitry Andric   void printComdat(const Comdat *C);
26480b57cec5SDimitry Andric   void printFunction(const Function *F);
26490b57cec5SDimitry Andric   void printArgument(const Argument *FA, AttributeSet Attrs);
26500b57cec5SDimitry Andric   void printBasicBlock(const BasicBlock *BB);
26510b57cec5SDimitry Andric   void printInstructionLine(const Instruction &I);
26520b57cec5SDimitry Andric   void printInstruction(const Instruction &I);
2653*5f757f3fSDimitry Andric   void printDPMarker(const DPMarker &DPI);
2654*5f757f3fSDimitry Andric   void printDPValue(const DPValue &DPI);
26550b57cec5SDimitry Andric 
2656fe6060f1SDimitry Andric   void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle);
26570b57cec5SDimitry Andric   void printUseLists(const Function *F);
26580b57cec5SDimitry Andric 
26590b57cec5SDimitry Andric   void printModuleSummaryIndex();
26600b57cec5SDimitry Andric   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
26610b57cec5SDimitry Andric   void printSummary(const GlobalValueSummary &Summary);
26620b57cec5SDimitry Andric   void printAliasSummary(const AliasSummary *AS);
26630b57cec5SDimitry Andric   void printGlobalVarSummary(const GlobalVarSummary *GS);
26640b57cec5SDimitry Andric   void printFunctionSummary(const FunctionSummary *FS);
26650b57cec5SDimitry Andric   void printTypeIdSummary(const TypeIdSummary &TIS);
26660b57cec5SDimitry Andric   void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
26670b57cec5SDimitry Andric   void printTypeTestResolution(const TypeTestResolution &TTRes);
26680b57cec5SDimitry Andric   void printArgs(const std::vector<uint64_t> &Args);
26690b57cec5SDimitry Andric   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
26700b57cec5SDimitry Andric   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
26710b57cec5SDimitry Andric   void printVFuncId(const FunctionSummary::VFuncId VFId);
26720b57cec5SDimitry Andric   void
26735ffd83dbSDimitry Andric   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
26740b57cec5SDimitry Andric                       const char *Tag);
26750b57cec5SDimitry Andric   void
26765ffd83dbSDimitry Andric   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
26770b57cec5SDimitry Andric                    const char *Tag);
26780b57cec5SDimitry Andric 
26790b57cec5SDimitry Andric private:
26800b57cec5SDimitry Andric   /// Print out metadata attachments.
26810b57cec5SDimitry Andric   void printMetadataAttachments(
26820b57cec5SDimitry Andric       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
26830b57cec5SDimitry Andric       StringRef Separator);
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric   // printInfoComment - Print a little comment after the instruction indicating
26860b57cec5SDimitry Andric   // which slot it occupies.
26870b57cec5SDimitry Andric   void printInfoComment(const Value &V);
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric   // printGCRelocateComment - print comment after call to the gc.relocate
26900b57cec5SDimitry Andric   // intrinsic indicating base and derived pointer names.
26910b57cec5SDimitry Andric   void printGCRelocateComment(const GCRelocateInst &Relocate);
26920b57cec5SDimitry Andric };
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric } // end anonymous namespace
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
26970b57cec5SDimitry Andric                                const Module *M, AssemblyAnnotationWriter *AAW,
26980b57cec5SDimitry Andric                                bool IsForDebug, bool ShouldPreserveUseListOrder)
26990b57cec5SDimitry Andric     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
27000b57cec5SDimitry Andric       IsForDebug(IsForDebug),
27010b57cec5SDimitry Andric       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
27020b57cec5SDimitry Andric   if (!TheModule)
27030b57cec5SDimitry Andric     return;
27040b57cec5SDimitry Andric   for (const GlobalObject &GO : TheModule->global_objects())
27050b57cec5SDimitry Andric     if (const Comdat *C = GO.getComdat())
27060b57cec5SDimitry Andric       Comdats.insert(C);
27070b57cec5SDimitry Andric }
27080b57cec5SDimitry Andric 
27090b57cec5SDimitry Andric AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
27100b57cec5SDimitry Andric                                const ModuleSummaryIndex *Index, bool IsForDebug)
27110b57cec5SDimitry Andric     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
27120b57cec5SDimitry Andric       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
27130b57cec5SDimitry Andric 
27140b57cec5SDimitry Andric void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
27150b57cec5SDimitry Andric   if (!Operand) {
27160b57cec5SDimitry Andric     Out << "<null operand!>";
27170b57cec5SDimitry Andric     return;
27180b57cec5SDimitry Andric   }
27190b57cec5SDimitry Andric   if (PrintType) {
27200b57cec5SDimitry Andric     TypePrinter.print(Operand->getType(), Out);
27210b57cec5SDimitry Andric     Out << ' ';
27220b57cec5SDimitry Andric   }
2723349cc55cSDimitry Andric   auto WriterCtx = getContext();
2724349cc55cSDimitry Andric   WriteAsOperandInternal(Out, Operand, WriterCtx);
27250b57cec5SDimitry Andric }
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
27280b57cec5SDimitry Andric                                     SyncScope::ID SSID) {
27290b57cec5SDimitry Andric   switch (SSID) {
27300b57cec5SDimitry Andric   case SyncScope::System: {
27310b57cec5SDimitry Andric     break;
27320b57cec5SDimitry Andric   }
27330b57cec5SDimitry Andric   default: {
27340b57cec5SDimitry Andric     if (SSNs.empty())
27350b57cec5SDimitry Andric       Context.getSyncScopeNames(SSNs);
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric     Out << " syncscope(\"";
27380b57cec5SDimitry Andric     printEscapedString(SSNs[SSID], Out);
27390b57cec5SDimitry Andric     Out << "\")";
27400b57cec5SDimitry Andric     break;
27410b57cec5SDimitry Andric   }
27420b57cec5SDimitry Andric   }
27430b57cec5SDimitry Andric }
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric void AssemblyWriter::writeAtomic(const LLVMContext &Context,
27460b57cec5SDimitry Andric                                  AtomicOrdering Ordering,
27470b57cec5SDimitry Andric                                  SyncScope::ID SSID) {
27480b57cec5SDimitry Andric   if (Ordering == AtomicOrdering::NotAtomic)
27490b57cec5SDimitry Andric     return;
27500b57cec5SDimitry Andric 
27510b57cec5SDimitry Andric   writeSyncScope(Context, SSID);
27520b57cec5SDimitry Andric   Out << " " << toIRString(Ordering);
27530b57cec5SDimitry Andric }
27540b57cec5SDimitry Andric 
27550b57cec5SDimitry Andric void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
27560b57cec5SDimitry Andric                                         AtomicOrdering SuccessOrdering,
27570b57cec5SDimitry Andric                                         AtomicOrdering FailureOrdering,
27580b57cec5SDimitry Andric                                         SyncScope::ID SSID) {
27590b57cec5SDimitry Andric   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
27600b57cec5SDimitry Andric          FailureOrdering != AtomicOrdering::NotAtomic);
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric   writeSyncScope(Context, SSID);
27630b57cec5SDimitry Andric   Out << " " << toIRString(SuccessOrdering);
27640b57cec5SDimitry Andric   Out << " " << toIRString(FailureOrdering);
27650b57cec5SDimitry Andric }
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric void AssemblyWriter::writeParamOperand(const Value *Operand,
27680b57cec5SDimitry Andric                                        AttributeSet Attrs) {
27690b57cec5SDimitry Andric   if (!Operand) {
27700b57cec5SDimitry Andric     Out << "<null operand!>";
27710b57cec5SDimitry Andric     return;
27720b57cec5SDimitry Andric   }
27730b57cec5SDimitry Andric 
27740b57cec5SDimitry Andric   // Print the type
27750b57cec5SDimitry Andric   TypePrinter.print(Operand->getType(), Out);
27760b57cec5SDimitry Andric   // Print parameter attributes list
2777480093f4SDimitry Andric   if (Attrs.hasAttributes()) {
2778480093f4SDimitry Andric     Out << ' ';
2779480093f4SDimitry Andric     writeAttributeSet(Attrs);
2780480093f4SDimitry Andric   }
27810b57cec5SDimitry Andric   Out << ' ';
27820b57cec5SDimitry Andric   // Print the operand
2783349cc55cSDimitry Andric   auto WriterCtx = getContext();
2784349cc55cSDimitry Andric   WriteAsOperandInternal(Out, Operand, WriterCtx);
27850b57cec5SDimitry Andric }
27860b57cec5SDimitry Andric 
27870b57cec5SDimitry Andric void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
27880b57cec5SDimitry Andric   if (!Call->hasOperandBundles())
27890b57cec5SDimitry Andric     return;
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric   Out << " [ ";
27920b57cec5SDimitry Andric 
27930b57cec5SDimitry Andric   bool FirstBundle = true;
27940b57cec5SDimitry Andric   for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
27950b57cec5SDimitry Andric     OperandBundleUse BU = Call->getOperandBundleAt(i);
27960b57cec5SDimitry Andric 
27970b57cec5SDimitry Andric     if (!FirstBundle)
27980b57cec5SDimitry Andric       Out << ", ";
27990b57cec5SDimitry Andric     FirstBundle = false;
28000b57cec5SDimitry Andric 
28010b57cec5SDimitry Andric     Out << '"';
28020b57cec5SDimitry Andric     printEscapedString(BU.getTagName(), Out);
28030b57cec5SDimitry Andric     Out << '"';
28040b57cec5SDimitry Andric 
28050b57cec5SDimitry Andric     Out << '(';
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric     bool FirstInput = true;
2808349cc55cSDimitry Andric     auto WriterCtx = getContext();
28090b57cec5SDimitry Andric     for (const auto &Input : BU.Inputs) {
28100b57cec5SDimitry Andric       if (!FirstInput)
28110b57cec5SDimitry Andric         Out << ", ";
28120b57cec5SDimitry Andric       FirstInput = false;
28130b57cec5SDimitry Andric 
2814bdd1243dSDimitry Andric       if (Input == nullptr)
2815bdd1243dSDimitry Andric         Out << "<null operand bundle!>";
2816bdd1243dSDimitry Andric       else {
28170b57cec5SDimitry Andric         TypePrinter.print(Input->getType(), Out);
28180b57cec5SDimitry Andric         Out << " ";
2819349cc55cSDimitry Andric         WriteAsOperandInternal(Out, Input, WriterCtx);
28200b57cec5SDimitry Andric       }
2821bdd1243dSDimitry Andric     }
28220b57cec5SDimitry Andric 
28230b57cec5SDimitry Andric     Out << ')';
28240b57cec5SDimitry Andric   }
28250b57cec5SDimitry Andric 
28260b57cec5SDimitry Andric   Out << " ]";
28270b57cec5SDimitry Andric }
28280b57cec5SDimitry Andric 
28290b57cec5SDimitry Andric void AssemblyWriter::printModule(const Module *M) {
28300b57cec5SDimitry Andric   Machine.initializeIfNeeded();
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric   if (ShouldPreserveUseListOrder)
28330b57cec5SDimitry Andric     UseListOrders = predictUseListOrder(M);
28340b57cec5SDimitry Andric 
28350b57cec5SDimitry Andric   if (!M->getModuleIdentifier().empty() &&
28360b57cec5SDimitry Andric       // Don't print the ID if it will start a new line (which would
28370b57cec5SDimitry Andric       // require a comment char before it).
28380b57cec5SDimitry Andric       M->getModuleIdentifier().find('\n') == std::string::npos)
28390b57cec5SDimitry Andric     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
28400b57cec5SDimitry Andric 
28410b57cec5SDimitry Andric   if (!M->getSourceFileName().empty()) {
28420b57cec5SDimitry Andric     Out << "source_filename = \"";
28430b57cec5SDimitry Andric     printEscapedString(M->getSourceFileName(), Out);
28440b57cec5SDimitry Andric     Out << "\"\n";
28450b57cec5SDimitry Andric   }
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   const std::string &DL = M->getDataLayoutStr();
28480b57cec5SDimitry Andric   if (!DL.empty())
28490b57cec5SDimitry Andric     Out << "target datalayout = \"" << DL << "\"\n";
28500b57cec5SDimitry Andric   if (!M->getTargetTriple().empty())
28510b57cec5SDimitry Andric     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   if (!M->getModuleInlineAsm().empty()) {
28540b57cec5SDimitry Andric     Out << '\n';
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric     // Split the string into lines, to make it easier to read the .ll file.
28570b57cec5SDimitry Andric     StringRef Asm = M->getModuleInlineAsm();
28580b57cec5SDimitry Andric     do {
28590b57cec5SDimitry Andric       StringRef Front;
28600b57cec5SDimitry Andric       std::tie(Front, Asm) = Asm.split('\n');
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric       // We found a newline, print the portion of the asm string from the
28630b57cec5SDimitry Andric       // last newline up to this newline.
28640b57cec5SDimitry Andric       Out << "module asm \"";
28650b57cec5SDimitry Andric       printEscapedString(Front, Out);
28660b57cec5SDimitry Andric       Out << "\"\n";
28670b57cec5SDimitry Andric     } while (!Asm.empty());
28680b57cec5SDimitry Andric   }
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric   printTypeIdentities();
28710b57cec5SDimitry Andric 
28720b57cec5SDimitry Andric   // Output all comdats.
28730b57cec5SDimitry Andric   if (!Comdats.empty())
28740b57cec5SDimitry Andric     Out << '\n';
28750b57cec5SDimitry Andric   for (const Comdat *C : Comdats) {
28760b57cec5SDimitry Andric     printComdat(C);
28770b57cec5SDimitry Andric     if (C != Comdats.back())
28780b57cec5SDimitry Andric       Out << '\n';
28790b57cec5SDimitry Andric   }
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric   // Output all globals.
28820b57cec5SDimitry Andric   if (!M->global_empty()) Out << '\n';
28830b57cec5SDimitry Andric   for (const GlobalVariable &GV : M->globals()) {
28840b57cec5SDimitry Andric     printGlobal(&GV); Out << '\n';
28850b57cec5SDimitry Andric   }
28860b57cec5SDimitry Andric 
28870b57cec5SDimitry Andric   // Output all aliases.
28880b57cec5SDimitry Andric   if (!M->alias_empty()) Out << "\n";
28890b57cec5SDimitry Andric   for (const GlobalAlias &GA : M->aliases())
2890349cc55cSDimitry Andric     printAlias(&GA);
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric   // Output all ifuncs.
28930b57cec5SDimitry Andric   if (!M->ifunc_empty()) Out << "\n";
28940b57cec5SDimitry Andric   for (const GlobalIFunc &GI : M->ifuncs())
2895349cc55cSDimitry Andric     printIFunc(&GI);
28960b57cec5SDimitry Andric 
28970b57cec5SDimitry Andric   // Output all of the functions.
289813138422SDimitry Andric   for (const Function &F : *M) {
289913138422SDimitry Andric     Out << '\n';
29000b57cec5SDimitry Andric     printFunction(&F);
290113138422SDimitry Andric   }
2902fe6060f1SDimitry Andric 
2903fe6060f1SDimitry Andric   // Output global use-lists.
2904fe6060f1SDimitry Andric   printUseLists(nullptr);
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric   // Output all attribute groups.
29070b57cec5SDimitry Andric   if (!Machine.as_empty()) {
29080b57cec5SDimitry Andric     Out << '\n';
29090b57cec5SDimitry Andric     writeAllAttributeGroups();
29100b57cec5SDimitry Andric   }
29110b57cec5SDimitry Andric 
29120b57cec5SDimitry Andric   // Output named metadata.
29130b57cec5SDimitry Andric   if (!M->named_metadata_empty()) Out << '\n';
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric   for (const NamedMDNode &Node : M->named_metadata())
29160b57cec5SDimitry Andric     printNamedMDNode(&Node);
29170b57cec5SDimitry Andric 
29180b57cec5SDimitry Andric   // Output metadata.
29190b57cec5SDimitry Andric   if (!Machine.mdn_empty()) {
29200b57cec5SDimitry Andric     Out << '\n';
29210b57cec5SDimitry Andric     writeAllMDNodes();
29220b57cec5SDimitry Andric   }
29230b57cec5SDimitry Andric }
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric void AssemblyWriter::printModuleSummaryIndex() {
29260b57cec5SDimitry Andric   assert(TheIndex);
29275ffd83dbSDimitry Andric   int NumSlots = Machine.initializeIndexIfNeeded();
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   Out << "\n";
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric   // Print module path entries. To print in order, add paths to a vector
29320b57cec5SDimitry Andric   // indexed by module slot.
29330b57cec5SDimitry Andric   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
29345ffd83dbSDimitry Andric   std::string RegularLTOModuleName =
29355ffd83dbSDimitry Andric       ModuleSummaryIndex::getRegularLTOModuleName();
29360b57cec5SDimitry Andric   moduleVec.resize(TheIndex->modulePaths().size());
2937*5f757f3fSDimitry Andric   for (auto &[ModPath, ModHash] : TheIndex->modulePaths())
2938bdd1243dSDimitry Andric     moduleVec[Machine.getModulePathSlot(ModPath)] = std::make_pair(
2939*5f757f3fSDimitry Andric         // An empty module path is a special entry for a regular LTO module
2940*5f757f3fSDimitry Andric         // created during the thin link.
2941*5f757f3fSDimitry Andric         ModPath.empty() ? RegularLTOModuleName : std::string(ModPath), ModHash);
29420b57cec5SDimitry Andric 
29430b57cec5SDimitry Andric   unsigned i = 0;
29440b57cec5SDimitry Andric   for (auto &ModPair : moduleVec) {
29450b57cec5SDimitry Andric     Out << "^" << i++ << " = module: (";
29460b57cec5SDimitry Andric     Out << "path: \"";
29470b57cec5SDimitry Andric     printEscapedString(ModPair.first, Out);
29480b57cec5SDimitry Andric     Out << "\", hash: (";
29490b57cec5SDimitry Andric     FieldSeparator FS;
29500b57cec5SDimitry Andric     for (auto Hash : ModPair.second)
29510b57cec5SDimitry Andric       Out << FS << Hash;
29520b57cec5SDimitry Andric     Out << "))\n";
29530b57cec5SDimitry Andric   }
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
29560b57cec5SDimitry Andric   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
29570b57cec5SDimitry Andric   for (auto &GlobalList : *TheIndex) {
29580b57cec5SDimitry Andric     auto GUID = GlobalList.first;
29590b57cec5SDimitry Andric     for (auto &Summary : GlobalList.second.SummaryList)
29600b57cec5SDimitry Andric       SummaryToGUIDMap[Summary.get()] = GUID;
29610b57cec5SDimitry Andric   }
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric   // Print the global value summary entries.
29640b57cec5SDimitry Andric   for (auto &GlobalList : *TheIndex) {
29650b57cec5SDimitry Andric     auto GUID = GlobalList.first;
29660b57cec5SDimitry Andric     auto VI = TheIndex->getValueInfo(GlobalList);
29670b57cec5SDimitry Andric     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
29680b57cec5SDimitry Andric   }
29690b57cec5SDimitry Andric 
29700b57cec5SDimitry Andric   // Print the TypeIdMap entries.
2971fe6060f1SDimitry Andric   for (const auto &TID : TheIndex->typeIds()) {
2972fe6060f1SDimitry Andric     Out << "^" << Machine.getTypeIdSlot(TID.second.first)
2973fe6060f1SDimitry Andric         << " = typeid: (name: \"" << TID.second.first << "\"";
2974fe6060f1SDimitry Andric     printTypeIdSummary(TID.second.second);
2975fe6060f1SDimitry Andric     Out << ") ; guid = " << TID.first << "\n";
29760b57cec5SDimitry Andric   }
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric   // Print the TypeIdCompatibleVtableMap entries.
29790b57cec5SDimitry Andric   for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
29800b57cec5SDimitry Andric     auto GUID = GlobalValue::getGUID(TId.first);
2981*5f757f3fSDimitry Andric     Out << "^" << Machine.getTypeIdCompatibleVtableSlot(TId.first)
29820b57cec5SDimitry Andric         << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
29830b57cec5SDimitry Andric     printTypeIdCompatibleVtableSummary(TId.second);
29840b57cec5SDimitry Andric     Out << ") ; guid = " << GUID << "\n";
29850b57cec5SDimitry Andric   }
29865ffd83dbSDimitry Andric 
29875ffd83dbSDimitry Andric   // Don't emit flags when it's not really needed (value is zero by default).
29885ffd83dbSDimitry Andric   if (TheIndex->getFlags()) {
29895ffd83dbSDimitry Andric     Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
29905ffd83dbSDimitry Andric     ++NumSlots;
29915ffd83dbSDimitry Andric   }
29925ffd83dbSDimitry Andric 
29935ffd83dbSDimitry Andric   Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
29945ffd83dbSDimitry Andric       << "\n";
29950b57cec5SDimitry Andric }
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric static const char *
29980b57cec5SDimitry Andric getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
29990b57cec5SDimitry Andric   switch (K) {
30000b57cec5SDimitry Andric   case WholeProgramDevirtResolution::Indir:
30010b57cec5SDimitry Andric     return "indir";
30020b57cec5SDimitry Andric   case WholeProgramDevirtResolution::SingleImpl:
30030b57cec5SDimitry Andric     return "singleImpl";
30040b57cec5SDimitry Andric   case WholeProgramDevirtResolution::BranchFunnel:
30050b57cec5SDimitry Andric     return "branchFunnel";
30060b57cec5SDimitry Andric   }
30070b57cec5SDimitry Andric   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
30080b57cec5SDimitry Andric }
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric static const char *getWholeProgDevirtResByArgKindName(
30110b57cec5SDimitry Andric     WholeProgramDevirtResolution::ByArg::Kind K) {
30120b57cec5SDimitry Andric   switch (K) {
30130b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::Indir:
30140b57cec5SDimitry Andric     return "indir";
30150b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
30160b57cec5SDimitry Andric     return "uniformRetVal";
30170b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
30180b57cec5SDimitry Andric     return "uniqueRetVal";
30190b57cec5SDimitry Andric   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
30200b57cec5SDimitry Andric     return "virtualConstProp";
30210b57cec5SDimitry Andric   }
30220b57cec5SDimitry Andric   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
30230b57cec5SDimitry Andric }
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric static const char *getTTResKindName(TypeTestResolution::Kind K) {
30260b57cec5SDimitry Andric   switch (K) {
30275ffd83dbSDimitry Andric   case TypeTestResolution::Unknown:
30285ffd83dbSDimitry Andric     return "unknown";
30290b57cec5SDimitry Andric   case TypeTestResolution::Unsat:
30300b57cec5SDimitry Andric     return "unsat";
30310b57cec5SDimitry Andric   case TypeTestResolution::ByteArray:
30320b57cec5SDimitry Andric     return "byteArray";
30330b57cec5SDimitry Andric   case TypeTestResolution::Inline:
30340b57cec5SDimitry Andric     return "inline";
30350b57cec5SDimitry Andric   case TypeTestResolution::Single:
30360b57cec5SDimitry Andric     return "single";
30370b57cec5SDimitry Andric   case TypeTestResolution::AllOnes:
30380b57cec5SDimitry Andric     return "allOnes";
30390b57cec5SDimitry Andric   }
30400b57cec5SDimitry Andric   llvm_unreachable("invalid TypeTestResolution kind");
30410b57cec5SDimitry Andric }
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
30440b57cec5SDimitry Andric   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
30450b57cec5SDimitry Andric       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
30460b57cec5SDimitry Andric 
30470b57cec5SDimitry Andric   // The following fields are only used if the target does not support the use
30480b57cec5SDimitry Andric   // of absolute symbols to store constants. Print only if non-zero.
30490b57cec5SDimitry Andric   if (TTRes.AlignLog2)
30500b57cec5SDimitry Andric     Out << ", alignLog2: " << TTRes.AlignLog2;
30510b57cec5SDimitry Andric   if (TTRes.SizeM1)
30520b57cec5SDimitry Andric     Out << ", sizeM1: " << TTRes.SizeM1;
30530b57cec5SDimitry Andric   if (TTRes.BitMask)
30540b57cec5SDimitry Andric     // BitMask is uint8_t which causes it to print the corresponding char.
30550b57cec5SDimitry Andric     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
30560b57cec5SDimitry Andric   if (TTRes.InlineBits)
30570b57cec5SDimitry Andric     Out << ", inlineBits: " << TTRes.InlineBits;
30580b57cec5SDimitry Andric 
30590b57cec5SDimitry Andric   Out << ")";
30600b57cec5SDimitry Andric }
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
30630b57cec5SDimitry Andric   Out << ", summary: (";
30640b57cec5SDimitry Andric   printTypeTestResolution(TIS.TTRes);
30650b57cec5SDimitry Andric   if (!TIS.WPDRes.empty()) {
30660b57cec5SDimitry Andric     Out << ", wpdResolutions: (";
30670b57cec5SDimitry Andric     FieldSeparator FS;
30680b57cec5SDimitry Andric     for (auto &WPDRes : TIS.WPDRes) {
30690b57cec5SDimitry Andric       Out << FS;
30700b57cec5SDimitry Andric       Out << "(offset: " << WPDRes.first << ", ";
30710b57cec5SDimitry Andric       printWPDRes(WPDRes.second);
30720b57cec5SDimitry Andric       Out << ")";
30730b57cec5SDimitry Andric     }
30740b57cec5SDimitry Andric     Out << ")";
30750b57cec5SDimitry Andric   }
30760b57cec5SDimitry Andric   Out << ")";
30770b57cec5SDimitry Andric }
30780b57cec5SDimitry Andric 
30790b57cec5SDimitry Andric void AssemblyWriter::printTypeIdCompatibleVtableSummary(
30800b57cec5SDimitry Andric     const TypeIdCompatibleVtableInfo &TI) {
30810b57cec5SDimitry Andric   Out << ", summary: (";
30820b57cec5SDimitry Andric   FieldSeparator FS;
30830b57cec5SDimitry Andric   for (auto &P : TI) {
30840b57cec5SDimitry Andric     Out << FS;
30850b57cec5SDimitry Andric     Out << "(offset: " << P.AddressPointOffset << ", ";
30860b57cec5SDimitry Andric     Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
30870b57cec5SDimitry Andric     Out << ")";
30880b57cec5SDimitry Andric   }
30890b57cec5SDimitry Andric   Out << ")";
30900b57cec5SDimitry Andric }
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
30930b57cec5SDimitry Andric   Out << "args: (";
30940b57cec5SDimitry Andric   FieldSeparator FS;
30950b57cec5SDimitry Andric   for (auto arg : Args) {
30960b57cec5SDimitry Andric     Out << FS;
30970b57cec5SDimitry Andric     Out << arg;
30980b57cec5SDimitry Andric   }
30990b57cec5SDimitry Andric   Out << ")";
31000b57cec5SDimitry Andric }
31010b57cec5SDimitry Andric 
31020b57cec5SDimitry Andric void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
31030b57cec5SDimitry Andric   Out << "wpdRes: (kind: ";
31040b57cec5SDimitry Andric   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
31050b57cec5SDimitry Andric 
31060b57cec5SDimitry Andric   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
31070b57cec5SDimitry Andric     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric   if (!WPDRes.ResByArg.empty()) {
31100b57cec5SDimitry Andric     Out << ", resByArg: (";
31110b57cec5SDimitry Andric     FieldSeparator FS;
31120b57cec5SDimitry Andric     for (auto &ResByArg : WPDRes.ResByArg) {
31130b57cec5SDimitry Andric       Out << FS;
31140b57cec5SDimitry Andric       printArgs(ResByArg.first);
31150b57cec5SDimitry Andric       Out << ", byArg: (kind: ";
31160b57cec5SDimitry Andric       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
31170b57cec5SDimitry Andric       if (ResByArg.second.TheKind ==
31180b57cec5SDimitry Andric               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
31190b57cec5SDimitry Andric           ResByArg.second.TheKind ==
31200b57cec5SDimitry Andric               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
31210b57cec5SDimitry Andric         Out << ", info: " << ResByArg.second.Info;
31220b57cec5SDimitry Andric 
31230b57cec5SDimitry Andric       // The following fields are only used if the target does not support the
31240b57cec5SDimitry Andric       // use of absolute symbols to store constants. Print only if non-zero.
31250b57cec5SDimitry Andric       if (ResByArg.second.Byte || ResByArg.second.Bit)
31260b57cec5SDimitry Andric         Out << ", byte: " << ResByArg.second.Byte
31270b57cec5SDimitry Andric             << ", bit: " << ResByArg.second.Bit;
31280b57cec5SDimitry Andric 
31290b57cec5SDimitry Andric       Out << ")";
31300b57cec5SDimitry Andric     }
31310b57cec5SDimitry Andric     Out << ")";
31320b57cec5SDimitry Andric   }
31330b57cec5SDimitry Andric   Out << ")";
31340b57cec5SDimitry Andric }
31350b57cec5SDimitry Andric 
31360b57cec5SDimitry Andric static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
31370b57cec5SDimitry Andric   switch (SK) {
31380b57cec5SDimitry Andric   case GlobalValueSummary::AliasKind:
31390b57cec5SDimitry Andric     return "alias";
31400b57cec5SDimitry Andric   case GlobalValueSummary::FunctionKind:
31410b57cec5SDimitry Andric     return "function";
31420b57cec5SDimitry Andric   case GlobalValueSummary::GlobalVarKind:
31430b57cec5SDimitry Andric     return "variable";
31440b57cec5SDimitry Andric   }
31450b57cec5SDimitry Andric   llvm_unreachable("invalid summary kind");
31460b57cec5SDimitry Andric }
31470b57cec5SDimitry Andric 
31480b57cec5SDimitry Andric void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
31490b57cec5SDimitry Andric   Out << ", aliasee: ";
31500b57cec5SDimitry Andric   // The indexes emitted for distributed backends may not include the
31510b57cec5SDimitry Andric   // aliasee summary (only if it is being imported directly). Handle
31520b57cec5SDimitry Andric   // that case by just emitting "null" as the aliasee.
31530b57cec5SDimitry Andric   if (AS->hasAliasee())
31540b57cec5SDimitry Andric     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
31550b57cec5SDimitry Andric   else
31560b57cec5SDimitry Andric     Out << "null";
31570b57cec5SDimitry Andric }
31580b57cec5SDimitry Andric 
31590b57cec5SDimitry Andric void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
31600b57cec5SDimitry Andric   auto VTableFuncs = GS->vTableFuncs();
31615ffd83dbSDimitry Andric   Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
31625ffd83dbSDimitry Andric       << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
31635ffd83dbSDimitry Andric       << "constant: " << GS->VarFlags.Constant;
31645ffd83dbSDimitry Andric   if (!VTableFuncs.empty())
31655ffd83dbSDimitry Andric     Out << ", "
31665ffd83dbSDimitry Andric         << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
31675ffd83dbSDimitry Andric   Out << ")";
31685ffd83dbSDimitry Andric 
31690b57cec5SDimitry Andric   if (!VTableFuncs.empty()) {
31700b57cec5SDimitry Andric     Out << ", vTableFuncs: (";
31710b57cec5SDimitry Andric     FieldSeparator FS;
31720b57cec5SDimitry Andric     for (auto &P : VTableFuncs) {
31730b57cec5SDimitry Andric       Out << FS;
31740b57cec5SDimitry Andric       Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
31750b57cec5SDimitry Andric           << ", offset: " << P.VTableOffset;
31760b57cec5SDimitry Andric       Out << ")";
31770b57cec5SDimitry Andric     }
31780b57cec5SDimitry Andric     Out << ")";
31790b57cec5SDimitry Andric   }
31800b57cec5SDimitry Andric }
31810b57cec5SDimitry Andric 
31820b57cec5SDimitry Andric static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
31830b57cec5SDimitry Andric   switch (LT) {
31840b57cec5SDimitry Andric   case GlobalValue::ExternalLinkage:
31850b57cec5SDimitry Andric     return "external";
31860b57cec5SDimitry Andric   case GlobalValue::PrivateLinkage:
31870b57cec5SDimitry Andric     return "private";
31880b57cec5SDimitry Andric   case GlobalValue::InternalLinkage:
31890b57cec5SDimitry Andric     return "internal";
31900b57cec5SDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
31910b57cec5SDimitry Andric     return "linkonce";
31920b57cec5SDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
31930b57cec5SDimitry Andric     return "linkonce_odr";
31940b57cec5SDimitry Andric   case GlobalValue::WeakAnyLinkage:
31950b57cec5SDimitry Andric     return "weak";
31960b57cec5SDimitry Andric   case GlobalValue::WeakODRLinkage:
31970b57cec5SDimitry Andric     return "weak_odr";
31980b57cec5SDimitry Andric   case GlobalValue::CommonLinkage:
31990b57cec5SDimitry Andric     return "common";
32000b57cec5SDimitry Andric   case GlobalValue::AppendingLinkage:
32010b57cec5SDimitry Andric     return "appending";
32020b57cec5SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
32030b57cec5SDimitry Andric     return "extern_weak";
32040b57cec5SDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
32050b57cec5SDimitry Andric     return "available_externally";
32060b57cec5SDimitry Andric   }
32070b57cec5SDimitry Andric   llvm_unreachable("invalid linkage");
32080b57cec5SDimitry Andric }
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric // When printing the linkage types in IR where the ExternalLinkage is
32110b57cec5SDimitry Andric // not printed, and other linkage types are expected to be printed with
32120b57cec5SDimitry Andric // a space after the name.
32130b57cec5SDimitry Andric static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
32140b57cec5SDimitry Andric   if (LT == GlobalValue::ExternalLinkage)
32150b57cec5SDimitry Andric     return "";
32160b57cec5SDimitry Andric   return getLinkageName(LT) + " ";
32170b57cec5SDimitry Andric }
32180b57cec5SDimitry Andric 
3219fe6060f1SDimitry Andric static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) {
3220fe6060f1SDimitry Andric   switch (Vis) {
3221fe6060f1SDimitry Andric   case GlobalValue::DefaultVisibility:
3222fe6060f1SDimitry Andric     return "default";
3223fe6060f1SDimitry Andric   case GlobalValue::HiddenVisibility:
3224fe6060f1SDimitry Andric     return "hidden";
3225fe6060f1SDimitry Andric   case GlobalValue::ProtectedVisibility:
3226fe6060f1SDimitry Andric     return "protected";
3227fe6060f1SDimitry Andric   }
3228fe6060f1SDimitry Andric   llvm_unreachable("invalid visibility");
3229fe6060f1SDimitry Andric }
3230fe6060f1SDimitry Andric 
32310b57cec5SDimitry Andric void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
32320b57cec5SDimitry Andric   Out << ", insts: " << FS->instCount();
3233349cc55cSDimitry Andric   if (FS->fflags().anyFlagSet())
3234349cc55cSDimitry Andric     Out << ", " << FS->fflags();
32350b57cec5SDimitry Andric 
32360b57cec5SDimitry Andric   if (!FS->calls().empty()) {
32370b57cec5SDimitry Andric     Out << ", calls: (";
32380b57cec5SDimitry Andric     FieldSeparator IFS;
32390b57cec5SDimitry Andric     for (auto &Call : FS->calls()) {
32400b57cec5SDimitry Andric       Out << IFS;
32410b57cec5SDimitry Andric       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
32420b57cec5SDimitry Andric       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
32430b57cec5SDimitry Andric         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
32440b57cec5SDimitry Andric       else if (Call.second.RelBlockFreq)
32450b57cec5SDimitry Andric         Out << ", relbf: " << Call.second.RelBlockFreq;
3246*5f757f3fSDimitry Andric       // Follow the convention of emitting flags as a boolean value, but only
3247*5f757f3fSDimitry Andric       // emit if true to avoid unnecessary verbosity and test churn.
3248*5f757f3fSDimitry Andric       if (Call.second.HasTailCall)
3249*5f757f3fSDimitry Andric         Out << ", tail: 1";
32500b57cec5SDimitry Andric       Out << ")";
32510b57cec5SDimitry Andric     }
32520b57cec5SDimitry Andric     Out << ")";
32530b57cec5SDimitry Andric   }
32540b57cec5SDimitry Andric 
32550b57cec5SDimitry Andric   if (const auto *TIdInfo = FS->getTypeIdInfo())
32560b57cec5SDimitry Andric     printTypeIdInfo(*TIdInfo);
32575ffd83dbSDimitry Andric 
3258bdd1243dSDimitry Andric   // The AllocationType identifiers capture the profiled context behavior
325906c3fb27SDimitry Andric   // reaching a specific static allocation site (possibly cloned).
3260bdd1243dSDimitry Andric   auto AllocTypeName = [](uint8_t Type) -> const char * {
3261bdd1243dSDimitry Andric     switch (Type) {
3262bdd1243dSDimitry Andric     case (uint8_t)AllocationType::None:
3263bdd1243dSDimitry Andric       return "none";
3264bdd1243dSDimitry Andric     case (uint8_t)AllocationType::NotCold:
3265bdd1243dSDimitry Andric       return "notcold";
3266bdd1243dSDimitry Andric     case (uint8_t)AllocationType::Cold:
3267bdd1243dSDimitry Andric       return "cold";
326806c3fb27SDimitry Andric     case (uint8_t)AllocationType::Hot:
326906c3fb27SDimitry Andric       return "hot";
3270bdd1243dSDimitry Andric     }
3271bdd1243dSDimitry Andric     llvm_unreachable("Unexpected alloc type");
3272bdd1243dSDimitry Andric   };
3273bdd1243dSDimitry Andric 
3274bdd1243dSDimitry Andric   if (!FS->allocs().empty()) {
3275bdd1243dSDimitry Andric     Out << ", allocs: (";
3276bdd1243dSDimitry Andric     FieldSeparator AFS;
3277bdd1243dSDimitry Andric     for (auto &AI : FS->allocs()) {
3278bdd1243dSDimitry Andric       Out << AFS;
3279bdd1243dSDimitry Andric       Out << "(versions: (";
3280bdd1243dSDimitry Andric       FieldSeparator VFS;
3281bdd1243dSDimitry Andric       for (auto V : AI.Versions) {
3282bdd1243dSDimitry Andric         Out << VFS;
3283bdd1243dSDimitry Andric         Out << AllocTypeName(V);
3284bdd1243dSDimitry Andric       }
3285bdd1243dSDimitry Andric       Out << "), memProf: (";
3286bdd1243dSDimitry Andric       FieldSeparator MIBFS;
3287bdd1243dSDimitry Andric       for (auto &MIB : AI.MIBs) {
3288bdd1243dSDimitry Andric         Out << MIBFS;
3289bdd1243dSDimitry Andric         Out << "(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3290bdd1243dSDimitry Andric         Out << ", stackIds: (";
3291bdd1243dSDimitry Andric         FieldSeparator SIDFS;
3292bdd1243dSDimitry Andric         for (auto Id : MIB.StackIdIndices) {
3293bdd1243dSDimitry Andric           Out << SIDFS;
3294bdd1243dSDimitry Andric           Out << TheIndex->getStackIdAtIndex(Id);
3295bdd1243dSDimitry Andric         }
3296bdd1243dSDimitry Andric         Out << "))";
3297bdd1243dSDimitry Andric       }
3298bdd1243dSDimitry Andric       Out << "))";
3299bdd1243dSDimitry Andric     }
3300bdd1243dSDimitry Andric     Out << ")";
3301bdd1243dSDimitry Andric   }
3302bdd1243dSDimitry Andric 
3303bdd1243dSDimitry Andric   if (!FS->callsites().empty()) {
3304bdd1243dSDimitry Andric     Out << ", callsites: (";
3305bdd1243dSDimitry Andric     FieldSeparator SNFS;
3306bdd1243dSDimitry Andric     for (auto &CI : FS->callsites()) {
3307bdd1243dSDimitry Andric       Out << SNFS;
3308bdd1243dSDimitry Andric       if (CI.Callee)
3309bdd1243dSDimitry Andric         Out << "(callee: ^" << Machine.getGUIDSlot(CI.Callee.getGUID());
3310bdd1243dSDimitry Andric       else
3311bdd1243dSDimitry Andric         Out << "(callee: null";
3312bdd1243dSDimitry Andric       Out << ", clones: (";
3313bdd1243dSDimitry Andric       FieldSeparator VFS;
3314bdd1243dSDimitry Andric       for (auto V : CI.Clones) {
3315bdd1243dSDimitry Andric         Out << VFS;
3316bdd1243dSDimitry Andric         Out << V;
3317bdd1243dSDimitry Andric       }
3318bdd1243dSDimitry Andric       Out << "), stackIds: (";
3319bdd1243dSDimitry Andric       FieldSeparator SIDFS;
3320bdd1243dSDimitry Andric       for (auto Id : CI.StackIdIndices) {
3321bdd1243dSDimitry Andric         Out << SIDFS;
3322bdd1243dSDimitry Andric         Out << TheIndex->getStackIdAtIndex(Id);
3323bdd1243dSDimitry Andric       }
3324bdd1243dSDimitry Andric       Out << "))";
3325bdd1243dSDimitry Andric     }
3326bdd1243dSDimitry Andric     Out << ")";
3327bdd1243dSDimitry Andric   }
3328bdd1243dSDimitry Andric 
33295ffd83dbSDimitry Andric   auto PrintRange = [&](const ConstantRange &Range) {
3330e8d8bef9SDimitry Andric     Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
33315ffd83dbSDimitry Andric   };
33325ffd83dbSDimitry Andric 
33335ffd83dbSDimitry Andric   if (!FS->paramAccesses().empty()) {
33345ffd83dbSDimitry Andric     Out << ", params: (";
33355ffd83dbSDimitry Andric     FieldSeparator IFS;
33365ffd83dbSDimitry Andric     for (auto &PS : FS->paramAccesses()) {
33375ffd83dbSDimitry Andric       Out << IFS;
33385ffd83dbSDimitry Andric       Out << "(param: " << PS.ParamNo;
33395ffd83dbSDimitry Andric       Out << ", offset: ";
33405ffd83dbSDimitry Andric       PrintRange(PS.Use);
33415ffd83dbSDimitry Andric       if (!PS.Calls.empty()) {
33425ffd83dbSDimitry Andric         Out << ", calls: (";
33435ffd83dbSDimitry Andric         FieldSeparator IFS;
33445ffd83dbSDimitry Andric         for (auto &Call : PS.Calls) {
33455ffd83dbSDimitry Andric           Out << IFS;
3346e8d8bef9SDimitry Andric           Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
33475ffd83dbSDimitry Andric           Out << ", param: " << Call.ParamNo;
33485ffd83dbSDimitry Andric           Out << ", offset: ";
33495ffd83dbSDimitry Andric           PrintRange(Call.Offsets);
33505ffd83dbSDimitry Andric           Out << ")";
33515ffd83dbSDimitry Andric         }
33525ffd83dbSDimitry Andric         Out << ")";
33535ffd83dbSDimitry Andric       }
33545ffd83dbSDimitry Andric       Out << ")";
33555ffd83dbSDimitry Andric     }
33565ffd83dbSDimitry Andric     Out << ")";
33575ffd83dbSDimitry Andric   }
33580b57cec5SDimitry Andric }
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric void AssemblyWriter::printTypeIdInfo(
33610b57cec5SDimitry Andric     const FunctionSummary::TypeIdInfo &TIDInfo) {
33620b57cec5SDimitry Andric   Out << ", typeIdInfo: (";
33630b57cec5SDimitry Andric   FieldSeparator TIDFS;
33640b57cec5SDimitry Andric   if (!TIDInfo.TypeTests.empty()) {
33650b57cec5SDimitry Andric     Out << TIDFS;
33660b57cec5SDimitry Andric     Out << "typeTests: (";
33670b57cec5SDimitry Andric     FieldSeparator FS;
33680b57cec5SDimitry Andric     for (auto &GUID : TIDInfo.TypeTests) {
33690b57cec5SDimitry Andric       auto TidIter = TheIndex->typeIds().equal_range(GUID);
33700b57cec5SDimitry Andric       if (TidIter.first == TidIter.second) {
33710b57cec5SDimitry Andric         Out << FS;
33720b57cec5SDimitry Andric         Out << GUID;
33730b57cec5SDimitry Andric         continue;
33740b57cec5SDimitry Andric       }
33750b57cec5SDimitry Andric       // Print all type id that correspond to this GUID.
33760b57cec5SDimitry Andric       for (auto It = TidIter.first; It != TidIter.second; ++It) {
33770b57cec5SDimitry Andric         Out << FS;
33780b57cec5SDimitry Andric         auto Slot = Machine.getTypeIdSlot(It->second.first);
33790b57cec5SDimitry Andric         assert(Slot != -1);
33800b57cec5SDimitry Andric         Out << "^" << Slot;
33810b57cec5SDimitry Andric       }
33820b57cec5SDimitry Andric     }
33830b57cec5SDimitry Andric     Out << ")";
33840b57cec5SDimitry Andric   }
33850b57cec5SDimitry Andric   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
33860b57cec5SDimitry Andric     Out << TIDFS;
33870b57cec5SDimitry Andric     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
33880b57cec5SDimitry Andric   }
33890b57cec5SDimitry Andric   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
33900b57cec5SDimitry Andric     Out << TIDFS;
33910b57cec5SDimitry Andric     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
33920b57cec5SDimitry Andric   }
33930b57cec5SDimitry Andric   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
33940b57cec5SDimitry Andric     Out << TIDFS;
33950b57cec5SDimitry Andric     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
33960b57cec5SDimitry Andric                      "typeTestAssumeConstVCalls");
33970b57cec5SDimitry Andric   }
33980b57cec5SDimitry Andric   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
33990b57cec5SDimitry Andric     Out << TIDFS;
34000b57cec5SDimitry Andric     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
34010b57cec5SDimitry Andric                      "typeCheckedLoadConstVCalls");
34020b57cec5SDimitry Andric   }
34030b57cec5SDimitry Andric   Out << ")";
34040b57cec5SDimitry Andric }
34050b57cec5SDimitry Andric 
34060b57cec5SDimitry Andric void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
34070b57cec5SDimitry Andric   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
34080b57cec5SDimitry Andric   if (TidIter.first == TidIter.second) {
34090b57cec5SDimitry Andric     Out << "vFuncId: (";
34100b57cec5SDimitry Andric     Out << "guid: " << VFId.GUID;
34110b57cec5SDimitry Andric     Out << ", offset: " << VFId.Offset;
34120b57cec5SDimitry Andric     Out << ")";
34130b57cec5SDimitry Andric     return;
34140b57cec5SDimitry Andric   }
34150b57cec5SDimitry Andric   // Print all type id that correspond to this GUID.
34160b57cec5SDimitry Andric   FieldSeparator FS;
34170b57cec5SDimitry Andric   for (auto It = TidIter.first; It != TidIter.second; ++It) {
34180b57cec5SDimitry Andric     Out << FS;
34190b57cec5SDimitry Andric     Out << "vFuncId: (";
34200b57cec5SDimitry Andric     auto Slot = Machine.getTypeIdSlot(It->second.first);
34210b57cec5SDimitry Andric     assert(Slot != -1);
34220b57cec5SDimitry Andric     Out << "^" << Slot;
34230b57cec5SDimitry Andric     Out << ", offset: " << VFId.Offset;
34240b57cec5SDimitry Andric     Out << ")";
34250b57cec5SDimitry Andric   }
34260b57cec5SDimitry Andric }
34270b57cec5SDimitry Andric 
34280b57cec5SDimitry Andric void AssemblyWriter::printNonConstVCalls(
34295ffd83dbSDimitry Andric     const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
34300b57cec5SDimitry Andric   Out << Tag << ": (";
34310b57cec5SDimitry Andric   FieldSeparator FS;
34320b57cec5SDimitry Andric   for (auto &VFuncId : VCallList) {
34330b57cec5SDimitry Andric     Out << FS;
34340b57cec5SDimitry Andric     printVFuncId(VFuncId);
34350b57cec5SDimitry Andric   }
34360b57cec5SDimitry Andric   Out << ")";
34370b57cec5SDimitry Andric }
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric void AssemblyWriter::printConstVCalls(
34405ffd83dbSDimitry Andric     const std::vector<FunctionSummary::ConstVCall> &VCallList,
34415ffd83dbSDimitry Andric     const char *Tag) {
34420b57cec5SDimitry Andric   Out << Tag << ": (";
34430b57cec5SDimitry Andric   FieldSeparator FS;
34440b57cec5SDimitry Andric   for (auto &ConstVCall : VCallList) {
34450b57cec5SDimitry Andric     Out << FS;
34460b57cec5SDimitry Andric     Out << "(";
34470b57cec5SDimitry Andric     printVFuncId(ConstVCall.VFunc);
34480b57cec5SDimitry Andric     if (!ConstVCall.Args.empty()) {
34490b57cec5SDimitry Andric       Out << ", ";
34500b57cec5SDimitry Andric       printArgs(ConstVCall.Args);
34510b57cec5SDimitry Andric     }
34520b57cec5SDimitry Andric     Out << ")";
34530b57cec5SDimitry Andric   }
34540b57cec5SDimitry Andric   Out << ")";
34550b57cec5SDimitry Andric }
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
34580b57cec5SDimitry Andric   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
34590b57cec5SDimitry Andric   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
34600b57cec5SDimitry Andric   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
34610b57cec5SDimitry Andric   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
34620b57cec5SDimitry Andric       << ", flags: (";
34630b57cec5SDimitry Andric   Out << "linkage: " << getLinkageName(LT);
3464fe6060f1SDimitry Andric   Out << ", visibility: "
3465fe6060f1SDimitry Andric       << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility);
34660b57cec5SDimitry Andric   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
34670b57cec5SDimitry Andric   Out << ", live: " << GVFlags.Live;
34680b57cec5SDimitry Andric   Out << ", dsoLocal: " << GVFlags.DSOLocal;
34690b57cec5SDimitry Andric   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
34700b57cec5SDimitry Andric   Out << ")";
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
34730b57cec5SDimitry Andric     printAliasSummary(cast<AliasSummary>(&Summary));
34740b57cec5SDimitry Andric   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
34750b57cec5SDimitry Andric     printFunctionSummary(cast<FunctionSummary>(&Summary));
34760b57cec5SDimitry Andric   else
34770b57cec5SDimitry Andric     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   auto RefList = Summary.refs();
34800b57cec5SDimitry Andric   if (!RefList.empty()) {
34810b57cec5SDimitry Andric     Out << ", refs: (";
34820b57cec5SDimitry Andric     FieldSeparator FS;
34830b57cec5SDimitry Andric     for (auto &Ref : RefList) {
34840b57cec5SDimitry Andric       Out << FS;
34850b57cec5SDimitry Andric       if (Ref.isReadOnly())
34860b57cec5SDimitry Andric         Out << "readonly ";
34870b57cec5SDimitry Andric       else if (Ref.isWriteOnly())
34880b57cec5SDimitry Andric         Out << "writeonly ";
34890b57cec5SDimitry Andric       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
34900b57cec5SDimitry Andric     }
34910b57cec5SDimitry Andric     Out << ")";
34920b57cec5SDimitry Andric   }
34930b57cec5SDimitry Andric 
34940b57cec5SDimitry Andric   Out << ")";
34950b57cec5SDimitry Andric }
34960b57cec5SDimitry Andric 
34970b57cec5SDimitry Andric void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
34980b57cec5SDimitry Andric   Out << "^" << Slot << " = gv: (";
34990b57cec5SDimitry Andric   if (!VI.name().empty())
35000b57cec5SDimitry Andric     Out << "name: \"" << VI.name() << "\"";
35010b57cec5SDimitry Andric   else
35020b57cec5SDimitry Andric     Out << "guid: " << VI.getGUID();
35030b57cec5SDimitry Andric   if (!VI.getSummaryList().empty()) {
35040b57cec5SDimitry Andric     Out << ", summaries: (";
35050b57cec5SDimitry Andric     FieldSeparator FS;
35060b57cec5SDimitry Andric     for (auto &Summary : VI.getSummaryList()) {
35070b57cec5SDimitry Andric       Out << FS;
35080b57cec5SDimitry Andric       printSummary(*Summary);
35090b57cec5SDimitry Andric     }
35100b57cec5SDimitry Andric     Out << ")";
35110b57cec5SDimitry Andric   }
35120b57cec5SDimitry Andric   Out << ")";
35130b57cec5SDimitry Andric   if (!VI.name().empty())
35140b57cec5SDimitry Andric     Out << " ; guid = " << VI.getGUID();
35150b57cec5SDimitry Andric   Out << "\n";
35160b57cec5SDimitry Andric }
35170b57cec5SDimitry Andric 
35180b57cec5SDimitry Andric static void printMetadataIdentifier(StringRef Name,
35190b57cec5SDimitry Andric                                     formatted_raw_ostream &Out) {
35200b57cec5SDimitry Andric   if (Name.empty()) {
35210b57cec5SDimitry Andric     Out << "<empty name> ";
35220b57cec5SDimitry Andric   } else {
3523*5f757f3fSDimitry Andric     unsigned char FirstC = static_cast<unsigned char>(Name[0]);
3524*5f757f3fSDimitry Andric     if (isalpha(FirstC) || FirstC == '-' || FirstC == '$' || FirstC == '.' ||
3525*5f757f3fSDimitry Andric         FirstC == '_')
3526*5f757f3fSDimitry Andric       Out << FirstC;
35270b57cec5SDimitry Andric     else
3528*5f757f3fSDimitry Andric       Out << '\\' << hexdigit(FirstC >> 4) << hexdigit(FirstC & 0x0F);
35290b57cec5SDimitry Andric     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
35300b57cec5SDimitry Andric       unsigned char C = Name[i];
3531*5f757f3fSDimitry Andric       if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
35320b57cec5SDimitry Andric         Out << C;
35330b57cec5SDimitry Andric       else
35340b57cec5SDimitry Andric         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
35350b57cec5SDimitry Andric     }
35360b57cec5SDimitry Andric   }
35370b57cec5SDimitry Andric }
35380b57cec5SDimitry Andric 
35390b57cec5SDimitry Andric void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
35400b57cec5SDimitry Andric   Out << '!';
35410b57cec5SDimitry Andric   printMetadataIdentifier(NMD->getName(), Out);
35420b57cec5SDimitry Andric   Out << " = !{";
35430b57cec5SDimitry Andric   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
35440b57cec5SDimitry Andric     if (i)
35450b57cec5SDimitry Andric       Out << ", ";
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric     // Write DIExpressions inline.
35480b57cec5SDimitry Andric     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
35490b57cec5SDimitry Andric     MDNode *Op = NMD->getOperand(i);
35500b57cec5SDimitry Andric     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3551349cc55cSDimitry Andric       writeDIExpression(Out, Expr, AsmWriterContext::getEmpty());
35520b57cec5SDimitry Andric       continue;
35530b57cec5SDimitry Andric     }
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric     int Slot = Machine.getMetadataSlot(Op);
35560b57cec5SDimitry Andric     if (Slot == -1)
35570b57cec5SDimitry Andric       Out << "<badref>";
35580b57cec5SDimitry Andric     else
35590b57cec5SDimitry Andric       Out << '!' << Slot;
35600b57cec5SDimitry Andric   }
35610b57cec5SDimitry Andric   Out << "}\n";
35620b57cec5SDimitry Andric }
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
35650b57cec5SDimitry Andric                             formatted_raw_ostream &Out) {
35660b57cec5SDimitry Andric   switch (Vis) {
35670b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility: break;
35680b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
35690b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
35700b57cec5SDimitry Andric   }
35710b57cec5SDimitry Andric }
35720b57cec5SDimitry Andric 
35730b57cec5SDimitry Andric static void PrintDSOLocation(const GlobalValue &GV,
35740b57cec5SDimitry Andric                              formatted_raw_ostream &Out) {
35755ffd83dbSDimitry Andric   if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
35760b57cec5SDimitry Andric     Out << "dso_local ";
35770b57cec5SDimitry Andric }
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
35800b57cec5SDimitry Andric                                  formatted_raw_ostream &Out) {
35810b57cec5SDimitry Andric   switch (SCT) {
35820b57cec5SDimitry Andric   case GlobalValue::DefaultStorageClass: break;
35830b57cec5SDimitry Andric   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
35840b57cec5SDimitry Andric   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
35850b57cec5SDimitry Andric   }
35860b57cec5SDimitry Andric }
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
35890b57cec5SDimitry Andric                                   formatted_raw_ostream &Out) {
35900b57cec5SDimitry Andric   switch (TLM) {
35910b57cec5SDimitry Andric     case GlobalVariable::NotThreadLocal:
35920b57cec5SDimitry Andric       break;
35930b57cec5SDimitry Andric     case GlobalVariable::GeneralDynamicTLSModel:
35940b57cec5SDimitry Andric       Out << "thread_local ";
35950b57cec5SDimitry Andric       break;
35960b57cec5SDimitry Andric     case GlobalVariable::LocalDynamicTLSModel:
35970b57cec5SDimitry Andric       Out << "thread_local(localdynamic) ";
35980b57cec5SDimitry Andric       break;
35990b57cec5SDimitry Andric     case GlobalVariable::InitialExecTLSModel:
36000b57cec5SDimitry Andric       Out << "thread_local(initialexec) ";
36010b57cec5SDimitry Andric       break;
36020b57cec5SDimitry Andric     case GlobalVariable::LocalExecTLSModel:
36030b57cec5SDimitry Andric       Out << "thread_local(localexec) ";
36040b57cec5SDimitry Andric       break;
36050b57cec5SDimitry Andric   }
36060b57cec5SDimitry Andric }
36070b57cec5SDimitry Andric 
36080b57cec5SDimitry Andric static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
36090b57cec5SDimitry Andric   switch (UA) {
36100b57cec5SDimitry Andric   case GlobalVariable::UnnamedAddr::None:
36110b57cec5SDimitry Andric     return "";
36120b57cec5SDimitry Andric   case GlobalVariable::UnnamedAddr::Local:
36130b57cec5SDimitry Andric     return "local_unnamed_addr";
36140b57cec5SDimitry Andric   case GlobalVariable::UnnamedAddr::Global:
36150b57cec5SDimitry Andric     return "unnamed_addr";
36160b57cec5SDimitry Andric   }
36170b57cec5SDimitry Andric   llvm_unreachable("Unknown UnnamedAddr");
36180b57cec5SDimitry Andric }
36190b57cec5SDimitry Andric 
36200b57cec5SDimitry Andric static void maybePrintComdat(formatted_raw_ostream &Out,
36210b57cec5SDimitry Andric                              const GlobalObject &GO) {
36220b57cec5SDimitry Andric   const Comdat *C = GO.getComdat();
36230b57cec5SDimitry Andric   if (!C)
36240b57cec5SDimitry Andric     return;
36250b57cec5SDimitry Andric 
36260b57cec5SDimitry Andric   if (isa<GlobalVariable>(GO))
36270b57cec5SDimitry Andric     Out << ',';
36280b57cec5SDimitry Andric   Out << " comdat";
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric   if (GO.getName() == C->getName())
36310b57cec5SDimitry Andric     return;
36320b57cec5SDimitry Andric 
36330b57cec5SDimitry Andric   Out << '(';
36340b57cec5SDimitry Andric   PrintLLVMName(Out, C->getName(), ComdatPrefix);
36350b57cec5SDimitry Andric   Out << ')';
36360b57cec5SDimitry Andric }
36370b57cec5SDimitry Andric 
36380b57cec5SDimitry Andric void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
36390b57cec5SDimitry Andric   if (GV->isMaterializable())
36400b57cec5SDimitry Andric     Out << "; Materializable\n";
36410b57cec5SDimitry Andric 
3642349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent());
3643349cc55cSDimitry Andric   WriteAsOperandInternal(Out, GV, WriterCtx);
36440b57cec5SDimitry Andric   Out << " = ";
36450b57cec5SDimitry Andric 
36460b57cec5SDimitry Andric   if (!GV->hasInitializer() && GV->hasExternalLinkage())
36470b57cec5SDimitry Andric     Out << "external ";
36480b57cec5SDimitry Andric 
36490b57cec5SDimitry Andric   Out << getLinkageNameWithSpace(GV->getLinkage());
36500b57cec5SDimitry Andric   PrintDSOLocation(*GV, Out);
36510b57cec5SDimitry Andric   PrintVisibility(GV->getVisibility(), Out);
36520b57cec5SDimitry Andric   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
36530b57cec5SDimitry Andric   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
36540b57cec5SDimitry Andric   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
36550b57cec5SDimitry Andric   if (!UA.empty())
36560b57cec5SDimitry Andric       Out << UA << ' ';
36570b57cec5SDimitry Andric 
36580b57cec5SDimitry Andric   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
36590b57cec5SDimitry Andric     Out << "addrspace(" << AddressSpace << ") ";
36600b57cec5SDimitry Andric   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
36610b57cec5SDimitry Andric   Out << (GV->isConstant() ? "constant " : "global ");
36620b57cec5SDimitry Andric   TypePrinter.print(GV->getValueType(), Out);
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric   if (GV->hasInitializer()) {
36650b57cec5SDimitry Andric     Out << ' ';
36660b57cec5SDimitry Andric     writeOperand(GV->getInitializer(), false);
36670b57cec5SDimitry Andric   }
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric   if (GV->hasSection()) {
36700b57cec5SDimitry Andric     Out << ", section \"";
36710b57cec5SDimitry Andric     printEscapedString(GV->getSection(), Out);
36720b57cec5SDimitry Andric     Out << '"';
36730b57cec5SDimitry Andric   }
36740b57cec5SDimitry Andric   if (GV->hasPartition()) {
36750b57cec5SDimitry Andric     Out << ", partition \"";
36760b57cec5SDimitry Andric     printEscapedString(GV->getPartition(), Out);
36770b57cec5SDimitry Andric     Out << '"';
36780b57cec5SDimitry Andric   }
3679*5f757f3fSDimitry Andric   if (auto CM = GV->getCodeModel()) {
3680*5f757f3fSDimitry Andric     Out << ", code_model \"";
3681*5f757f3fSDimitry Andric     switch (*CM) {
3682*5f757f3fSDimitry Andric     case CodeModel::Tiny:
3683*5f757f3fSDimitry Andric       Out << "tiny";
3684*5f757f3fSDimitry Andric       break;
3685*5f757f3fSDimitry Andric     case CodeModel::Small:
3686*5f757f3fSDimitry Andric       Out << "small";
3687*5f757f3fSDimitry Andric       break;
3688*5f757f3fSDimitry Andric     case CodeModel::Kernel:
3689*5f757f3fSDimitry Andric       Out << "kernel";
3690*5f757f3fSDimitry Andric       break;
3691*5f757f3fSDimitry Andric     case CodeModel::Medium:
3692*5f757f3fSDimitry Andric       Out << "medium";
3693*5f757f3fSDimitry Andric       break;
3694*5f757f3fSDimitry Andric     case CodeModel::Large:
3695*5f757f3fSDimitry Andric       Out << "large";
3696*5f757f3fSDimitry Andric       break;
3697*5f757f3fSDimitry Andric     }
3698*5f757f3fSDimitry Andric     Out << '"';
3699*5f757f3fSDimitry Andric   }
37000b57cec5SDimitry Andric 
370181ad6265SDimitry Andric   using SanitizerMetadata = llvm::GlobalValue::SanitizerMetadata;
370281ad6265SDimitry Andric   if (GV->hasSanitizerMetadata()) {
370381ad6265SDimitry Andric     SanitizerMetadata MD = GV->getSanitizerMetadata();
370481ad6265SDimitry Andric     if (MD.NoAddress)
370581ad6265SDimitry Andric       Out << ", no_sanitize_address";
370681ad6265SDimitry Andric     if (MD.NoHWAddress)
370781ad6265SDimitry Andric       Out << ", no_sanitize_hwaddress";
3708753f127fSDimitry Andric     if (MD.Memtag)
3709753f127fSDimitry Andric       Out << ", sanitize_memtag";
371081ad6265SDimitry Andric     if (MD.IsDynInit)
371181ad6265SDimitry Andric       Out << ", sanitize_address_dyninit";
371281ad6265SDimitry Andric   }
371381ad6265SDimitry Andric 
37140b57cec5SDimitry Andric   maybePrintComdat(Out, *GV);
37150eae32dcSDimitry Andric   if (MaybeAlign A = GV->getAlign())
37160eae32dcSDimitry Andric     Out << ", align " << A->value();
37170b57cec5SDimitry Andric 
37180b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
37190b57cec5SDimitry Andric   GV->getAllMetadata(MDs);
37200b57cec5SDimitry Andric   printMetadataAttachments(MDs, ", ");
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric   auto Attrs = GV->getAttributes();
37230b57cec5SDimitry Andric   if (Attrs.hasAttributes())
37240b57cec5SDimitry Andric     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
37250b57cec5SDimitry Andric 
37260b57cec5SDimitry Andric   printInfoComment(*GV);
37270b57cec5SDimitry Andric }
37280b57cec5SDimitry Andric 
3729349cc55cSDimitry Andric void AssemblyWriter::printAlias(const GlobalAlias *GA) {
3730349cc55cSDimitry Andric   if (GA->isMaterializable())
37310b57cec5SDimitry Andric     Out << "; Materializable\n";
37320b57cec5SDimitry Andric 
3733349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent());
3734349cc55cSDimitry Andric   WriteAsOperandInternal(Out, GA, WriterCtx);
37350b57cec5SDimitry Andric   Out << " = ";
37360b57cec5SDimitry Andric 
3737349cc55cSDimitry Andric   Out << getLinkageNameWithSpace(GA->getLinkage());
3738349cc55cSDimitry Andric   PrintDSOLocation(*GA, Out);
3739349cc55cSDimitry Andric   PrintVisibility(GA->getVisibility(), Out);
3740349cc55cSDimitry Andric   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
3741349cc55cSDimitry Andric   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
3742349cc55cSDimitry Andric   StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr());
37430b57cec5SDimitry Andric   if (!UA.empty())
37440b57cec5SDimitry Andric       Out << UA << ' ';
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric   Out << "alias ";
37470b57cec5SDimitry Andric 
3748349cc55cSDimitry Andric   TypePrinter.print(GA->getValueType(), Out);
37490b57cec5SDimitry Andric   Out << ", ";
37500b57cec5SDimitry Andric 
3751349cc55cSDimitry Andric   if (const Constant *Aliasee = GA->getAliasee()) {
3752349cc55cSDimitry Andric     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
37530b57cec5SDimitry Andric   } else {
3754349cc55cSDimitry Andric     TypePrinter.print(GA->getType(), Out);
3755349cc55cSDimitry Andric     Out << " <<NULL ALIASEE>>";
37560b57cec5SDimitry Andric   }
37570b57cec5SDimitry Andric 
3758349cc55cSDimitry Andric   if (GA->hasPartition()) {
37590b57cec5SDimitry Andric     Out << ", partition \"";
3760349cc55cSDimitry Andric     printEscapedString(GA->getPartition(), Out);
37610b57cec5SDimitry Andric     Out << '"';
37620b57cec5SDimitry Andric   }
37630b57cec5SDimitry Andric 
3764349cc55cSDimitry Andric   printInfoComment(*GA);
3765349cc55cSDimitry Andric   Out << '\n';
3766349cc55cSDimitry Andric }
3767349cc55cSDimitry Andric 
3768349cc55cSDimitry Andric void AssemblyWriter::printIFunc(const GlobalIFunc *GI) {
3769349cc55cSDimitry Andric   if (GI->isMaterializable())
3770349cc55cSDimitry Andric     Out << "; Materializable\n";
3771349cc55cSDimitry Andric 
3772349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent());
3773349cc55cSDimitry Andric   WriteAsOperandInternal(Out, GI, WriterCtx);
3774349cc55cSDimitry Andric   Out << " = ";
3775349cc55cSDimitry Andric 
3776349cc55cSDimitry Andric   Out << getLinkageNameWithSpace(GI->getLinkage());
3777349cc55cSDimitry Andric   PrintDSOLocation(*GI, Out);
3778349cc55cSDimitry Andric   PrintVisibility(GI->getVisibility(), Out);
3779349cc55cSDimitry Andric 
3780349cc55cSDimitry Andric   Out << "ifunc ";
3781349cc55cSDimitry Andric 
3782349cc55cSDimitry Andric   TypePrinter.print(GI->getValueType(), Out);
3783349cc55cSDimitry Andric   Out << ", ";
3784349cc55cSDimitry Andric 
3785349cc55cSDimitry Andric   if (const Constant *Resolver = GI->getResolver()) {
3786349cc55cSDimitry Andric     writeOperand(Resolver, !isa<ConstantExpr>(Resolver));
3787349cc55cSDimitry Andric   } else {
3788349cc55cSDimitry Andric     TypePrinter.print(GI->getType(), Out);
3789349cc55cSDimitry Andric     Out << " <<NULL RESOLVER>>";
3790349cc55cSDimitry Andric   }
3791349cc55cSDimitry Andric 
3792349cc55cSDimitry Andric   if (GI->hasPartition()) {
3793349cc55cSDimitry Andric     Out << ", partition \"";
3794349cc55cSDimitry Andric     printEscapedString(GI->getPartition(), Out);
3795349cc55cSDimitry Andric     Out << '"';
3796349cc55cSDimitry Andric   }
3797349cc55cSDimitry Andric 
3798349cc55cSDimitry Andric   printInfoComment(*GI);
37990b57cec5SDimitry Andric   Out << '\n';
38000b57cec5SDimitry Andric }
38010b57cec5SDimitry Andric 
38020b57cec5SDimitry Andric void AssemblyWriter::printComdat(const Comdat *C) {
38030b57cec5SDimitry Andric   C->print(Out);
38040b57cec5SDimitry Andric }
38050b57cec5SDimitry Andric 
38060b57cec5SDimitry Andric void AssemblyWriter::printTypeIdentities() {
38070b57cec5SDimitry Andric   if (TypePrinter.empty())
38080b57cec5SDimitry Andric     return;
38090b57cec5SDimitry Andric 
38100b57cec5SDimitry Andric   Out << '\n';
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric   // Emit all numbered types.
38130b57cec5SDimitry Andric   auto &NumberedTypes = TypePrinter.getNumberedTypes();
38140b57cec5SDimitry Andric   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
38150b57cec5SDimitry Andric     Out << '%' << I << " = type ";
38160b57cec5SDimitry Andric 
38170b57cec5SDimitry Andric     // Make sure we print out at least one level of the type structure, so
38180b57cec5SDimitry Andric     // that we do not get %2 = type %2
38190b57cec5SDimitry Andric     TypePrinter.printStructBody(NumberedTypes[I], Out);
38200b57cec5SDimitry Andric     Out << '\n';
38210b57cec5SDimitry Andric   }
38220b57cec5SDimitry Andric 
38230b57cec5SDimitry Andric   auto &NamedTypes = TypePrinter.getNamedTypes();
38240eae32dcSDimitry Andric   for (StructType *NamedType : NamedTypes) {
38250eae32dcSDimitry Andric     PrintLLVMName(Out, NamedType->getName(), LocalPrefix);
38260b57cec5SDimitry Andric     Out << " = type ";
38270b57cec5SDimitry Andric 
38280b57cec5SDimitry Andric     // Make sure we print out at least one level of the type structure, so
38290b57cec5SDimitry Andric     // that we do not get %FILE = type %FILE
38300eae32dcSDimitry Andric     TypePrinter.printStructBody(NamedType, Out);
38310b57cec5SDimitry Andric     Out << '\n';
38320b57cec5SDimitry Andric   }
38330b57cec5SDimitry Andric }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric /// printFunction - Print all aspects of a function.
38360b57cec5SDimitry Andric void AssemblyWriter::printFunction(const Function *F) {
3837*5f757f3fSDimitry Andric   bool ConvertBack = F->IsNewDbgInfoFormat;
3838*5f757f3fSDimitry Andric   if (ConvertBack)
3839*5f757f3fSDimitry Andric     const_cast<Function *>(F)->convertFromNewDbgValues();
38400b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   if (F->isMaterializable())
38430b57cec5SDimitry Andric     Out << "; Materializable\n";
38440b57cec5SDimitry Andric 
38450b57cec5SDimitry Andric   const AttributeList &Attrs = F->getAttributes();
3846349cc55cSDimitry Andric   if (Attrs.hasFnAttrs()) {
3847349cc55cSDimitry Andric     AttributeSet AS = Attrs.getFnAttrs();
38480b57cec5SDimitry Andric     std::string AttrStr;
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric     for (const Attribute &Attr : AS) {
38510b57cec5SDimitry Andric       if (!Attr.isStringAttribute()) {
38520b57cec5SDimitry Andric         if (!AttrStr.empty()) AttrStr += ' ';
38530b57cec5SDimitry Andric         AttrStr += Attr.getAsString();
38540b57cec5SDimitry Andric       }
38550b57cec5SDimitry Andric     }
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric     if (!AttrStr.empty())
38580b57cec5SDimitry Andric       Out << "; Function Attrs: " << AttrStr << '\n';
38590b57cec5SDimitry Andric   }
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric   Machine.incorporateFunction(F);
38620b57cec5SDimitry Andric 
38630b57cec5SDimitry Andric   if (F->isDeclaration()) {
38640b57cec5SDimitry Andric     Out << "declare";
38650b57cec5SDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
38660b57cec5SDimitry Andric     F->getAllMetadata(MDs);
38670b57cec5SDimitry Andric     printMetadataAttachments(MDs, " ");
38680b57cec5SDimitry Andric     Out << ' ';
38690b57cec5SDimitry Andric   } else
38700b57cec5SDimitry Andric     Out << "define ";
38710b57cec5SDimitry Andric 
38720b57cec5SDimitry Andric   Out << getLinkageNameWithSpace(F->getLinkage());
38730b57cec5SDimitry Andric   PrintDSOLocation(*F, Out);
38740b57cec5SDimitry Andric   PrintVisibility(F->getVisibility(), Out);
38750b57cec5SDimitry Andric   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
38760b57cec5SDimitry Andric 
38770b57cec5SDimitry Andric   // Print the calling convention.
38780b57cec5SDimitry Andric   if (F->getCallingConv() != CallingConv::C) {
38790b57cec5SDimitry Andric     PrintCallingConv(F->getCallingConv(), Out);
38800b57cec5SDimitry Andric     Out << " ";
38810b57cec5SDimitry Andric   }
38820b57cec5SDimitry Andric 
38830b57cec5SDimitry Andric   FunctionType *FT = F->getFunctionType();
3884349cc55cSDimitry Andric   if (Attrs.hasRetAttrs())
38850b57cec5SDimitry Andric     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
38860b57cec5SDimitry Andric   TypePrinter.print(F->getReturnType(), Out);
3887349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent());
38880b57cec5SDimitry Andric   Out << ' ';
3889349cc55cSDimitry Andric   WriteAsOperandInternal(Out, F, WriterCtx);
38900b57cec5SDimitry Andric   Out << '(';
38910b57cec5SDimitry Andric 
38920b57cec5SDimitry Andric   // Loop over the arguments, printing them...
38930b57cec5SDimitry Andric   if (F->isDeclaration() && !IsForDebug) {
38940b57cec5SDimitry Andric     // We're only interested in the type here - don't print argument names.
38950b57cec5SDimitry Andric     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
38960b57cec5SDimitry Andric       // Insert commas as we go... the first arg doesn't get a comma
38970b57cec5SDimitry Andric       if (I)
38980b57cec5SDimitry Andric         Out << ", ";
38990b57cec5SDimitry Andric       // Output type...
39000b57cec5SDimitry Andric       TypePrinter.print(FT->getParamType(I), Out);
39010b57cec5SDimitry Andric 
3902349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
3903480093f4SDimitry Andric       if (ArgAttrs.hasAttributes()) {
3904480093f4SDimitry Andric         Out << ' ';
3905480093f4SDimitry Andric         writeAttributeSet(ArgAttrs);
3906480093f4SDimitry Andric       }
39070b57cec5SDimitry Andric     }
39080b57cec5SDimitry Andric   } else {
39090b57cec5SDimitry Andric     // The arguments are meaningful here, print them in detail.
39100b57cec5SDimitry Andric     for (const Argument &Arg : F->args()) {
39110b57cec5SDimitry Andric       // Insert commas as we go... the first arg doesn't get a comma
39120b57cec5SDimitry Andric       if (Arg.getArgNo() != 0)
39130b57cec5SDimitry Andric         Out << ", ";
3914349cc55cSDimitry Andric       printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo()));
39150b57cec5SDimitry Andric     }
39160b57cec5SDimitry Andric   }
39170b57cec5SDimitry Andric 
39180b57cec5SDimitry Andric   // Finish printing arguments...
39190b57cec5SDimitry Andric   if (FT->isVarArg()) {
39200b57cec5SDimitry Andric     if (FT->getNumParams()) Out << ", ";
39210b57cec5SDimitry Andric     Out << "...";  // Output varargs portion of signature!
39220b57cec5SDimitry Andric   }
39230b57cec5SDimitry Andric   Out << ')';
39240b57cec5SDimitry Andric   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
39250b57cec5SDimitry Andric   if (!UA.empty())
39260b57cec5SDimitry Andric     Out << ' ' << UA;
39270b57cec5SDimitry Andric   // We print the function address space if it is non-zero or if we are writing
39280b57cec5SDimitry Andric   // a module with a non-zero program address space or if there is no valid
39290b57cec5SDimitry Andric   // Module* so that the file can be parsed without the datalayout string.
39300b57cec5SDimitry Andric   const Module *Mod = F->getParent();
39310b57cec5SDimitry Andric   if (F->getAddressSpace() != 0 || !Mod ||
39320b57cec5SDimitry Andric       Mod->getDataLayout().getProgramAddressSpace() != 0)
39330b57cec5SDimitry Andric     Out << " addrspace(" << F->getAddressSpace() << ")";
3934349cc55cSDimitry Andric   if (Attrs.hasFnAttrs())
3935349cc55cSDimitry Andric     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs());
39360b57cec5SDimitry Andric   if (F->hasSection()) {
39370b57cec5SDimitry Andric     Out << " section \"";
39380b57cec5SDimitry Andric     printEscapedString(F->getSection(), Out);
39390b57cec5SDimitry Andric     Out << '"';
39400b57cec5SDimitry Andric   }
39410b57cec5SDimitry Andric   if (F->hasPartition()) {
39420b57cec5SDimitry Andric     Out << " partition \"";
39430b57cec5SDimitry Andric     printEscapedString(F->getPartition(), Out);
39440b57cec5SDimitry Andric     Out << '"';
39450b57cec5SDimitry Andric   }
39460b57cec5SDimitry Andric   maybePrintComdat(Out, *F);
39470eae32dcSDimitry Andric   if (MaybeAlign A = F->getAlign())
39480eae32dcSDimitry Andric     Out << " align " << A->value();
39490b57cec5SDimitry Andric   if (F->hasGC())
39500b57cec5SDimitry Andric     Out << " gc \"" << F->getGC() << '"';
39510b57cec5SDimitry Andric   if (F->hasPrefixData()) {
39520b57cec5SDimitry Andric     Out << " prefix ";
39530b57cec5SDimitry Andric     writeOperand(F->getPrefixData(), true);
39540b57cec5SDimitry Andric   }
39550b57cec5SDimitry Andric   if (F->hasPrologueData()) {
39560b57cec5SDimitry Andric     Out << " prologue ";
39570b57cec5SDimitry Andric     writeOperand(F->getPrologueData(), true);
39580b57cec5SDimitry Andric   }
39590b57cec5SDimitry Andric   if (F->hasPersonalityFn()) {
39600b57cec5SDimitry Andric     Out << " personality ";
39610b57cec5SDimitry Andric     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
39620b57cec5SDimitry Andric   }
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   if (F->isDeclaration()) {
39650b57cec5SDimitry Andric     Out << '\n';
39660b57cec5SDimitry Andric   } else {
39670b57cec5SDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
39680b57cec5SDimitry Andric     F->getAllMetadata(MDs);
39690b57cec5SDimitry Andric     printMetadataAttachments(MDs, " ");
39700b57cec5SDimitry Andric 
39710b57cec5SDimitry Andric     Out << " {";
39720b57cec5SDimitry Andric     // Output all of the function's basic blocks.
39730b57cec5SDimitry Andric     for (const BasicBlock &BB : *F)
39740b57cec5SDimitry Andric       printBasicBlock(&BB);
39750b57cec5SDimitry Andric 
39760b57cec5SDimitry Andric     // Output the function's use-lists.
39770b57cec5SDimitry Andric     printUseLists(F);
39780b57cec5SDimitry Andric 
39790b57cec5SDimitry Andric     Out << "}\n";
39800b57cec5SDimitry Andric   }
39810b57cec5SDimitry Andric 
3982*5f757f3fSDimitry Andric   if (ConvertBack)
3983*5f757f3fSDimitry Andric     const_cast<Function *>(F)->convertToNewDbgValues();
39840b57cec5SDimitry Andric   Machine.purgeFunction();
39850b57cec5SDimitry Andric }
39860b57cec5SDimitry Andric 
39870b57cec5SDimitry Andric /// printArgument - This member is called for every argument that is passed into
39880b57cec5SDimitry Andric /// the function.  Simply print it out
39890b57cec5SDimitry Andric void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
39900b57cec5SDimitry Andric   // Output type...
39910b57cec5SDimitry Andric   TypePrinter.print(Arg->getType(), Out);
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric   // Output parameter attributes list
3994480093f4SDimitry Andric   if (Attrs.hasAttributes()) {
3995480093f4SDimitry Andric     Out << ' ';
3996480093f4SDimitry Andric     writeAttributeSet(Attrs);
3997480093f4SDimitry Andric   }
39980b57cec5SDimitry Andric 
39990b57cec5SDimitry Andric   // Output name, if available...
40000b57cec5SDimitry Andric   if (Arg->hasName()) {
40010b57cec5SDimitry Andric     Out << ' ';
40020b57cec5SDimitry Andric     PrintLLVMName(Out, Arg);
40038bcb0991SDimitry Andric   } else {
40048bcb0991SDimitry Andric     int Slot = Machine.getLocalSlot(Arg);
40058bcb0991SDimitry Andric     assert(Slot != -1 && "expect argument in function here");
40068bcb0991SDimitry Andric     Out << " %" << Slot;
40070b57cec5SDimitry Andric   }
40080b57cec5SDimitry Andric }
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric /// printBasicBlock - This member is called for each basic block in a method.
40110b57cec5SDimitry Andric void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
4012fe6060f1SDimitry Andric   bool IsEntryBlock = BB->getParent() && BB->isEntryBlock();
40130b57cec5SDimitry Andric   if (BB->hasName()) {              // Print out the label if it exists...
40140b57cec5SDimitry Andric     Out << "\n";
40150b57cec5SDimitry Andric     PrintLLVMName(Out, BB->getName(), LabelPrefix);
40160b57cec5SDimitry Andric     Out << ':';
40170b57cec5SDimitry Andric   } else if (!IsEntryBlock) {
40180b57cec5SDimitry Andric     Out << "\n";
40190b57cec5SDimitry Andric     int Slot = Machine.getLocalSlot(BB);
40200b57cec5SDimitry Andric     if (Slot != -1)
40210b57cec5SDimitry Andric       Out << Slot << ":";
40220b57cec5SDimitry Andric     else
40230b57cec5SDimitry Andric       Out << "<badref>:";
40240b57cec5SDimitry Andric   }
40250b57cec5SDimitry Andric 
4026480093f4SDimitry Andric   if (!IsEntryBlock) {
40270b57cec5SDimitry Andric     // Output predecessors for the block.
40280b57cec5SDimitry Andric     Out.PadToColumn(50);
40290b57cec5SDimitry Andric     Out << ";";
40300b57cec5SDimitry Andric     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
40310b57cec5SDimitry Andric 
40320b57cec5SDimitry Andric     if (PI == PE) {
40330b57cec5SDimitry Andric       Out << " No predecessors!";
40340b57cec5SDimitry Andric     } else {
40350b57cec5SDimitry Andric       Out << " preds = ";
40360b57cec5SDimitry Andric       writeOperand(*PI, false);
40370b57cec5SDimitry Andric       for (++PI; PI != PE; ++PI) {
40380b57cec5SDimitry Andric         Out << ", ";
40390b57cec5SDimitry Andric         writeOperand(*PI, false);
40400b57cec5SDimitry Andric       }
40410b57cec5SDimitry Andric     }
40420b57cec5SDimitry Andric   }
40430b57cec5SDimitry Andric 
40440b57cec5SDimitry Andric   Out << "\n";
40450b57cec5SDimitry Andric 
40460b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
40470b57cec5SDimitry Andric 
40480b57cec5SDimitry Andric   // Output all of the instructions in the basic block...
40490b57cec5SDimitry Andric   for (const Instruction &I : *BB) {
40500b57cec5SDimitry Andric     printInstructionLine(I);
40510b57cec5SDimitry Andric   }
40520b57cec5SDimitry Andric 
40530b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
40540b57cec5SDimitry Andric }
40550b57cec5SDimitry Andric 
40560b57cec5SDimitry Andric /// printInstructionLine - Print an instruction and a newline character.
40570b57cec5SDimitry Andric void AssemblyWriter::printInstructionLine(const Instruction &I) {
40580b57cec5SDimitry Andric   printInstruction(I);
40590b57cec5SDimitry Andric   Out << '\n';
40600b57cec5SDimitry Andric }
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric /// printGCRelocateComment - print comment after call to the gc.relocate
40630b57cec5SDimitry Andric /// intrinsic indicating base and derived pointer names.
40640b57cec5SDimitry Andric void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
40650b57cec5SDimitry Andric   Out << " ; (";
40660b57cec5SDimitry Andric   writeOperand(Relocate.getBasePtr(), false);
40670b57cec5SDimitry Andric   Out << ", ";
40680b57cec5SDimitry Andric   writeOperand(Relocate.getDerivedPtr(), false);
40690b57cec5SDimitry Andric   Out << ")";
40700b57cec5SDimitry Andric }
40710b57cec5SDimitry Andric 
40720b57cec5SDimitry Andric /// printInfoComment - Print a little comment after the instruction indicating
40730b57cec5SDimitry Andric /// which slot it occupies.
40740b57cec5SDimitry Andric void AssemblyWriter::printInfoComment(const Value &V) {
40750b57cec5SDimitry Andric   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
40760b57cec5SDimitry Andric     printGCRelocateComment(*Relocate);
40770b57cec5SDimitry Andric 
4078*5f757f3fSDimitry Andric   if (AnnotationWriter) {
40790b57cec5SDimitry Andric     AnnotationWriter->printInfoComment(V, Out);
4080*5f757f3fSDimitry Andric   } else if (const Instruction *I = dyn_cast<Instruction>(&V)) {
4081*5f757f3fSDimitry Andric     if (I->DbgMarker) {
4082*5f757f3fSDimitry Andric       // In the new, experimental DPValue representation of debug-info, print
4083*5f757f3fSDimitry Andric       // out which instructions have DPMarkers and where they are.
4084*5f757f3fSDimitry Andric       Out << "; dbgmarker @ " << I->DbgMarker;
4085*5f757f3fSDimitry Andric     }
4086*5f757f3fSDimitry Andric   }
40870b57cec5SDimitry Andric }
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
40900b57cec5SDimitry Andric                                     raw_ostream &Out) {
40910b57cec5SDimitry Andric   // We print the address space of the call if it is non-zero.
4092bdd1243dSDimitry Andric   if (Operand == nullptr) {
4093bdd1243dSDimitry Andric     Out << " <cannot get addrspace!>";
4094bdd1243dSDimitry Andric     return;
4095bdd1243dSDimitry Andric   }
40960b57cec5SDimitry Andric   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
40970b57cec5SDimitry Andric   bool PrintAddrSpace = CallAddrSpace != 0;
40980b57cec5SDimitry Andric   if (!PrintAddrSpace) {
40990b57cec5SDimitry Andric     const Module *Mod = getModuleFromVal(I);
41000b57cec5SDimitry Andric     // We also print it if it is zero but not equal to the program address space
41010b57cec5SDimitry Andric     // or if we can't find a valid Module* to make it possible to parse
41020b57cec5SDimitry Andric     // the resulting file even without a datalayout string.
41030b57cec5SDimitry Andric     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
41040b57cec5SDimitry Andric       PrintAddrSpace = true;
41050b57cec5SDimitry Andric   }
41060b57cec5SDimitry Andric   if (PrintAddrSpace)
41070b57cec5SDimitry Andric     Out << " addrspace(" << CallAddrSpace << ")";
41080b57cec5SDimitry Andric }
41090b57cec5SDimitry Andric 
41100b57cec5SDimitry Andric // This member is called for each Instruction in a function..
41110b57cec5SDimitry Andric void AssemblyWriter::printInstruction(const Instruction &I) {
41120b57cec5SDimitry Andric   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
41130b57cec5SDimitry Andric 
41140b57cec5SDimitry Andric   // Print out indentation for an instruction.
41150b57cec5SDimitry Andric   Out << "  ";
41160b57cec5SDimitry Andric 
41170b57cec5SDimitry Andric   // Print out name if it exists...
41180b57cec5SDimitry Andric   if (I.hasName()) {
41190b57cec5SDimitry Andric     PrintLLVMName(Out, &I);
41200b57cec5SDimitry Andric     Out << " = ";
41210b57cec5SDimitry Andric   } else if (!I.getType()->isVoidTy()) {
41220b57cec5SDimitry Andric     // Print out the def slot taken.
41230b57cec5SDimitry Andric     int SlotNum = Machine.getLocalSlot(&I);
41240b57cec5SDimitry Andric     if (SlotNum == -1)
41250b57cec5SDimitry Andric       Out << "<badref> = ";
41260b57cec5SDimitry Andric     else
41270b57cec5SDimitry Andric       Out << '%' << SlotNum << " = ";
41280b57cec5SDimitry Andric   }
41290b57cec5SDimitry Andric 
41300b57cec5SDimitry Andric   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
41310b57cec5SDimitry Andric     if (CI->isMustTailCall())
41320b57cec5SDimitry Andric       Out << "musttail ";
41330b57cec5SDimitry Andric     else if (CI->isTailCall())
41340b57cec5SDimitry Andric       Out << "tail ";
41350b57cec5SDimitry Andric     else if (CI->isNoTailCall())
41360b57cec5SDimitry Andric       Out << "notail ";
41370b57cec5SDimitry Andric   }
41380b57cec5SDimitry Andric 
41390b57cec5SDimitry Andric   // Print out the opcode...
41400b57cec5SDimitry Andric   Out << I.getOpcodeName();
41410b57cec5SDimitry Andric 
41420b57cec5SDimitry Andric   // If this is an atomic load or store, print out the atomic marker.
41430b57cec5SDimitry Andric   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
41440b57cec5SDimitry Andric       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
41450b57cec5SDimitry Andric     Out << " atomic";
41460b57cec5SDimitry Andric 
41470b57cec5SDimitry Andric   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
41480b57cec5SDimitry Andric     Out << " weak";
41490b57cec5SDimitry Andric 
41500b57cec5SDimitry Andric   // If this is a volatile operation, print out the volatile marker.
41510b57cec5SDimitry Andric   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
41520b57cec5SDimitry Andric       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
41530b57cec5SDimitry Andric       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
41540b57cec5SDimitry Andric       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
41550b57cec5SDimitry Andric     Out << " volatile";
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric   // Print out optimization information.
41580b57cec5SDimitry Andric   WriteOptimizationInfo(Out, &I);
41590b57cec5SDimitry Andric 
41600b57cec5SDimitry Andric   // Print out the compare instruction predicates
41610b57cec5SDimitry Andric   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
416206c3fb27SDimitry Andric     Out << ' ' << CI->getPredicate();
41630b57cec5SDimitry Andric 
41640b57cec5SDimitry Andric   // Print out the atomicrmw operation
41650b57cec5SDimitry Andric   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
41660b57cec5SDimitry Andric     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
41670b57cec5SDimitry Andric 
41680b57cec5SDimitry Andric   // Print out the type of the operands...
41690b57cec5SDimitry Andric   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
41700b57cec5SDimitry Andric 
41710b57cec5SDimitry Andric   // Special case conditional branches to swizzle the condition out to the front
41720b57cec5SDimitry Andric   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
41730b57cec5SDimitry Andric     const BranchInst &BI(cast<BranchInst>(I));
41740b57cec5SDimitry Andric     Out << ' ';
41750b57cec5SDimitry Andric     writeOperand(BI.getCondition(), true);
41760b57cec5SDimitry Andric     Out << ", ";
41770b57cec5SDimitry Andric     writeOperand(BI.getSuccessor(0), true);
41780b57cec5SDimitry Andric     Out << ", ";
41790b57cec5SDimitry Andric     writeOperand(BI.getSuccessor(1), true);
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric   } else if (isa<SwitchInst>(I)) {
41820b57cec5SDimitry Andric     const SwitchInst& SI(cast<SwitchInst>(I));
41830b57cec5SDimitry Andric     // Special case switch instruction to get formatting nice and correct.
41840b57cec5SDimitry Andric     Out << ' ';
41850b57cec5SDimitry Andric     writeOperand(SI.getCondition(), true);
41860b57cec5SDimitry Andric     Out << ", ";
41870b57cec5SDimitry Andric     writeOperand(SI.getDefaultDest(), true);
41880b57cec5SDimitry Andric     Out << " [";
41890b57cec5SDimitry Andric     for (auto Case : SI.cases()) {
41900b57cec5SDimitry Andric       Out << "\n    ";
41910b57cec5SDimitry Andric       writeOperand(Case.getCaseValue(), true);
41920b57cec5SDimitry Andric       Out << ", ";
41930b57cec5SDimitry Andric       writeOperand(Case.getCaseSuccessor(), true);
41940b57cec5SDimitry Andric     }
41950b57cec5SDimitry Andric     Out << "\n  ]";
41960b57cec5SDimitry Andric   } else if (isa<IndirectBrInst>(I)) {
41970b57cec5SDimitry Andric     // Special case indirectbr instruction to get formatting nice and correct.
41980b57cec5SDimitry Andric     Out << ' ';
41990b57cec5SDimitry Andric     writeOperand(Operand, true);
42000b57cec5SDimitry Andric     Out << ", [";
42010b57cec5SDimitry Andric 
42020b57cec5SDimitry Andric     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
42030b57cec5SDimitry Andric       if (i != 1)
42040b57cec5SDimitry Andric         Out << ", ";
42050b57cec5SDimitry Andric       writeOperand(I.getOperand(i), true);
42060b57cec5SDimitry Andric     }
42070b57cec5SDimitry Andric     Out << ']';
42080b57cec5SDimitry Andric   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
42090b57cec5SDimitry Andric     Out << ' ';
42100b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
42110b57cec5SDimitry Andric     Out << ' ';
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
42140b57cec5SDimitry Andric       if (op) Out << ", ";
42150b57cec5SDimitry Andric       Out << "[ ";
42160b57cec5SDimitry Andric       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
42170b57cec5SDimitry Andric       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
42180b57cec5SDimitry Andric     }
42190b57cec5SDimitry Andric   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
42200b57cec5SDimitry Andric     Out << ' ';
42210b57cec5SDimitry Andric     writeOperand(I.getOperand(0), true);
4222fe6060f1SDimitry Andric     for (unsigned i : EVI->indices())
4223fe6060f1SDimitry Andric       Out << ", " << i;
42240b57cec5SDimitry Andric   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
42250b57cec5SDimitry Andric     Out << ' ';
42260b57cec5SDimitry Andric     writeOperand(I.getOperand(0), true); Out << ", ";
42270b57cec5SDimitry Andric     writeOperand(I.getOperand(1), true);
4228fe6060f1SDimitry Andric     for (unsigned i : IVI->indices())
4229fe6060f1SDimitry Andric       Out << ", " << i;
42300b57cec5SDimitry Andric   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
42310b57cec5SDimitry Andric     Out << ' ';
42320b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
42330b57cec5SDimitry Andric     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
42340b57cec5SDimitry Andric       Out << '\n';
42350b57cec5SDimitry Andric 
42360b57cec5SDimitry Andric     if (LPI->isCleanup())
42370b57cec5SDimitry Andric       Out << "          cleanup";
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
42400b57cec5SDimitry Andric       if (i != 0 || LPI->isCleanup()) Out << "\n";
42410b57cec5SDimitry Andric       if (LPI->isCatch(i))
42420b57cec5SDimitry Andric         Out << "          catch ";
42430b57cec5SDimitry Andric       else
42440b57cec5SDimitry Andric         Out << "          filter ";
42450b57cec5SDimitry Andric 
42460b57cec5SDimitry Andric       writeOperand(LPI->getClause(i), true);
42470b57cec5SDimitry Andric     }
42480b57cec5SDimitry Andric   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
42490b57cec5SDimitry Andric     Out << " within ";
42500b57cec5SDimitry Andric     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
42510b57cec5SDimitry Andric     Out << " [";
42520b57cec5SDimitry Andric     unsigned Op = 0;
42530b57cec5SDimitry Andric     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
42540b57cec5SDimitry Andric       if (Op > 0)
42550b57cec5SDimitry Andric         Out << ", ";
42560b57cec5SDimitry Andric       writeOperand(PadBB, /*PrintType=*/true);
42570b57cec5SDimitry Andric       ++Op;
42580b57cec5SDimitry Andric     }
42590b57cec5SDimitry Andric     Out << "] unwind ";
42600b57cec5SDimitry Andric     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
42610b57cec5SDimitry Andric       writeOperand(UnwindDest, /*PrintType=*/true);
42620b57cec5SDimitry Andric     else
42630b57cec5SDimitry Andric       Out << "to caller";
42640b57cec5SDimitry Andric   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
42650b57cec5SDimitry Andric     Out << " within ";
42660b57cec5SDimitry Andric     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
42670b57cec5SDimitry Andric     Out << " [";
4268bdd1243dSDimitry Andric     for (unsigned Op = 0, NumOps = FPI->arg_size(); Op < NumOps; ++Op) {
42690b57cec5SDimitry Andric       if (Op > 0)
42700b57cec5SDimitry Andric         Out << ", ";
42710b57cec5SDimitry Andric       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
42720b57cec5SDimitry Andric     }
42730b57cec5SDimitry Andric     Out << ']';
42740b57cec5SDimitry Andric   } else if (isa<ReturnInst>(I) && !Operand) {
42750b57cec5SDimitry Andric     Out << " void";
42760b57cec5SDimitry Andric   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
42770b57cec5SDimitry Andric     Out << " from ";
42780b57cec5SDimitry Andric     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
42790b57cec5SDimitry Andric 
42800b57cec5SDimitry Andric     Out << " to ";
42810b57cec5SDimitry Andric     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
42820b57cec5SDimitry Andric   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
42830b57cec5SDimitry Andric     Out << " from ";
42840b57cec5SDimitry Andric     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric     Out << " unwind ";
42870b57cec5SDimitry Andric     if (CRI->hasUnwindDest())
42880b57cec5SDimitry Andric       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
42890b57cec5SDimitry Andric     else
42900b57cec5SDimitry Andric       Out << "to caller";
42910b57cec5SDimitry Andric   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
42920b57cec5SDimitry Andric     // Print the calling convention being used.
42930b57cec5SDimitry Andric     if (CI->getCallingConv() != CallingConv::C) {
42940b57cec5SDimitry Andric       Out << " ";
42950b57cec5SDimitry Andric       PrintCallingConv(CI->getCallingConv(), Out);
42960b57cec5SDimitry Andric     }
42970b57cec5SDimitry Andric 
42985ffd83dbSDimitry Andric     Operand = CI->getCalledOperand();
42990b57cec5SDimitry Andric     FunctionType *FTy = CI->getFunctionType();
43000b57cec5SDimitry Andric     Type *RetTy = FTy->getReturnType();
43010b57cec5SDimitry Andric     const AttributeList &PAL = CI->getAttributes();
43020b57cec5SDimitry Andric 
4303349cc55cSDimitry Andric     if (PAL.hasRetAttrs())
43040b57cec5SDimitry Andric       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric     // Only print addrspace(N) if necessary:
43070b57cec5SDimitry Andric     maybePrintCallAddrSpace(Operand, &I, Out);
43080b57cec5SDimitry Andric 
43090b57cec5SDimitry Andric     // If possible, print out the short form of the call instruction.  We can
43100b57cec5SDimitry Andric     // only do this if the first argument is a pointer to a nonvararg function,
43110b57cec5SDimitry Andric     // and if the return type is not a pointer to a function.
43120b57cec5SDimitry Andric     Out << ' ';
43130b57cec5SDimitry Andric     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
43140b57cec5SDimitry Andric     Out << ' ';
43150b57cec5SDimitry Andric     writeOperand(Operand, false);
43160b57cec5SDimitry Andric     Out << '(';
4317349cc55cSDimitry Andric     for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) {
43180b57cec5SDimitry Andric       if (op > 0)
43190b57cec5SDimitry Andric         Out << ", ";
4320349cc55cSDimitry Andric       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op));
43210b57cec5SDimitry Andric     }
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric     // Emit an ellipsis if this is a musttail call in a vararg function.  This
43240b57cec5SDimitry Andric     // is only to aid readability, musttail calls forward varargs by default.
43250b57cec5SDimitry Andric     if (CI->isMustTailCall() && CI->getParent() &&
43260b57cec5SDimitry Andric         CI->getParent()->getParent() &&
4327bdd1243dSDimitry Andric         CI->getParent()->getParent()->isVarArg()) {
4328bdd1243dSDimitry Andric       if (CI->arg_size() > 0)
4329bdd1243dSDimitry Andric         Out << ", ";
4330bdd1243dSDimitry Andric       Out << "...";
4331bdd1243dSDimitry Andric     }
43320b57cec5SDimitry Andric 
43330b57cec5SDimitry Andric     Out << ')';
4334349cc55cSDimitry Andric     if (PAL.hasFnAttrs())
4335349cc55cSDimitry Andric       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
43360b57cec5SDimitry Andric 
43370b57cec5SDimitry Andric     writeOperandBundles(CI);
43380b57cec5SDimitry Andric   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
43395ffd83dbSDimitry Andric     Operand = II->getCalledOperand();
43400b57cec5SDimitry Andric     FunctionType *FTy = II->getFunctionType();
43410b57cec5SDimitry Andric     Type *RetTy = FTy->getReturnType();
43420b57cec5SDimitry Andric     const AttributeList &PAL = II->getAttributes();
43430b57cec5SDimitry Andric 
43440b57cec5SDimitry Andric     // Print the calling convention being used.
43450b57cec5SDimitry Andric     if (II->getCallingConv() != CallingConv::C) {
43460b57cec5SDimitry Andric       Out << " ";
43470b57cec5SDimitry Andric       PrintCallingConv(II->getCallingConv(), Out);
43480b57cec5SDimitry Andric     }
43490b57cec5SDimitry Andric 
4350349cc55cSDimitry Andric     if (PAL.hasRetAttrs())
43510b57cec5SDimitry Andric       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric     // Only print addrspace(N) if necessary:
43540b57cec5SDimitry Andric     maybePrintCallAddrSpace(Operand, &I, Out);
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric     // If possible, print out the short form of the invoke instruction. We can
43570b57cec5SDimitry Andric     // only do this if the first argument is a pointer to a nonvararg function,
43580b57cec5SDimitry Andric     // and if the return type is not a pointer to a function.
43590b57cec5SDimitry Andric     //
43600b57cec5SDimitry Andric     Out << ' ';
43610b57cec5SDimitry Andric     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
43620b57cec5SDimitry Andric     Out << ' ';
43630b57cec5SDimitry Andric     writeOperand(Operand, false);
43640b57cec5SDimitry Andric     Out << '(';
4365349cc55cSDimitry Andric     for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) {
43660b57cec5SDimitry Andric       if (op)
43670b57cec5SDimitry Andric         Out << ", ";
4368349cc55cSDimitry Andric       writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op));
43690b57cec5SDimitry Andric     }
43700b57cec5SDimitry Andric 
43710b57cec5SDimitry Andric     Out << ')';
4372349cc55cSDimitry Andric     if (PAL.hasFnAttrs())
4373349cc55cSDimitry Andric       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
43740b57cec5SDimitry Andric 
43750b57cec5SDimitry Andric     writeOperandBundles(II);
43760b57cec5SDimitry Andric 
43770b57cec5SDimitry Andric     Out << "\n          to ";
43780b57cec5SDimitry Andric     writeOperand(II->getNormalDest(), true);
43790b57cec5SDimitry Andric     Out << " unwind ";
43800b57cec5SDimitry Andric     writeOperand(II->getUnwindDest(), true);
43810b57cec5SDimitry Andric   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
43825ffd83dbSDimitry Andric     Operand = CBI->getCalledOperand();
43830b57cec5SDimitry Andric     FunctionType *FTy = CBI->getFunctionType();
43840b57cec5SDimitry Andric     Type *RetTy = FTy->getReturnType();
43850b57cec5SDimitry Andric     const AttributeList &PAL = CBI->getAttributes();
43860b57cec5SDimitry Andric 
43870b57cec5SDimitry Andric     // Print the calling convention being used.
43880b57cec5SDimitry Andric     if (CBI->getCallingConv() != CallingConv::C) {
43890b57cec5SDimitry Andric       Out << " ";
43900b57cec5SDimitry Andric       PrintCallingConv(CBI->getCallingConv(), Out);
43910b57cec5SDimitry Andric     }
43920b57cec5SDimitry Andric 
4393349cc55cSDimitry Andric     if (PAL.hasRetAttrs())
43940b57cec5SDimitry Andric       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
43950b57cec5SDimitry Andric 
43960b57cec5SDimitry Andric     // If possible, print out the short form of the callbr instruction. We can
43970b57cec5SDimitry Andric     // only do this if the first argument is a pointer to a nonvararg function,
43980b57cec5SDimitry Andric     // and if the return type is not a pointer to a function.
43990b57cec5SDimitry Andric     //
44000b57cec5SDimitry Andric     Out << ' ';
44010b57cec5SDimitry Andric     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
44020b57cec5SDimitry Andric     Out << ' ';
44030b57cec5SDimitry Andric     writeOperand(Operand, false);
44040b57cec5SDimitry Andric     Out << '(';
4405349cc55cSDimitry Andric     for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) {
44060b57cec5SDimitry Andric       if (op)
44070b57cec5SDimitry Andric         Out << ", ";
4408349cc55cSDimitry Andric       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op));
44090b57cec5SDimitry Andric     }
44100b57cec5SDimitry Andric 
44110b57cec5SDimitry Andric     Out << ')';
4412349cc55cSDimitry Andric     if (PAL.hasFnAttrs())
4413349cc55cSDimitry Andric       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs());
44140b57cec5SDimitry Andric 
44150b57cec5SDimitry Andric     writeOperandBundles(CBI);
44160b57cec5SDimitry Andric 
44170b57cec5SDimitry Andric     Out << "\n          to ";
44180b57cec5SDimitry Andric     writeOperand(CBI->getDefaultDest(), true);
44190b57cec5SDimitry Andric     Out << " [";
44200b57cec5SDimitry Andric     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
44210b57cec5SDimitry Andric       if (i != 0)
44220b57cec5SDimitry Andric         Out << ", ";
44230b57cec5SDimitry Andric       writeOperand(CBI->getIndirectDest(i), true);
44240b57cec5SDimitry Andric     }
44250b57cec5SDimitry Andric     Out << ']';
44260b57cec5SDimitry Andric   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
44270b57cec5SDimitry Andric     Out << ' ';
44280b57cec5SDimitry Andric     if (AI->isUsedWithInAlloca())
44290b57cec5SDimitry Andric       Out << "inalloca ";
44300b57cec5SDimitry Andric     if (AI->isSwiftError())
44310b57cec5SDimitry Andric       Out << "swifterror ";
44320b57cec5SDimitry Andric     TypePrinter.print(AI->getAllocatedType(), Out);
44330b57cec5SDimitry Andric 
44340b57cec5SDimitry Andric     // Explicitly write the array size if the code is broken, if it's an array
44350b57cec5SDimitry Andric     // allocation, or if the type is not canonical for scalar allocations.  The
44360b57cec5SDimitry Andric     // latter case prevents the type from mutating when round-tripping through
44370b57cec5SDimitry Andric     // assembly.
44380b57cec5SDimitry Andric     if (!AI->getArraySize() || AI->isArrayAllocation() ||
44390b57cec5SDimitry Andric         !AI->getArraySize()->getType()->isIntegerTy(32)) {
44400b57cec5SDimitry Andric       Out << ", ";
44410b57cec5SDimitry Andric       writeOperand(AI->getArraySize(), true);
44420b57cec5SDimitry Andric     }
44430eae32dcSDimitry Andric     if (MaybeAlign A = AI->getAlign()) {
44440eae32dcSDimitry Andric       Out << ", align " << A->value();
44450b57cec5SDimitry Andric     }
44460b57cec5SDimitry Andric 
4447bdd1243dSDimitry Andric     unsigned AddrSpace = AI->getAddressSpace();
44480b57cec5SDimitry Andric     if (AddrSpace != 0) {
44490b57cec5SDimitry Andric       Out << ", addrspace(" << AddrSpace << ')';
44500b57cec5SDimitry Andric     }
44510b57cec5SDimitry Andric   } else if (isa<CastInst>(I)) {
44520b57cec5SDimitry Andric     if (Operand) {
44530b57cec5SDimitry Andric       Out << ' ';
44540b57cec5SDimitry Andric       writeOperand(Operand, true);   // Work with broken code
44550b57cec5SDimitry Andric     }
44560b57cec5SDimitry Andric     Out << " to ";
44570b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
44580b57cec5SDimitry Andric   } else if (isa<VAArgInst>(I)) {
44590b57cec5SDimitry Andric     if (Operand) {
44600b57cec5SDimitry Andric       Out << ' ';
44610b57cec5SDimitry Andric       writeOperand(Operand, true);   // Work with broken code
44620b57cec5SDimitry Andric     }
44630b57cec5SDimitry Andric     Out << ", ";
44640b57cec5SDimitry Andric     TypePrinter.print(I.getType(), Out);
44650b57cec5SDimitry Andric   } else if (Operand) {   // Print the normal way.
44660b57cec5SDimitry Andric     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
44670b57cec5SDimitry Andric       Out << ' ';
44680b57cec5SDimitry Andric       TypePrinter.print(GEP->getSourceElementType(), Out);
44690b57cec5SDimitry Andric       Out << ',';
44700b57cec5SDimitry Andric     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
44710b57cec5SDimitry Andric       Out << ' ';
44720b57cec5SDimitry Andric       TypePrinter.print(LI->getType(), Out);
44730b57cec5SDimitry Andric       Out << ',';
44740b57cec5SDimitry Andric     }
44750b57cec5SDimitry Andric 
44760b57cec5SDimitry Andric     // PrintAllTypes - Instructions who have operands of all the same type
44770b57cec5SDimitry Andric     // omit the type from all but the first operand.  If the instruction has
44780b57cec5SDimitry Andric     // different type operands (for example br), then they are all printed.
44790b57cec5SDimitry Andric     bool PrintAllTypes = false;
44800b57cec5SDimitry Andric     Type *TheType = Operand->getType();
44810b57cec5SDimitry Andric 
4482bdd1243dSDimitry Andric     // Select, Store, ShuffleVector, CmpXchg and AtomicRMW always print all
4483bdd1243dSDimitry Andric     // types.
4484753f127fSDimitry Andric     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) ||
4485bdd1243dSDimitry Andric         isa<ReturnInst>(I) || isa<AtomicCmpXchgInst>(I) ||
4486bdd1243dSDimitry Andric         isa<AtomicRMWInst>(I)) {
44870b57cec5SDimitry Andric       PrintAllTypes = true;
44880b57cec5SDimitry Andric     } else {
44890b57cec5SDimitry Andric       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
44900b57cec5SDimitry Andric         Operand = I.getOperand(i);
44910b57cec5SDimitry Andric         // note that Operand shouldn't be null, but the test helps make dump()
44920b57cec5SDimitry Andric         // more tolerant of malformed IR
44930b57cec5SDimitry Andric         if (Operand && Operand->getType() != TheType) {
44940b57cec5SDimitry Andric           PrintAllTypes = true;    // We have differing types!  Print them all!
44950b57cec5SDimitry Andric           break;
44960b57cec5SDimitry Andric         }
44970b57cec5SDimitry Andric       }
44980b57cec5SDimitry Andric     }
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric     if (!PrintAllTypes) {
45010b57cec5SDimitry Andric       Out << ' ';
45020b57cec5SDimitry Andric       TypePrinter.print(TheType, Out);
45030b57cec5SDimitry Andric     }
45040b57cec5SDimitry Andric 
45050b57cec5SDimitry Andric     Out << ' ';
45060b57cec5SDimitry Andric     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
45070b57cec5SDimitry Andric       if (i) Out << ", ";
45080b57cec5SDimitry Andric       writeOperand(I.getOperand(i), PrintAllTypes);
45090b57cec5SDimitry Andric     }
45100b57cec5SDimitry Andric   }
45110b57cec5SDimitry Andric 
45120b57cec5SDimitry Andric   // Print atomic ordering/alignment for memory operations
45130b57cec5SDimitry Andric   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
45140b57cec5SDimitry Andric     if (LI->isAtomic())
45150b57cec5SDimitry Andric       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
45160eae32dcSDimitry Andric     if (MaybeAlign A = LI->getAlign())
45170eae32dcSDimitry Andric       Out << ", align " << A->value();
45180b57cec5SDimitry Andric   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
45190b57cec5SDimitry Andric     if (SI->isAtomic())
45200b57cec5SDimitry Andric       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
45210eae32dcSDimitry Andric     if (MaybeAlign A = SI->getAlign())
45220eae32dcSDimitry Andric       Out << ", align " << A->value();
45230b57cec5SDimitry Andric   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
45240b57cec5SDimitry Andric     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
45250b57cec5SDimitry Andric                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4526fe6060f1SDimitry Andric     Out << ", align " << CXI->getAlign().value();
45270b57cec5SDimitry Andric   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
45280b57cec5SDimitry Andric     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
45290b57cec5SDimitry Andric                 RMWI->getSyncScopeID());
4530fe6060f1SDimitry Andric     Out << ", align " << RMWI->getAlign().value();
45310b57cec5SDimitry Andric   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
45320b57cec5SDimitry Andric     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
45335ffd83dbSDimitry Andric   } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
45345ffd83dbSDimitry Andric     PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
45350b57cec5SDimitry Andric   }
45360b57cec5SDimitry Andric 
45370b57cec5SDimitry Andric   // Print Metadata info.
45380b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
45390b57cec5SDimitry Andric   I.getAllMetadata(InstMD);
45400b57cec5SDimitry Andric   printMetadataAttachments(InstMD, ", ");
45410b57cec5SDimitry Andric 
45420b57cec5SDimitry Andric   // Print a nice comment.
45430b57cec5SDimitry Andric   printInfoComment(I);
45440b57cec5SDimitry Andric }
45450b57cec5SDimitry Andric 
4546*5f757f3fSDimitry Andric void AssemblyWriter::printDPMarker(const DPMarker &Marker) {
4547*5f757f3fSDimitry Andric   // There's no formal representation of a DPMarker -- print purely as a
4548*5f757f3fSDimitry Andric   // debugging aid.
4549*5f757f3fSDimitry Andric   for (const DPValue &DPI2 : Marker.StoredDPValues) {
4550*5f757f3fSDimitry Andric     printDPValue(DPI2);
4551*5f757f3fSDimitry Andric     Out << "\n";
4552*5f757f3fSDimitry Andric   }
4553*5f757f3fSDimitry Andric 
4554*5f757f3fSDimitry Andric   Out << "  DPMarker -> { ";
4555*5f757f3fSDimitry Andric   printInstruction(*Marker.MarkedInstr);
4556*5f757f3fSDimitry Andric   Out << " }";
4557*5f757f3fSDimitry Andric   return;
4558*5f757f3fSDimitry Andric }
4559*5f757f3fSDimitry Andric 
4560*5f757f3fSDimitry Andric void AssemblyWriter::printDPValue(const DPValue &Value) {
4561*5f757f3fSDimitry Andric   // There's no formal representation of a DPValue -- print purely as a
4562*5f757f3fSDimitry Andric   // debugging aid.
4563*5f757f3fSDimitry Andric   Out << "  DPValue { ";
4564*5f757f3fSDimitry Andric   auto WriterCtx = getContext();
4565*5f757f3fSDimitry Andric   WriteAsOperandInternal(Out, Value.getRawLocation(), WriterCtx, true);
4566*5f757f3fSDimitry Andric   Out << ", ";
4567*5f757f3fSDimitry Andric   WriteAsOperandInternal(Out, Value.getVariable(), WriterCtx, true);
4568*5f757f3fSDimitry Andric   Out << ", ";
4569*5f757f3fSDimitry Andric   WriteAsOperandInternal(Out, Value.getExpression(), WriterCtx, true);
4570*5f757f3fSDimitry Andric   Out << ", ";
4571*5f757f3fSDimitry Andric   WriteAsOperandInternal(Out, Value.getDebugLoc().get(), WriterCtx, true);
4572*5f757f3fSDimitry Andric   Out << " marker @" << Value.getMarker();
4573*5f757f3fSDimitry Andric   Out << " }";
4574*5f757f3fSDimitry Andric }
4575*5f757f3fSDimitry Andric 
45760b57cec5SDimitry Andric void AssemblyWriter::printMetadataAttachments(
45770b57cec5SDimitry Andric     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
45780b57cec5SDimitry Andric     StringRef Separator) {
45790b57cec5SDimitry Andric   if (MDs.empty())
45800b57cec5SDimitry Andric     return;
45810b57cec5SDimitry Andric 
45820b57cec5SDimitry Andric   if (MDNames.empty())
45830b57cec5SDimitry Andric     MDs[0].second->getContext().getMDKindNames(MDNames);
45840b57cec5SDimitry Andric 
4585349cc55cSDimitry Andric   auto WriterCtx = getContext();
45860b57cec5SDimitry Andric   for (const auto &I : MDs) {
45870b57cec5SDimitry Andric     unsigned Kind = I.first;
45880b57cec5SDimitry Andric     Out << Separator;
45890b57cec5SDimitry Andric     if (Kind < MDNames.size()) {
45900b57cec5SDimitry Andric       Out << "!";
45910b57cec5SDimitry Andric       printMetadataIdentifier(MDNames[Kind], Out);
45920b57cec5SDimitry Andric     } else
45930b57cec5SDimitry Andric       Out << "!<unknown kind #" << Kind << ">";
45940b57cec5SDimitry Andric     Out << ' ';
4595349cc55cSDimitry Andric     WriteAsOperandInternal(Out, I.second, WriterCtx);
45960b57cec5SDimitry Andric   }
45970b57cec5SDimitry Andric }
45980b57cec5SDimitry Andric 
45990b57cec5SDimitry Andric void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
46000b57cec5SDimitry Andric   Out << '!' << Slot << " = ";
46010b57cec5SDimitry Andric   printMDNodeBody(Node);
46020b57cec5SDimitry Andric   Out << "\n";
46030b57cec5SDimitry Andric }
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric void AssemblyWriter::writeAllMDNodes() {
46060b57cec5SDimitry Andric   SmallVector<const MDNode *, 16> Nodes;
46070b57cec5SDimitry Andric   Nodes.resize(Machine.mdn_size());
4608fe6060f1SDimitry Andric   for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end()))
4609fe6060f1SDimitry Andric     Nodes[I.second] = cast<MDNode>(I.first);
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
46120b57cec5SDimitry Andric     writeMDNode(i, Nodes[i]);
46130b57cec5SDimitry Andric   }
46140b57cec5SDimitry Andric }
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4617349cc55cSDimitry Andric   auto WriterCtx = getContext();
4618349cc55cSDimitry Andric   WriteMDNodeBodyInternal(Out, Node, WriterCtx);
46190b57cec5SDimitry Andric }
46200b57cec5SDimitry Andric 
4621480093f4SDimitry Andric void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4622480093f4SDimitry Andric   if (!Attr.isTypeAttribute()) {
4623480093f4SDimitry Andric     Out << Attr.getAsString(InAttrGroup);
4624480093f4SDimitry Andric     return;
4625480093f4SDimitry Andric   }
4626480093f4SDimitry Andric 
4627fe6060f1SDimitry Andric   Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum());
4628480093f4SDimitry Andric   if (Type *Ty = Attr.getValueAsType()) {
4629480093f4SDimitry Andric     Out << '(';
4630480093f4SDimitry Andric     TypePrinter.print(Ty, Out);
4631480093f4SDimitry Andric     Out << ')';
4632480093f4SDimitry Andric   }
4633480093f4SDimitry Andric }
4634480093f4SDimitry Andric 
4635480093f4SDimitry Andric void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4636480093f4SDimitry Andric                                        bool InAttrGroup) {
4637480093f4SDimitry Andric   bool FirstAttr = true;
4638480093f4SDimitry Andric   for (const auto &Attr : AttrSet) {
4639480093f4SDimitry Andric     if (!FirstAttr)
4640480093f4SDimitry Andric       Out << ' ';
4641480093f4SDimitry Andric     writeAttribute(Attr, InAttrGroup);
4642480093f4SDimitry Andric     FirstAttr = false;
4643480093f4SDimitry Andric   }
4644480093f4SDimitry Andric }
4645480093f4SDimitry Andric 
46460b57cec5SDimitry Andric void AssemblyWriter::writeAllAttributeGroups() {
46470b57cec5SDimitry Andric   std::vector<std::pair<AttributeSet, unsigned>> asVec;
46480b57cec5SDimitry Andric   asVec.resize(Machine.as_size());
46490b57cec5SDimitry Andric 
4650fe6060f1SDimitry Andric   for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end()))
4651fe6060f1SDimitry Andric     asVec[I.second] = I;
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric   for (const auto &I : asVec)
46540b57cec5SDimitry Andric     Out << "attributes #" << I.second << " = { "
46550b57cec5SDimitry Andric         << I.first.getAsString(true) << " }\n";
46560b57cec5SDimitry Andric }
46570b57cec5SDimitry Andric 
4658fe6060f1SDimitry Andric void AssemblyWriter::printUseListOrder(const Value *V,
4659fe6060f1SDimitry Andric                                        const std::vector<unsigned> &Shuffle) {
46600b57cec5SDimitry Andric   bool IsInFunction = Machine.getFunction();
46610b57cec5SDimitry Andric   if (IsInFunction)
46620b57cec5SDimitry Andric     Out << "  ";
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric   Out << "uselistorder";
4665fe6060f1SDimitry Andric   if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) {
46660b57cec5SDimitry Andric     Out << "_bb ";
46670b57cec5SDimitry Andric     writeOperand(BB->getParent(), false);
46680b57cec5SDimitry Andric     Out << ", ";
46690b57cec5SDimitry Andric     writeOperand(BB, false);
46700b57cec5SDimitry Andric   } else {
46710b57cec5SDimitry Andric     Out << " ";
4672fe6060f1SDimitry Andric     writeOperand(V, true);
46730b57cec5SDimitry Andric   }
46740b57cec5SDimitry Andric   Out << ", { ";
46750b57cec5SDimitry Andric 
4676fe6060f1SDimitry Andric   assert(Shuffle.size() >= 2 && "Shuffle too small");
4677fe6060f1SDimitry Andric   Out << Shuffle[0];
4678fe6060f1SDimitry Andric   for (unsigned I = 1, E = Shuffle.size(); I != E; ++I)
4679fe6060f1SDimitry Andric     Out << ", " << Shuffle[I];
46800b57cec5SDimitry Andric   Out << " }\n";
46810b57cec5SDimitry Andric }
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric void AssemblyWriter::printUseLists(const Function *F) {
4684fe6060f1SDimitry Andric   auto It = UseListOrders.find(F);
4685fe6060f1SDimitry Andric   if (It == UseListOrders.end())
46860b57cec5SDimitry Andric     return;
46870b57cec5SDimitry Andric 
46880b57cec5SDimitry Andric   Out << "\n; uselistorder directives\n";
4689fe6060f1SDimitry Andric   for (const auto &Pair : It->second)
4690fe6060f1SDimitry Andric     printUseListOrder(Pair.first, Pair.second);
46910b57cec5SDimitry Andric }
46920b57cec5SDimitry Andric 
46930b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
46940b57cec5SDimitry Andric //                       External Interface declarations
46950b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
46980b57cec5SDimitry Andric                      bool ShouldPreserveUseListOrder,
46990b57cec5SDimitry Andric                      bool IsForDebug) const {
47000b57cec5SDimitry Andric   SlotTracker SlotTable(this->getParent());
47010b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
47020b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
47030b57cec5SDimitry Andric                    IsForDebug,
47040b57cec5SDimitry Andric                    ShouldPreserveUseListOrder);
47050b57cec5SDimitry Andric   W.printFunction(this);
47060b57cec5SDimitry Andric }
47070b57cec5SDimitry Andric 
47085ffd83dbSDimitry Andric void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
47095ffd83dbSDimitry Andric                      bool ShouldPreserveUseListOrder,
47105ffd83dbSDimitry Andric                      bool IsForDebug) const {
4711e8d8bef9SDimitry Andric   SlotTracker SlotTable(this->getParent());
47125ffd83dbSDimitry Andric   formatted_raw_ostream OS(ROS);
47135ffd83dbSDimitry Andric   AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
47145ffd83dbSDimitry Andric                    IsForDebug,
47155ffd83dbSDimitry Andric                    ShouldPreserveUseListOrder);
47165ffd83dbSDimitry Andric   W.printBasicBlock(this);
47175ffd83dbSDimitry Andric }
47185ffd83dbSDimitry Andric 
47190b57cec5SDimitry Andric void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
47200b57cec5SDimitry Andric                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4721*5f757f3fSDimitry Andric   // RemoveDIs: always print with debug-info in intrinsic format.
4722*5f757f3fSDimitry Andric   bool ConvertAfter = IsNewDbgInfoFormat;
4723*5f757f3fSDimitry Andric   if (IsNewDbgInfoFormat)
4724*5f757f3fSDimitry Andric     const_cast<Module *>(this)->convertFromNewDbgValues();
4725*5f757f3fSDimitry Andric 
47260b57cec5SDimitry Andric   SlotTracker SlotTable(this);
47270b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
47280b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
47290b57cec5SDimitry Andric                    ShouldPreserveUseListOrder);
47300b57cec5SDimitry Andric   W.printModule(this);
4731*5f757f3fSDimitry Andric 
4732*5f757f3fSDimitry Andric   if (ConvertAfter)
4733*5f757f3fSDimitry Andric     const_cast<Module *>(this)->convertToNewDbgValues();
47340b57cec5SDimitry Andric }
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
47370b57cec5SDimitry Andric   SlotTracker SlotTable(getParent());
47380b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
47390b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
47400b57cec5SDimitry Andric   W.printNamedMDNode(this);
47410b57cec5SDimitry Andric }
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
47440b57cec5SDimitry Andric                         bool IsForDebug) const {
4745bdd1243dSDimitry Andric   std::optional<SlotTracker> LocalST;
47460b57cec5SDimitry Andric   SlotTracker *SlotTable;
47470b57cec5SDimitry Andric   if (auto *ST = MST.getMachine())
47480b57cec5SDimitry Andric     SlotTable = ST;
47490b57cec5SDimitry Andric   else {
47500b57cec5SDimitry Andric     LocalST.emplace(getParent());
47510b57cec5SDimitry Andric     SlotTable = &*LocalST;
47520b57cec5SDimitry Andric   }
47530b57cec5SDimitry Andric 
47540b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
47550b57cec5SDimitry Andric   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
47560b57cec5SDimitry Andric   W.printNamedMDNode(this);
47570b57cec5SDimitry Andric }
47580b57cec5SDimitry Andric 
47590b57cec5SDimitry Andric void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
47600b57cec5SDimitry Andric   PrintLLVMName(ROS, getName(), ComdatPrefix);
47610b57cec5SDimitry Andric   ROS << " = comdat ";
47620b57cec5SDimitry Andric 
47630b57cec5SDimitry Andric   switch (getSelectionKind()) {
47640b57cec5SDimitry Andric   case Comdat::Any:
47650b57cec5SDimitry Andric     ROS << "any";
47660b57cec5SDimitry Andric     break;
47670b57cec5SDimitry Andric   case Comdat::ExactMatch:
47680b57cec5SDimitry Andric     ROS << "exactmatch";
47690b57cec5SDimitry Andric     break;
47700b57cec5SDimitry Andric   case Comdat::Largest:
47710b57cec5SDimitry Andric     ROS << "largest";
47720b57cec5SDimitry Andric     break;
4773fe6060f1SDimitry Andric   case Comdat::NoDeduplicate:
4774fe6060f1SDimitry Andric     ROS << "nodeduplicate";
47750b57cec5SDimitry Andric     break;
47760b57cec5SDimitry Andric   case Comdat::SameSize:
47770b57cec5SDimitry Andric     ROS << "samesize";
47780b57cec5SDimitry Andric     break;
47790b57cec5SDimitry Andric   }
47800b57cec5SDimitry Andric 
47810b57cec5SDimitry Andric   ROS << '\n';
47820b57cec5SDimitry Andric }
47830b57cec5SDimitry Andric 
47840b57cec5SDimitry Andric void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
47850b57cec5SDimitry Andric   TypePrinting TP;
47860b57cec5SDimitry Andric   TP.print(const_cast<Type*>(this), OS);
47870b57cec5SDimitry Andric 
47880b57cec5SDimitry Andric   if (NoDetails)
47890b57cec5SDimitry Andric     return;
47900b57cec5SDimitry Andric 
47910b57cec5SDimitry Andric   // If the type is a named struct type, print the body as well.
47920b57cec5SDimitry Andric   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
47930b57cec5SDimitry Andric     if (!STy->isLiteral()) {
47940b57cec5SDimitry Andric       OS << " = type ";
47950b57cec5SDimitry Andric       TP.printStructBody(STy, OS);
47960b57cec5SDimitry Andric     }
47970b57cec5SDimitry Andric }
47980b57cec5SDimitry Andric 
47990b57cec5SDimitry Andric static bool isReferencingMDNode(const Instruction &I) {
48000b57cec5SDimitry Andric   if (const auto *CI = dyn_cast<CallInst>(&I))
48010b57cec5SDimitry Andric     if (Function *F = CI->getCalledFunction())
48020b57cec5SDimitry Andric       if (F->isIntrinsic())
48030b57cec5SDimitry Andric         for (auto &Op : I.operands())
48040b57cec5SDimitry Andric           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
48050b57cec5SDimitry Andric             if (isa<MDNode>(V->getMetadata()))
48060b57cec5SDimitry Andric               return true;
48070b57cec5SDimitry Andric   return false;
48080b57cec5SDimitry Andric }
48090b57cec5SDimitry Andric 
4810*5f757f3fSDimitry Andric void DPMarker::print(raw_ostream &ROS, bool IsForDebug) const {
4811*5f757f3fSDimitry Andric 
4812*5f757f3fSDimitry Andric   ModuleSlotTracker MST(getModuleFromDPI(this), true);
4813*5f757f3fSDimitry Andric   print(ROS, MST, IsForDebug);
4814*5f757f3fSDimitry Andric }
4815*5f757f3fSDimitry Andric 
4816*5f757f3fSDimitry Andric void DPValue::print(raw_ostream &ROS, bool IsForDebug) const {
4817*5f757f3fSDimitry Andric 
4818*5f757f3fSDimitry Andric   ModuleSlotTracker MST(getModuleFromDPI(this), true);
4819*5f757f3fSDimitry Andric   print(ROS, MST, IsForDebug);
4820*5f757f3fSDimitry Andric }
4821*5f757f3fSDimitry Andric 
4822*5f757f3fSDimitry Andric void DPMarker::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4823*5f757f3fSDimitry Andric                      bool IsForDebug) const {
4824*5f757f3fSDimitry Andric   // There's no formal representation of a DPMarker -- print purely as a
4825*5f757f3fSDimitry Andric   // debugging aid.
4826*5f757f3fSDimitry Andric   formatted_raw_ostream OS(ROS);
4827*5f757f3fSDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4828*5f757f3fSDimitry Andric   SlotTracker &SlotTable =
4829*5f757f3fSDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4830*5f757f3fSDimitry Andric   auto incorporateFunction = [&](const Function *F) {
4831*5f757f3fSDimitry Andric     if (F)
4832*5f757f3fSDimitry Andric       MST.incorporateFunction(*F);
4833*5f757f3fSDimitry Andric   };
4834*5f757f3fSDimitry Andric   incorporateFunction(getParent() ? getParent()->getParent() : nullptr);
4835*5f757f3fSDimitry Andric   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
4836*5f757f3fSDimitry Andric   W.printDPMarker(*this);
4837*5f757f3fSDimitry Andric }
4838*5f757f3fSDimitry Andric 
4839*5f757f3fSDimitry Andric void DPValue::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4840*5f757f3fSDimitry Andric                     bool IsForDebug) const {
4841*5f757f3fSDimitry Andric   // There's no formal representation of a DPValue -- print purely as a
4842*5f757f3fSDimitry Andric   // debugging aid.
4843*5f757f3fSDimitry Andric   formatted_raw_ostream OS(ROS);
4844*5f757f3fSDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4845*5f757f3fSDimitry Andric   SlotTracker &SlotTable =
4846*5f757f3fSDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4847*5f757f3fSDimitry Andric   auto incorporateFunction = [&](const Function *F) {
4848*5f757f3fSDimitry Andric     if (F)
4849*5f757f3fSDimitry Andric       MST.incorporateFunction(*F);
4850*5f757f3fSDimitry Andric   };
4851*5f757f3fSDimitry Andric   incorporateFunction(Marker->getParent() ? Marker->getParent()->getParent()
4852*5f757f3fSDimitry Andric                                           : nullptr);
4853*5f757f3fSDimitry Andric   AssemblyWriter W(OS, SlotTable, getModuleFromDPI(this), nullptr, IsForDebug);
4854*5f757f3fSDimitry Andric   W.printDPValue(*this);
4855*5f757f3fSDimitry Andric }
4856*5f757f3fSDimitry Andric 
48570b57cec5SDimitry Andric void Value::print(raw_ostream &ROS, bool IsForDebug) const {
48580b57cec5SDimitry Andric   bool ShouldInitializeAllMetadata = false;
48590b57cec5SDimitry Andric   if (auto *I = dyn_cast<Instruction>(this))
48600b57cec5SDimitry Andric     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
48610b57cec5SDimitry Andric   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
48620b57cec5SDimitry Andric     ShouldInitializeAllMetadata = true;
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
48650b57cec5SDimitry Andric   print(ROS, MST, IsForDebug);
48660b57cec5SDimitry Andric }
48670b57cec5SDimitry Andric 
48680b57cec5SDimitry Andric void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
48690b57cec5SDimitry Andric                   bool IsForDebug) const {
48700b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
48710b57cec5SDimitry Andric   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
48720b57cec5SDimitry Andric   SlotTracker &SlotTable =
48730b57cec5SDimitry Andric       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
48740b57cec5SDimitry Andric   auto incorporateFunction = [&](const Function *F) {
48750b57cec5SDimitry Andric     if (F)
48760b57cec5SDimitry Andric       MST.incorporateFunction(*F);
48770b57cec5SDimitry Andric   };
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(this)) {
48800b57cec5SDimitry Andric     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
48810b57cec5SDimitry Andric     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
48820b57cec5SDimitry Andric     W.printInstruction(*I);
48830b57cec5SDimitry Andric   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
48840b57cec5SDimitry Andric     incorporateFunction(BB->getParent());
48850b57cec5SDimitry Andric     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
48860b57cec5SDimitry Andric     W.printBasicBlock(BB);
48870b57cec5SDimitry Andric   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
48880b57cec5SDimitry Andric     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
48890b57cec5SDimitry Andric     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
48900b57cec5SDimitry Andric       W.printGlobal(V);
48910b57cec5SDimitry Andric     else if (const Function *F = dyn_cast<Function>(GV))
48920b57cec5SDimitry Andric       W.printFunction(F);
4893349cc55cSDimitry Andric     else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
4894349cc55cSDimitry Andric       W.printAlias(A);
4895349cc55cSDimitry Andric     else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV))
4896349cc55cSDimitry Andric       W.printIFunc(I);
48970b57cec5SDimitry Andric     else
4898349cc55cSDimitry Andric       llvm_unreachable("Unknown GlobalValue to print out!");
48990b57cec5SDimitry Andric   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
49000b57cec5SDimitry Andric     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
49010b57cec5SDimitry Andric   } else if (const Constant *C = dyn_cast<Constant>(this)) {
49020b57cec5SDimitry Andric     TypePrinting TypePrinter;
49030b57cec5SDimitry Andric     TypePrinter.print(C->getType(), OS);
49040b57cec5SDimitry Andric     OS << ' ';
4905349cc55cSDimitry Andric     AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine());
4906349cc55cSDimitry Andric     WriteConstantInternal(OS, C, WriterCtx);
49070b57cec5SDimitry Andric   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
49080b57cec5SDimitry Andric     this->printAsOperand(OS, /* PrintType */ true, MST);
49090b57cec5SDimitry Andric   } else {
49100b57cec5SDimitry Andric     llvm_unreachable("Unknown value to print out!");
49110b57cec5SDimitry Andric   }
49120b57cec5SDimitry Andric }
49130b57cec5SDimitry Andric 
49140b57cec5SDimitry Andric /// Print without a type, skipping the TypePrinting object.
49150b57cec5SDimitry Andric ///
49160b57cec5SDimitry Andric /// \return \c true iff printing was successful.
49170b57cec5SDimitry Andric static bool printWithoutType(const Value &V, raw_ostream &O,
49180b57cec5SDimitry Andric                              SlotTracker *Machine, const Module *M) {
49190b57cec5SDimitry Andric   if (V.hasName() || isa<GlobalValue>(V) ||
49200b57cec5SDimitry Andric       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4921349cc55cSDimitry Andric     AsmWriterContext WriterCtx(nullptr, Machine, M);
4922349cc55cSDimitry Andric     WriteAsOperandInternal(O, &V, WriterCtx);
49230b57cec5SDimitry Andric     return true;
49240b57cec5SDimitry Andric   }
49250b57cec5SDimitry Andric   return false;
49260b57cec5SDimitry Andric }
49270b57cec5SDimitry Andric 
49280b57cec5SDimitry Andric static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
49290b57cec5SDimitry Andric                                ModuleSlotTracker &MST) {
49300b57cec5SDimitry Andric   TypePrinting TypePrinter(MST.getModule());
49310b57cec5SDimitry Andric   if (PrintType) {
49320b57cec5SDimitry Andric     TypePrinter.print(V.getType(), O);
49330b57cec5SDimitry Andric     O << ' ';
49340b57cec5SDimitry Andric   }
49350b57cec5SDimitry Andric 
4936349cc55cSDimitry Andric   AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule());
4937349cc55cSDimitry Andric   WriteAsOperandInternal(O, &V, WriterCtx);
49380b57cec5SDimitry Andric }
49390b57cec5SDimitry Andric 
49400b57cec5SDimitry Andric void Value::printAsOperand(raw_ostream &O, bool PrintType,
49410b57cec5SDimitry Andric                            const Module *M) const {
49420b57cec5SDimitry Andric   if (!M)
49430b57cec5SDimitry Andric     M = getModuleFromVal(this);
49440b57cec5SDimitry Andric 
49450b57cec5SDimitry Andric   if (!PrintType)
49460b57cec5SDimitry Andric     if (printWithoutType(*this, O, nullptr, M))
49470b57cec5SDimitry Andric       return;
49480b57cec5SDimitry Andric 
49490b57cec5SDimitry Andric   SlotTracker Machine(
49500b57cec5SDimitry Andric       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
49510b57cec5SDimitry Andric   ModuleSlotTracker MST(Machine, M);
49520b57cec5SDimitry Andric   printAsOperandImpl(*this, O, PrintType, MST);
49530b57cec5SDimitry Andric }
49540b57cec5SDimitry Andric 
49550b57cec5SDimitry Andric void Value::printAsOperand(raw_ostream &O, bool PrintType,
49560b57cec5SDimitry Andric                            ModuleSlotTracker &MST) const {
49570b57cec5SDimitry Andric   if (!PrintType)
49580b57cec5SDimitry Andric     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
49590b57cec5SDimitry Andric       return;
49600b57cec5SDimitry Andric 
49610b57cec5SDimitry Andric   printAsOperandImpl(*this, O, PrintType, MST);
49620b57cec5SDimitry Andric }
49630b57cec5SDimitry Andric 
4964349cc55cSDimitry Andric /// Recursive version of printMetadataImpl.
4965349cc55cSDimitry Andric static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD,
4966349cc55cSDimitry Andric                                  AsmWriterContext &WriterCtx) {
4967349cc55cSDimitry Andric   formatted_raw_ostream OS(ROS);
4968349cc55cSDimitry Andric   WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true);
4969349cc55cSDimitry Andric 
4970349cc55cSDimitry Andric   auto *N = dyn_cast<MDNode>(&MD);
4971*5f757f3fSDimitry Andric   if (!N || isa<DIExpression>(MD))
4972349cc55cSDimitry Andric     return;
4973349cc55cSDimitry Andric 
4974349cc55cSDimitry Andric   OS << " = ";
4975349cc55cSDimitry Andric   WriteMDNodeBodyInternal(OS, N, WriterCtx);
4976349cc55cSDimitry Andric }
4977349cc55cSDimitry Andric 
4978349cc55cSDimitry Andric namespace {
4979349cc55cSDimitry Andric struct MDTreeAsmWriterContext : public AsmWriterContext {
4980349cc55cSDimitry Andric   unsigned Level;
4981349cc55cSDimitry Andric   // {Level, Printed string}
4982349cc55cSDimitry Andric   using EntryTy = std::pair<unsigned, std::string>;
4983349cc55cSDimitry Andric   SmallVector<EntryTy, 4> Buffer;
4984349cc55cSDimitry Andric 
4985349cc55cSDimitry Andric   // Used to break the cycle in case there is any.
4986349cc55cSDimitry Andric   SmallPtrSet<const Metadata *, 4> Visited;
4987349cc55cSDimitry Andric 
4988349cc55cSDimitry Andric   raw_ostream &MainOS;
4989349cc55cSDimitry Andric 
4990349cc55cSDimitry Andric   MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M,
4991349cc55cSDimitry Andric                          raw_ostream &OS, const Metadata *InitMD)
4992349cc55cSDimitry Andric       : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {}
4993349cc55cSDimitry Andric 
4994349cc55cSDimitry Andric   void onWriteMetadataAsOperand(const Metadata *MD) override {
499581ad6265SDimitry Andric     if (!Visited.insert(MD).second)
4996349cc55cSDimitry Andric       return;
4997349cc55cSDimitry Andric 
4998349cc55cSDimitry Andric     std::string Str;
4999349cc55cSDimitry Andric     raw_string_ostream SS(Str);
5000349cc55cSDimitry Andric     ++Level;
5001349cc55cSDimitry Andric     // A placeholder entry to memorize the correct
5002349cc55cSDimitry Andric     // position in buffer.
5003349cc55cSDimitry Andric     Buffer.emplace_back(std::make_pair(Level, ""));
5004349cc55cSDimitry Andric     unsigned InsertIdx = Buffer.size() - 1;
5005349cc55cSDimitry Andric 
5006349cc55cSDimitry Andric     printMetadataImplRec(SS, *MD, *this);
5007349cc55cSDimitry Andric     Buffer[InsertIdx].second = std::move(SS.str());
5008349cc55cSDimitry Andric     --Level;
5009349cc55cSDimitry Andric   }
5010349cc55cSDimitry Andric 
5011349cc55cSDimitry Andric   ~MDTreeAsmWriterContext() {
5012349cc55cSDimitry Andric     for (const auto &Entry : Buffer) {
5013349cc55cSDimitry Andric       MainOS << "\n";
5014349cc55cSDimitry Andric       unsigned NumIndent = Entry.first * 2U;
5015349cc55cSDimitry Andric       MainOS.indent(NumIndent) << Entry.second;
5016349cc55cSDimitry Andric     }
5017349cc55cSDimitry Andric   }
5018349cc55cSDimitry Andric };
5019349cc55cSDimitry Andric } // end anonymous namespace
5020349cc55cSDimitry Andric 
50210b57cec5SDimitry Andric static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
50220b57cec5SDimitry Andric                               ModuleSlotTracker &MST, const Module *M,
5023349cc55cSDimitry Andric                               bool OnlyAsOperand, bool PrintAsTree = false) {
50240b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
50250b57cec5SDimitry Andric 
50260b57cec5SDimitry Andric   TypePrinting TypePrinter(M);
50270b57cec5SDimitry Andric 
5028349cc55cSDimitry Andric   std::unique_ptr<AsmWriterContext> WriterCtx;
5029349cc55cSDimitry Andric   if (PrintAsTree && !OnlyAsOperand)
5030349cc55cSDimitry Andric     WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
5031349cc55cSDimitry Andric         &TypePrinter, MST.getMachine(), M, OS, &MD);
5032349cc55cSDimitry Andric   else
5033349cc55cSDimitry Andric     WriterCtx =
5034349cc55cSDimitry Andric         std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M);
5035349cc55cSDimitry Andric 
5036349cc55cSDimitry Andric   WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true);
50370b57cec5SDimitry Andric 
50380b57cec5SDimitry Andric   auto *N = dyn_cast<MDNode>(&MD);
5039*5f757f3fSDimitry Andric   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
50400b57cec5SDimitry Andric     return;
50410b57cec5SDimitry Andric 
50420b57cec5SDimitry Andric   OS << " = ";
5043349cc55cSDimitry Andric   WriteMDNodeBodyInternal(OS, N, *WriterCtx);
50440b57cec5SDimitry Andric }
50450b57cec5SDimitry Andric 
50460b57cec5SDimitry Andric void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
50470b57cec5SDimitry Andric   ModuleSlotTracker MST(M, isa<MDNode>(this));
50480b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
50490b57cec5SDimitry Andric }
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
50520b57cec5SDimitry Andric                               const Module *M) const {
50530b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
50540b57cec5SDimitry Andric }
50550b57cec5SDimitry Andric 
50560b57cec5SDimitry Andric void Metadata::print(raw_ostream &OS, const Module *M,
50570b57cec5SDimitry Andric                      bool /*IsForDebug*/) const {
50580b57cec5SDimitry Andric   ModuleSlotTracker MST(M, isa<MDNode>(this));
50590b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
50600b57cec5SDimitry Andric }
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
50630b57cec5SDimitry Andric                      const Module *M, bool /*IsForDebug*/) const {
50640b57cec5SDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
50650b57cec5SDimitry Andric }
50660b57cec5SDimitry Andric 
5067349cc55cSDimitry Andric void MDNode::printTree(raw_ostream &OS, const Module *M) const {
5068349cc55cSDimitry Andric   ModuleSlotTracker MST(M, true);
5069349cc55cSDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5070349cc55cSDimitry Andric                     /*PrintAsTree=*/true);
5071349cc55cSDimitry Andric }
5072349cc55cSDimitry Andric 
5073349cc55cSDimitry Andric void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST,
5074349cc55cSDimitry Andric                        const Module *M) const {
5075349cc55cSDimitry Andric   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false,
5076349cc55cSDimitry Andric                     /*PrintAsTree=*/true);
5077349cc55cSDimitry Andric }
5078349cc55cSDimitry Andric 
50790b57cec5SDimitry Andric void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
50800b57cec5SDimitry Andric   SlotTracker SlotTable(this);
50810b57cec5SDimitry Andric   formatted_raw_ostream OS(ROS);
50820b57cec5SDimitry Andric   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
50830b57cec5SDimitry Andric   W.printModuleSummaryIndex();
50840b57cec5SDimitry Andric }
50850b57cec5SDimitry Andric 
5086fe6060f1SDimitry Andric void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB,
5087fe6060f1SDimitry Andric                                        unsigned UB) const {
5088fe6060f1SDimitry Andric   SlotTracker *ST = MachineStorage.get();
5089fe6060f1SDimitry Andric   if (!ST)
5090fe6060f1SDimitry Andric     return;
5091fe6060f1SDimitry Andric 
5092fe6060f1SDimitry Andric   for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end()))
5093fe6060f1SDimitry Andric     if (I.second >= LB && I.second < UB)
5094fe6060f1SDimitry Andric       L.push_back(std::make_pair(I.second, I.first));
5095fe6060f1SDimitry Andric }
5096fe6060f1SDimitry Andric 
50970b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
50980b57cec5SDimitry Andric // Value::dump - allow easy printing of Values from the debugger.
50990b57cec5SDimitry Andric LLVM_DUMP_METHOD
51000b57cec5SDimitry Andric void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
51010b57cec5SDimitry Andric 
5102*5f757f3fSDimitry Andric // Value::dump - allow easy printing of Values from the debugger.
5103*5f757f3fSDimitry Andric LLVM_DUMP_METHOD
5104*5f757f3fSDimitry Andric void DPMarker::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5105*5f757f3fSDimitry Andric 
5106*5f757f3fSDimitry Andric // Value::dump - allow easy printing of Values from the debugger.
5107*5f757f3fSDimitry Andric LLVM_DUMP_METHOD
5108*5f757f3fSDimitry Andric void DPValue::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
5109*5f757f3fSDimitry Andric 
51100b57cec5SDimitry Andric // Type::dump - allow easy printing of Types from the debugger.
51110b57cec5SDimitry Andric LLVM_DUMP_METHOD
51120b57cec5SDimitry Andric void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric // Module::dump() - Allow printing of Modules from the debugger.
51150b57cec5SDimitry Andric LLVM_DUMP_METHOD
51160b57cec5SDimitry Andric void Module::dump() const {
51170b57cec5SDimitry Andric   print(dbgs(), nullptr,
51180b57cec5SDimitry Andric         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
51190b57cec5SDimitry Andric }
51200b57cec5SDimitry Andric 
51210b57cec5SDimitry Andric // Allow printing of Comdats from the debugger.
51220b57cec5SDimitry Andric LLVM_DUMP_METHOD
51230b57cec5SDimitry Andric void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
51240b57cec5SDimitry Andric 
51250b57cec5SDimitry Andric // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
51260b57cec5SDimitry Andric LLVM_DUMP_METHOD
51270b57cec5SDimitry Andric void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
51280b57cec5SDimitry Andric 
51290b57cec5SDimitry Andric LLVM_DUMP_METHOD
51300b57cec5SDimitry Andric void Metadata::dump() const { dump(nullptr); }
51310b57cec5SDimitry Andric 
51320b57cec5SDimitry Andric LLVM_DUMP_METHOD
51330b57cec5SDimitry Andric void Metadata::dump(const Module *M) const {
51340b57cec5SDimitry Andric   print(dbgs(), M, /*IsForDebug=*/true);
51350b57cec5SDimitry Andric   dbgs() << '\n';
51360b57cec5SDimitry Andric }
51370b57cec5SDimitry Andric 
5138349cc55cSDimitry Andric LLVM_DUMP_METHOD
5139349cc55cSDimitry Andric void MDNode::dumpTree() const { dumpTree(nullptr); }
5140349cc55cSDimitry Andric 
5141349cc55cSDimitry Andric LLVM_DUMP_METHOD
5142349cc55cSDimitry Andric void MDNode::dumpTree(const Module *M) const {
5143349cc55cSDimitry Andric   printTree(dbgs(), M);
5144349cc55cSDimitry Andric   dbgs() << '\n';
5145349cc55cSDimitry Andric }
5146349cc55cSDimitry Andric 
51470b57cec5SDimitry Andric // Allow printing of ModuleSummaryIndex from the debugger.
51480b57cec5SDimitry Andric LLVM_DUMP_METHOD
51490b57cec5SDimitry Andric void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
51500b57cec5SDimitry Andric #endif
5151